Skip to main content

prjcombine_entity/
bundle_map.rs

1//! A map where each key-value pair is assigned a contiguous range of IDs.
2use crate::map::Entry;
3use crate::part_map::DuplicateKeyError;
4use crate::{EntityId, EntityMap, EntityPartVec, EntityRange, entity_id_u32};
5#[cfg(feature = "bincode")]
6use ::bincode::{Decode, Encode};
7
8/// Indices occupied by a given bundle.
9#[derive(Copy, Clone, Debug, PartialEq, Eq)]
10#[cfg_attr(feature = "bincode", derive(Encode, Decode))]
11pub enum EntityBundleIndices<I: EntityId> {
12    /// Singular index occupied by a unit-shaped bundle.
13    Single(I),
14    /// Range of indices occupied by an array-shaped bundle.
15    Array(EntityRange<I>),
16}
17
18impl<I: EntityId> From<I> for EntityBundleIndices<I> {
19    fn from(value: I) -> Self {
20        EntityBundleIndices::Single(value)
21    }
22}
23
24impl<I: EntityId> From<EntityRange<I>> for EntityBundleIndices<I> {
25    fn from(value: EntityRange<I>) -> Self {
26        EntityBundleIndices::Array(value)
27    }
28}
29
30/// An index within a particular bundle.
31#[derive(Copy, Clone, Debug, PartialEq, Eq)]
32pub enum EntityBundleItemIndex {
33    /// The bundle is unit-shaped, thus we shall meow no further of indices within it.
34    Single,
35    /// The bundle is array-shaped.
36    Array {
37        /// The index within the array.
38        index: usize,
39        /// The total size of the array.
40        total: usize,
41    },
42}
43
44entity_id_u32!(BundleId, BundleTag tag, "BUNDLE");
45
46/// A map where each key-value pair is assigned a contiguous range of IDs.
47///
48/// An `EntityBundleMap` is a collection of *bundles*. Each bundle consists of a key, a value,
49/// and a *range* of IDs assigned to it. The amount of IDs assigned to a bundle is determined by
50/// its *shape*: an array of a specified size, or just a single unit.
51///
52/// Note that we distinguish between a *single unit* and *an array of size one*. This is
53/// intentional, as this datastructure is used to implement data models that make this distinction,
54/// much like Rust makes a distinction between `u32` and `[u32; 1]`.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct EntityBundleMap<I: EntityId, T> {
57    ids: EntityPartVec<I, BundleId>,
58    bundles: EntityMap<BundleId, String, (EntityBundleIndices<I>, T)>,
59}
60
61impl<I: EntityId, T> EntityBundleMap<I, T> {
62    pub fn new() -> Self {
63        Self {
64            ids: Default::default(),
65            bundles: Default::default(),
66        }
67    }
68
69    pub fn is_empty(&self) -> bool {
70        self.ids.is_empty()
71    }
72
73    pub fn ids(&self) -> impl DoubleEndedIterator<Item = I> + '_ {
74        self.ids.ids()
75    }
76
77    /// Retrieve a bundle by its key.
78    pub fn get(&self, key: &str) -> Option<(EntityBundleIndices<I>, &T)> {
79        let (_, (idx, val)) = self.bundles.get(key)?;
80        Some((*idx, val))
81    }
82
83    pub fn get_mut(&mut self, key: &str) -> Option<(EntityBundleIndices<I>, &mut T)> {
84        let (_, (idx, val)) = self.bundles.get_mut(key)?;
85        Some((*idx, val))
86    }
87
88    pub fn contains_key(&self, key: &str) -> bool {
89        self.bundles.contains_key(key)
90    }
91
92    /// Given an ID, returns the key of the bundle which owns that ID, as well as the particular
93    /// position within the bundle that corresponds to the ID.
94    pub fn key(&self, id: I) -> (&str, EntityBundleItemIndex) {
95        let idx = self.ids[id];
96        let key = self.bundles.key(idx);
97        let (bidx, _) = self.bundles[idx];
98        match bidx {
99            EntityBundleIndices::Single(sid) => {
100                assert_eq!(id, sid);
101                (key, EntityBundleItemIndex::Single)
102            }
103            EntityBundleIndices::Array(range) => (
104                key,
105                EntityBundleItemIndex::Array {
106                    index: range.index_of(id).unwrap(),
107                    total: range.len(),
108                },
109            ),
110        }
111    }
112
113    /// Insert a bundle.
114    pub fn insert(
115        &mut self,
116        ids: impl Into<EntityBundleIndices<I>>,
117        name: String,
118        value: T,
119    ) -> Result<(), DuplicateKeyError> {
120        let ids = ids.into();
121        match self.bundles.entry(name) {
122            Entry::Occupied(_) => Err(DuplicateKeyError),
123            Entry::Vacant(e) => {
124                match ids {
125                    EntityBundleIndices::Single(id) => {
126                        if self.ids.contains_id(id) {
127                            return Err(DuplicateKeyError);
128                        }
129                        self.ids.insert(id, e.index());
130                    }
131                    EntityBundleIndices::Array(range) => {
132                        for id in range {
133                            if self.ids.contains_id(id) {
134                                return Err(DuplicateKeyError);
135                            }
136                        }
137                        for id in range {
138                            self.ids.insert(id, e.index());
139                        }
140                    }
141                }
142                e.insert((ids, value));
143                Ok(())
144            }
145        }
146    }
147
148    pub fn iter(&self) -> impl Iterator<Item = (I, &str, EntityBundleItemIndex, &T)> {
149        self.ids.ids().map(|id| {
150            let (idx, name) = self.key(id);
151            (id, idx, name, &self[id])
152        })
153    }
154
155    pub fn bundles(&self) -> impl Iterator<Item = (EntityBundleIndices<I>, &str, &T)> {
156        self.bundles
157            .iter()
158            .map(|(_, k, (i, v))| (*i, k.as_str(), v))
159    }
160
161    pub fn bundles_mut(&mut self) -> impl Iterator<Item = (EntityBundleIndices<I>, &str, &mut T)> {
162        self.bundles
163            .iter_mut()
164            .map(|(_, k, (i, v))| (*i, k.as_str(), v))
165    }
166
167    pub fn into_bundles(self) -> impl Iterator<Item = (EntityBundleIndices<I>, String, T)> {
168        self.bundles.into_iter().map(|(_, k, (i, v))| (i, k, v))
169    }
170}
171
172impl<I: EntityId, T> Default for EntityBundleMap<I, T> {
173    fn default() -> Self {
174        Self::new()
175    }
176}
177
178impl<I: EntityId, T> core::ops::Index<I> for EntityBundleMap<I, T> {
179    type Output = T;
180
181    fn index(&self, index: I) -> &Self::Output {
182        let idx = self.ids[index];
183        &self.bundles[idx].1
184    }
185}
186
187impl<I: EntityId, T> core::ops::IndexMut<I> for EntityBundleMap<I, T> {
188    fn index_mut(&mut self, index: I) -> &mut Self::Output {
189        let idx = self.ids[index];
190        &mut self.bundles[idx].1
191    }
192}
193
194#[cfg(feature = "bincode")]
195mod bincode;