1pub mod prelude;
6
7use crate::prelude::*;
8use sparse_slot::SparseSlot;
9use std::fmt::{Debug, Formatter};
10use swamp_resource::prelude::*;
11use tracing::{debug, trace};
12
13#[derive(Resource)]
14pub struct Assets<A: Asset> {
15 storage: SparseSlot<A>,
16}
17
18impl<A: Asset> Debug for Assets<A> {
19 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
20 write!(f, "Assets capacity: {}", self.storage.len())
21 }
22}
23
24impl<A: Asset> Default for Assets<A> {
25 fn default() -> Self {
26 Self {
27 storage: SparseSlot::<A>::new(1024),
28 }
29 }
30}
31
32impl<A: Asset> Assets<A> {
33 #[must_use]
34 pub fn new(capacity: usize) -> Self {
35 Self {
36 storage: SparseSlot::new(capacity),
37 }
38 }
39
40 pub fn set(&mut self, id: &Id<A>, asset: A) {
42 debug!(id=%id,asset=?asset, "setting asset");
43 self.storage
44 .try_set(to_slot_map_id(id), asset)
45 .expect("internal error");
46 }
47
48 pub fn set_raw(&mut self, id: RawWeakId, asset: A) {
49 debug!(id=%id,asset=?asset, "setting asset");
50 self.storage
51 .try_set(to_slot_map_id_from_raw(id), asset)
52 .expect("internal error");
53 }
54
55 pub fn remove(&mut self, id: &Id<A>) {
56 self.storage.remove(to_slot_map_id(id));
57 }
58
59 #[must_use]
60 pub fn get(&self, id: &Id<A>) -> Option<&A> {
61 self.storage.get(to_slot_map_id(id))
62 }
63
64 pub fn get_weak(&self, weak_id: WeakId<A>) -> Option<&A> {
65 self.storage.get(to_slot_map_id_from_weak(weak_id))
66 }
67
68 #[must_use]
71 pub fn fetch(&self, id: &Id<A>) -> &A {
72 trace!(id=%id, "fetch asset");
73 self.storage.get(to_slot_map_id(id)).unwrap()
74 }
75
76 #[must_use]
77 pub fn get_mut(&mut self, id: &Id<A>) -> Option<&mut A> {
78 trace!(id=%id, "get_mut asset");
79 self.storage.get_mut(to_slot_map_id(id))
80 }
81
82 #[must_use]
83 pub fn contains(&self, id: &Id<A>) -> bool {
84 self.get(id).is_some()
85 }
86
87 #[must_use]
106 pub fn len(&self) -> usize {
107 self.storage.len()
108 }
109
110 #[must_use]
111 pub fn is_empty(&self) -> bool {
112 self.storage.is_empty()
113 }
114}
115
116fn to_slot_map_id<A: Asset>(typed_id: &Id<A>) -> sparse_slot::Id {
117 let raw_id_type: RawWeakId = typed_id.into();
118
119 to_slot_map_id_from_raw(raw_id_type)
120}
121
122fn to_slot_map_id_from_weak<A: Asset>(raw_id_type: WeakId<A>) -> sparse_slot::Id {
123 let raw_id: RawWeakId = raw_id_type.into();
124
125 to_slot_map_id_from_raw(raw_id)
126}
127
128fn to_slot_map_id_from_raw(raw_id_type: RawWeakId) -> sparse_slot::Id {
129 let raw_id: RawAssetId = raw_id_type.into();
130
131 sparse_slot::Id::new(raw_id.index as usize, raw_id.generation)
132}