avian3d/data_structures/
sparse_secondary_map.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! A map for associating data with previously stored entities in a generational arena.
//!
//! This is an adaptation of [`slotmap::SparseSecondaryMap`], tailored for Avian.
//! Some modifications include:
//!
//! - The key is always an [`Entity`] instead of a generic key type.
//! - Much more minimalistic. No entry API or iterators.
//! - `no_std` compatible.
//!
//! [`slotmap::SparseSecondaryMap`]: https://docs.rs/slotmap/1.0.7/slotmap/struct.SparseSecondaryMap.html

use alloc::collections::TryReserveError;
use bevy::platform::hash::RandomState;
use core::mem::MaybeUninit;
use std::collections::hash_map::{self, HashMap};
use std::hash;

use bevy::ecs::entity::Entity;

#[derive(Debug, Clone)]
struct Slot<T> {
    generation: u32,
    value: T,
}

/// Sparse secondary map for associating data with previously stored entities
/// in a generational arena.
#[derive(Debug, Clone)]
pub struct SparseSecondaryEntityMap<V, S: hash::BuildHasher = RandomState> {
    slots: HashMap<u32, Slot<V>, S>,
}

impl<V> SparseSecondaryEntityMap<V, hash_map::RandomState> {
    /// Constructs a new, empty [`SparseSecondaryEntityMap`].
    #[inline]
    pub fn new() -> Self {
        Self::with_capacity(0)
    }

    /// Creates an empty [`SparseSecondaryEntityMap`] with the given capacity of slots.
    ///
    /// The secondary map will not reallocate until it holds at least `capacity`
    /// slots.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            slots: HashMap::with_capacity(capacity),
        }
    }
}

/// Returns if a is an older generation than b, taking into account wrapping of
/// generations.
fn is_older_generation(a: u32, b: u32) -> bool {
    let diff = a.wrapping_sub(b);
    diff >= (1 << 31)
}

impl<V, S: hash::BuildHasher> SparseSecondaryEntityMap<V, S> {
    /// Creates an empty [`SparseSecondaryEntityMap`] which will use the given hash
    /// builder to hash keys.
    ///
    /// The secondary map will not reallocate until it holds at least `capacity`
    /// slots.
    #[inline]
    pub fn with_hasher(hash_builder: S) -> Self {
        Self {
            slots: HashMap::with_hasher(hash_builder),
        }
    }

    /// Creates an empty [`SparseSecondaryEntityMap`] with the given capacity of slots,
    /// using `hash_builder` to hash the keys.
    ///
    /// The secondary map will not reallocate until it holds at least `capacity`
    /// slots.
    #[inline]
    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
        Self {
            slots: HashMap::with_capacity_and_hasher(capacity, hash_builder),
        }
    }

    /// Returns the number of elements in the secondary map.
    #[inline]
    pub fn len(&self) -> usize {
        self.slots.len()
    }

    /// Returns if the secondary map is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.slots.is_empty()
    }

    /// Returns the number of elements the [`SparseSecondaryEntityMap`] can hold without
    /// reallocating.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.slots.capacity()
    }

    /// Reserves capacity for at least `additional` more slots in the
    /// [`SparseSecondaryEntityMap`]. The collection may reserve more space to avoid
    /// frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the new allocation size overflows [`usize`].
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.slots.reserve(additional);
    }

    /// Tries to reserve capacity for at least `additional` more slots in the
    /// [`SparseSecondaryEntityMap`].  The collection may reserve more space to avoid
    /// frequent reallocations.
    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.slots.try_reserve(additional)
    }

    /// Returns `true` if the secondary map contains the given `entity`.
    #[inline]
    pub fn contains(&self, entity: Entity) -> bool {
        self.slots
            .get(&entity.index())
            .is_some_and(|slot| slot.generation == entity.generation())
    }

    /// Inserts a value into the secondary map at the given `entity`.
    ///
    /// Returns [`None`] if this entity was not present in the map,
    /// and the old value otherwise.
    #[inline]
    pub fn insert(&mut self, entity: Entity, value: V) -> Option<V> {
        if entity == Entity::PLACEHOLDER {
            return None;
        }

        let (index, generation) = (entity.index(), entity.generation());

        if let Some(slot) = self.slots.get_mut(&index) {
            if slot.generation == generation {
                return Some(core::mem::replace(&mut slot.value, value));
            }

            // Don't replace existing newer values.
            if is_older_generation(generation, slot.generation) {
                return None;
            }

            *slot = Slot { generation, value };

            return None;
        }

        self.slots.insert(index, Slot { generation, value });

        None
    }

    /// Removes a entity from the secondary map, returning the value at the entity if
    /// the entity was not previously removed.
    #[inline]
    pub fn remove(&mut self, entity: Entity) -> Option<V> {
        if let hash_map::Entry::Occupied(entry) = self.slots.entry(entity.index()) {
            if entry.get().generation == entity.generation() {
                return Some(entry.remove_entry().1.value);
            }
        }

        None
    }

    /// Clears the secondary map. Keeps the allocated memory for reuse.
    #[inline]
    pub fn clear(&mut self) {
        self.slots.clear();
    }

    /// Returns a reference to the value corresponding to the entity.
    #[inline]
    pub fn get(&self, entity: Entity) -> Option<&V> {
        self.slots
            .get(&entity.index())
            .filter(|slot| slot.generation == entity.generation())
            .map(|slot| &slot.value)
    }

    /// Returns a reference to the value corresponding to the entity without
    /// version or bounds checking.
    ///
    /// # Safety
    ///
    /// This should only be used if `contains(entity)` is true. Otherwise it is
    /// potentially unsafe.
    #[inline]
    pub unsafe fn get_unchecked(&self, entity: Entity) -> &V {
        debug_assert!(self.contains(entity));
        self.get(entity).unwrap_unchecked()
    }

    /// Returns a mutable reference to the value corresponding to the entity.
    #[inline]
    pub fn get_mut(&mut self, entity: Entity) -> Option<&mut V> {
        self.slots
            .get_mut(&entity.index())
            .filter(|slot| slot.generation == entity.generation())
            .map(|slot| &mut slot.value)
    }

    /// Returns a mutable reference to the value corresponding to the entity
    /// without version or bounds checking.
    ///
    /// # Safety
    ///
    /// This should only be used if `contains(entity)` is true. Otherwise it is
    /// potentially unsafe.
    #[inline]
    pub unsafe fn get_unchecked_mut(&mut self, entity: Entity) -> &mut V {
        debug_assert!(self.contains(entity));
        self.get_mut(entity).unwrap_unchecked()
    }

    /// Returns the value corresponding to the entity if it exists, otherwise inserts
    /// the value returned by `f` and returns it.
    #[inline]
    pub fn get_or_insert_with<F>(&mut self, entity: Entity, f: F) -> V
    where
        F: FnOnce() -> V,
        V: Clone + Copy,
    {
        if let Some(slot) = self
            .slots
            .get(&entity.index())
            .filter(|s| s.generation == entity.generation())
        {
            slot.value
        } else {
            let value = f();
            self.insert(entity, value);
            value
        }
    }

    /// Returns mutable references to the values corresponding to the given
    /// keys. All keys must be valid and disjoint, otherwise `None` is returned.
    #[inline]
    pub fn get_disjoint_mut<const N: usize>(
        &mut self,
        entities: [Entity; N],
    ) -> Option<[&mut V; N]> {
        // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
        // safe because the type we are claiming to have initialized here is a
        // bunch of `MaybeUninit`s, which do not require initialization.
        let mut ptrs: [MaybeUninit<*mut V>; N] = unsafe { MaybeUninit::uninit().assume_init() };

        let mut i = 0;
        while i < N {
            let entity = entities[i];

            match self.slots.get_mut(&entity.index()) {
                Some(Slot { generation, value }) if *generation == entity.generation() => {
                    // This entity is valid, and the slot is occupied. Temporarily
                    // make the generation even so duplicate keys would show up as
                    // invalid, since keys always have an odd generation. This
                    // gives us a linear time disjointness check.
                    ptrs[i] = MaybeUninit::new(&mut *value);
                    *generation ^= 1;
                }

                _ => break,
            }

            i += 1;
        }

        // Undo temporary even versions.
        for entity in &entities[0..i] {
            match self.slots.get_mut(&entity.index()) {
                Some(Slot { generation, .. }) => {
                    *generation ^= 1;
                }
                _ => unsafe { core::hint::unreachable_unchecked() },
            }
        }

        if i == N {
            // All were valid and disjoint.
            Some(unsafe { core::mem::transmute_copy::<_, [&mut V; N]>(&ptrs) })
        } else {
            None
        }
    }

    /// Returns mutable references to the values corresponding to the given
    /// keys. All keys must be valid and disjoint.
    ///
    /// # Safety
    ///
    /// This should only be used if `contains(entity)` is true for every given
    /// entity and no two keys are equal. Otherwise it is potentially unsafe.
    #[inline]
    pub unsafe fn get_disjoint_unchecked_mut<const N: usize>(
        &mut self,
        entities: [Entity; N],
    ) -> [&mut V; N] {
        // Safe, see get_disjoint_mut.
        let mut ptrs: [MaybeUninit<*mut V>; N] = MaybeUninit::uninit().assume_init();
        for i in 0..N {
            ptrs[i] = MaybeUninit::new(self.get_unchecked_mut(entities[i]));
        }
        core::mem::transmute_copy::<_, [&mut V; N]>(&ptrs)
    }
}

impl<V, S> Default for SparseSecondaryEntityMap<V, S>
where
    S: hash::BuildHasher + Default,
{
    fn default() -> Self {
        Self::with_hasher(Default::default())
    }
}