Skip to main content

ferroui_base/platform/
i_optional_feature_provider.rs

1use std::any::{Any, TypeId};
2use std::rc::Rc;
3use std::sync::Arc;
4
5/// Something that can expose optional, backend-specific features by type.
6///
7/// Features are looked up by the `TypeId` of the feature's type, which may be
8/// a trait object type (`TypeId::of::<dyn IFoo>()`); the returned value then
9/// holds an `Rc<dyn IFoo>`, or an `Arc<dyn IFoo>` for a feature that is
10/// shared by threads.
11pub trait IOptionalFeatureProvider {
12    /// Queries for an optional feature.
13    fn try_get_feature(&self, feature_type: TypeId) -> Option<Rc<dyn Any>>;
14}
15
16impl dyn IOptionalFeatureProvider + '_ {
17    /// Queries for an optional feature registered as `Rc<T>`.
18    pub fn try_get<T: ?Sized + 'static>(&self) -> Option<Rc<T>> {
19        let feature = self.try_get_feature(TypeId::of::<T>())?;
20        feature.downcast_ref::<Rc<T>>().cloned()
21    }
22
23    /// Queries for an optional feature registered as `Arc<T>`: one that is
24    /// shared by threads.
25    pub fn try_get_shared<T: ?Sized + 'static>(&self) -> Option<Arc<T>> {
26        let feature = self.try_get_feature(TypeId::of::<T>())?;
27        feature.downcast_ref::<Arc<T>>().cloned()
28    }
29}