oxygengine_core/assets/
asset.rs

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