Skip to main content

goud_engine/assets/asset/
asset_id.rs

1//! Runtime type identifier for asset types.
2
3use super::trait_def::Asset;
4use std::any::TypeId;
5use std::fmt;
6use std::hash::Hash;
7
8/// Unique identifier for an asset type at runtime.
9///
10/// `AssetId` wraps a `TypeId` to identify asset types. This is used internally
11/// for asset storage, loader registration, and type-safe access.
12///
13/// Unlike [`Handle`](crate::core::handle::Handle), which identifies a specific
14/// asset instance, `AssetId` identifies an asset *type*.
15///
16/// # Example
17///
18/// ```
19/// use goud_engine::assets::{Asset, AssetId};
20///
21/// struct Texture { /* ... */ }
22/// impl Asset for Texture {}
23///
24/// struct Mesh { /* ... */ }
25/// impl Asset for Mesh {}
26///
27/// let tex_id = AssetId::of::<Texture>();
28/// let mesh_id = AssetId::of::<Mesh>();
29///
30/// assert_ne!(tex_id, mesh_id);
31/// assert_eq!(tex_id, AssetId::of::<Texture>());
32/// ```
33///
34/// # FFI Considerations
35///
36/// `AssetId` is NOT FFI-safe (contains `TypeId`). For FFI, use the
37/// `AssetType` enum or string-based type names.
38#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
39pub struct AssetId(TypeId);
40
41impl AssetId {
42    /// Returns the `AssetId` for a specific asset type.
43    ///
44    /// # Example
45    ///
46    /// ```
47    /// use goud_engine::assets::{Asset, AssetId};
48    ///
49    /// struct MyAsset;
50    /// impl Asset for MyAsset {}
51    ///
52    /// let id = AssetId::of::<MyAsset>();
53    /// ```
54    #[inline]
55    pub fn of<T: Asset>() -> Self {
56        Self(TypeId::of::<T>())
57    }
58
59    /// Returns the `AssetId` for any `'static` type.
60    ///
61    /// This is useful for internal operations where the type may not
62    /// implement `Asset` yet (e.g., during registration).
63    ///
64    /// # Example
65    ///
66    /// ```
67    /// use goud_engine::assets::AssetId;
68    ///
69    /// let id = AssetId::of_raw::<String>();
70    /// ```
71    #[inline]
72    pub fn of_raw<T: 'static>() -> Self {
73        Self(TypeId::of::<T>())
74    }
75
76    /// Returns the underlying `TypeId`.
77    ///
78    /// # Example
79    ///
80    /// ```
81    /// use goud_engine::assets::{Asset, AssetId};
82    /// use std::any::TypeId;
83    ///
84    /// struct MyAsset;
85    /// impl Asset for MyAsset {}
86    ///
87    /// let id = AssetId::of::<MyAsset>();
88    /// assert_eq!(id.type_id(), TypeId::of::<MyAsset>());
89    /// ```
90    #[inline]
91    pub fn type_id(&self) -> TypeId {
92        self.0
93    }
94}
95
96impl fmt::Debug for AssetId {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        write!(f, "AssetId({:?})", self.0)
99    }
100}
101
102impl fmt::Display for AssetId {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        write!(f, "AssetId({:?})", self.0)
105    }
106}