1use super::asset::{Asset, AssetTrait};
4use crate::asset_id::AssetId;
5use std::{collections::BTreeMap, fmt::Debug, sync::Arc};
6use typemap::{Key, ShareCloneMap};
7use uuid::Uuid;
8
9#[derive(Debug, Clone, Default)]
10pub struct Collection<T: AssetTrait>(BTreeMap<Uuid, Arc<Asset<T>>>);
11
12impl<T: AssetTrait + 'static> Key for Collection<T> {
13 type Value = Collection<T>;
14}
15
16impl<T: AssetTrait> Collection<T> {
17 pub(crate) fn assets(&self) -> Vec<Arc<Asset<T>>> {
19 self.0.values().cloned().collect()
20 }
21
22 pub fn get(&self, id: &AssetId<T>) -> Option<&Arc<Asset<T>>> {
23 self.0.get(&id.id)
24 }
25
26 pub fn shared(&self) -> impl Iterator<Item = &Arc<Asset<T>>> {
28 self.0.values()
29 }
30
31 pub fn insert_shared(&mut self, asset: Arc<Asset<T>>) {
33 self.0.insert(asset.id.id, asset);
34 }
35
36 pub fn set_asset(&mut self, asset: Asset<T>) {
38 self.0.insert(asset.id.id, Arc::new(asset));
39 }
40
41 pub fn delete_asset(&mut self, id: AssetId<T>) {
42 self.0.remove(&id.id);
43 }
44
45 pub fn from_assets(assets: BTreeMap<Uuid, Arc<Asset<T>>>) -> Self {
47 Self(assets)
48 }
49}
50
51#[derive(Clone)]
53pub struct Collections {
54 map: ShareCloneMap,
55}
56
57impl Default for Collections {
58 fn default() -> Self {
59 Self {
60 map: ShareCloneMap::custom(),
61 }
62 }
63}
64
65impl Debug for Collections {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 f.debug_struct("Collections").finish_non_exhaustive()
68 }
69}
70
71impl Collections {
72 pub fn insert<T: AssetTrait>(&mut self, collection: Collection<T>) {
73 self.map.insert::<Collection<T>>(collection);
74 }
75
76 pub fn get<T: AssetTrait>(&self) -> Option<&Collection<T>> {
77 self.map.get::<Collection<T>>()
78 }
79
80 pub fn get_mut<T: AssetTrait>(&mut self) -> &mut Collection<T> {
81 self.map
82 .entry::<Collection<T>>()
83 .or_insert_with(Default::default)
84 }
85}