hassium_core/assets/
asset.rs

1use crate::id::ID;
2use std::{any::Any, mem::replace};
3
4pub type AssetID = ID<()>;
5
6pub struct Asset {
7    id: AssetID,
8    protocol: String,
9    path: String,
10    data: Box<dyn Any + Send + Sync>,
11}
12
13impl Asset {
14    pub fn new(protocol: &str, path: &str, data: Box<dyn Any + Send + Sync>) -> Self {
15        Self {
16            id: AssetID::new(),
17            protocol: protocol.to_owned(),
18            path: path.to_owned(),
19            data,
20        }
21    }
22
23    pub fn id(&self) -> AssetID {
24        self.id
25    }
26
27    pub fn protocol(&self) -> &str {
28        &self.protocol
29    }
30
31    pub fn path(&self) -> &str {
32        &self.path
33    }
34
35    pub fn to_full_path(&self) -> String {
36        format!("{}://{}", self.protocol, self.path)
37    }
38
39    pub fn is<T>(&self) -> bool
40    where
41        T: Any + Send + Sync,
42    {
43        self.data.is::<T>()
44    }
45
46    pub fn get<T>(&self) -> Option<&T>
47    where
48        T: Any + Send + Sync,
49    {
50        self.data.downcast_ref()
51    }
52
53    pub fn get_mut<T>(&mut self) -> Option<&mut T>
54    where
55        T: Any + Send + Sync,
56    {
57        self.data.downcast_mut()
58    }
59
60    pub fn set<T>(&mut self, data: T) -> Box<dyn Any + Send + Sync>
61    where
62        T: Any + Send + Sync,
63    {
64        replace(&mut self.data, Box::new(data))
65    }
66}