moduforge_state/
resource.rs

1use std::any::Any;
2use std::any::TypeId;
3use std::sync::Arc;
4
5pub trait Resource: Any + Send + Sync + 'static {}
6
7impl dyn Resource {
8    #[inline(always)]
9    fn is<T: Resource>(&self) -> bool {
10        self.type_id() == TypeId::of::<T>()
11    }
12
13    #[inline(always)]
14    #[allow(clippy::needless_lifetimes)]
15    pub fn downcast_arc<'a, T: Resource>(
16        self: &'a Arc<Self>
17    ) -> Option<&'a Arc<T>> {
18        if self.is::<T>() {
19            let ptr = self as *const Arc<_> as *const Arc<T>;
20            // TODO(piscisaureus): safety comment
21            #[allow(clippy::undocumented_unsafe_blocks)]
22            Some(unsafe { &*ptr })
23        } else {
24            None
25        }
26    }
27    #[inline(always)]
28    #[allow(clippy::needless_lifetimes)]
29    pub fn downcast<'a, T: Resource>(
30        self: &'a Box<Self>
31    ) -> Option<&'a Box<T>> {
32        if self.is::<T>() {
33            let ptr = self as *const Box<_> as *const Box<T>;
34            // TODO(piscisaureus): safety comment
35            #[allow(clippy::undocumented_unsafe_blocks)]
36            Some(unsafe { &*ptr })
37        } else {
38            None
39        }
40    }
41}