Skip to main content

pebble/assets/
storage.rs

1use slotmap::{SecondaryMap, SlotMap, new_key_type};
2use std::collections::HashMap;
3
4new_key_type! {
5    pub struct RawAssetHandle;
6}
7
8pub struct Assets<T: 'static + Send + Sync> {
9    storage: SlotMap<RawAssetHandle, T>,
10    handles: HashMap<String, RawAssetHandle>,
11    queue: Vec<RawAssetHandle>,
12}
13
14impl<T: 'static + Send + Sync> Assets<T> {
15    pub fn new() -> Self {
16        Self {
17            storage: SlotMap::with_key(),
18            handles: HashMap::new(),
19            queue: Vec::new(),
20        }
21    }
22
23    pub fn insert(&mut self, name: &str, asset: T) -> RawAssetHandle {
24        let handle = self.storage.insert(asset);
25        self.queue.push(handle);
26
27        if let Some(old) = self.handles.insert(name.to_string(), handle) {
28            self.storage.remove(old);
29            self.queue.retain(|h| *h != old);
30        }
31        handle
32    }
33
34    pub fn get(&self, handle: RawAssetHandle) -> Option<&T> {
35        self.storage.get(handle)
36    }
37
38    pub fn get_mut(&mut self, handle: RawAssetHandle) -> Option<&mut T> {
39        self.storage.get_mut(handle)
40    }
41
42    pub fn get_by_name(&self, name: &str) -> Option<&T> {
43        self.handles
44            .get(name)
45            .and_then(|&handle| self.storage.get(handle))
46    }
47
48    pub fn get_mut_by_name(&mut self, name: &str) -> Option<&mut T> {
49        let handle = self.handles.get(name).copied()?;
50        self.storage.get_mut(handle)
51    }
52
53    pub fn take_dirty(&mut self) -> Vec<RawAssetHandle> {
54        std::mem::take(&mut self.queue)
55    }
56
57    pub fn remove(&mut self, handle: RawAssetHandle) -> Option<T> {
58        let value = self.storage.remove(handle)?;
59
60        self.handles.retain(|_, h| *h != handle);
61        self.queue.retain(|h| *h != handle);
62
63        Some(value)
64    }
65
66    pub fn remove_by_name(&mut self, name: &str) -> Option<T> {
67        let handle = self.handles.remove(name)?;
68        self.storage.remove(handle)
69    }
70}
71
72pub struct GPUAssets<T: 'static + Send + Sync> {
73    storage: SecondaryMap<RawAssetHandle, T>,
74}
75
76impl<T: 'static + Send + Sync> GPUAssets<T> {
77    pub fn new() -> Self {
78        Self {
79            storage: SecondaryMap::new(),
80        }
81    }
82
83    pub fn insert(&mut self, handle: RawAssetHandle, asset: T) -> Option<T> {
84        self.storage.insert(handle, asset)
85    }
86
87    pub fn get(&self, handle: RawAssetHandle) -> Option<&T> {
88        self.storage.get(handle)
89    }
90
91    pub fn get_mut(&mut self, handle: RawAssetHandle) -> Option<&mut T> {
92        self.storage.get_mut(handle)
93    }
94
95    pub fn remove(&mut self, handle: RawAssetHandle) -> Option<T> {
96        self.storage.remove(handle)
97    }
98
99    pub fn contains(&self, handle: RawAssetHandle) -> bool {
100        self.storage.contains_key(handle)
101    }
102}