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 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>, } impl FacilityMap { pub fn new() -> FacilityMap { FacilityMap { facilities: BTreeMap::new() } } pub fn insert(&mut self, facility: F) { self.facilities.insert(F::FACILITY_TYPE, Box::new(facility)); } pub fn get(&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 } } }