about summary refs log tree commit diff
path: root/src/facility.rs
blob: ab74dd112e191e40feebb58e789563931315c045 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::error::Result;

use std::any::Any;
use std::borrow::BorrowMut;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::Mutex;

use bitflags::bitflags;

pub use envsys::EnvSys;

pub mod envsys;


pub trait Facility: Any {
  /*   The where clause here is to keep things dyn-compatible. You can see how
   * "new" can't be put in a vtable because it has no self parameter. Since dyn
   * doesn't have Sized, this is a cute way to say new() won't be called
   * through dyn and doesn't need to be in the vtable.
   *
   *   As far as why the compiler can't reach that conclusion on its own, we
   * have no specific information.
   */
  fn new() -> Result<Self> where Self: Sized;

  /*   Though it would be tidy to put this in TypeableFacility instead, we
   * can't, because we need it as part of performing a downcast, and in the
   * FacilityMap accessors we don't know that we have TypeableFacility until
   * after the downcast succeeds.
   */
  fn as_any_mut(&mut self) -> &mut dyn Any;
}

/* In order to keep Facility dyn-compatible, the constant is here instead. */
pub trait TypeableFacility: Facility {
  const FACILITY_TYPE: FacilityType;
}


bitflags! {
  #[derive(PartialEq, Eq, PartialOrd, Ord)]
  pub struct FacilityType: u32 {
    const ENVSYS = 0x00000001;
  }
}


/*   The wisdom of having this complexity is questionable, but it does work.
 * Notice that we don't wrap the individual items in Mutex. That's necessary
 * because our accessors need to do the downcast on their callers' behalf, and
 * they wouldn't be able to return a reference to inside a lock. Instead,
 * callers should wrap the entire FacilityMap in a coarse Mutex.
 */
pub struct FacilityMap {
  facilities: BTreeMap<FacilityType, Box<dyn Facility>>,
}

impl FacilityMap {
  pub fn new() -> FacilityMap {
    FacilityMap { facilities: BTreeMap::new() }
  }

  pub fn insert<F: Facility + TypeableFacility>(&mut self, facility: F) {
    self.facilities.insert(F::FACILITY_TYPE, Box::new(facility));
  }

  pub fn get<F: Facility + TypeableFacility>(&mut self) -> Option<&mut F> {
    if let Some(facility) = self.facilities.get_mut(&F::FACILITY_TYPE) {
      (*facility).as_mut().as_any_mut().downcast_mut()
    } else { None }
  }
}