swamp_assets/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/piot/swamp-render
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */
pub mod prelude;

use std::marker::PhantomData;
use swamp_slot_map::SlotMap;

pub trait Asset: 'static + Send + Sync {}

#[derive(Default)]
pub struct Assets<A: Asset> {
    storage: SlotMap<A>,
}

#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct Id<A: Asset> {
    slot_map_id: swamp_slot_map::Id,
    _phantom_data: PhantomData<A>,
}

impl<A: Asset> Assets<A> {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            storage: SlotMap::new(),
        }
    }

    #[must_use]
    pub fn insert(&mut self, asset: A) -> Id<A> {
        Id {
            slot_map_id: self.storage.insert(asset),
            _phantom_data: PhantomData,
        }
    }

    pub fn remove(&mut self, id: &Id<A>) {
        self.storage.remove(&id.slot_map_id);
    }

    #[must_use]
    pub fn get(&self, id: &Id<A>) -> Option<&A> {
        self.storage.get(&id.slot_map_id)
    }

    #[must_use]
    pub fn get_mut(&mut self, id: &Id<A>) -> Option<&mut A> {
        self.storage.get_mut(&id.slot_map_id)
    }

    #[must_use]
    pub fn contains(&self, id: &Id<A>) -> bool {
        self.get(id).is_some()
    }

    pub fn iter(&self) -> impl Iterator<Item = (Id<A>, &A)> {
        self.storage.iter().map(|(id, asset)| {
            (
                Id {
                    slot_map_id: id,
                    _phantom_data: Default::default(),
                },
                asset,
            )
        })
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.storage.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.storage.is_empty()
    }
}