id-slab 0.1.0

Dense Vec<Option<T>> storage for externally assigned integer ids.
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Dense storage for values keyed by externally assigned integer ids.
//!
//! [`IdSlab`] is a small map-shaped wrapper around `Vec<Option<V>>`.
//! It is useful when the key is already a dense index, such as a mesh id,
//! graph node id, compiler IR id, or entity id.
//!
//! The collection does not generate keys. Callers supply a key, and the key
//! maps to a slot with [`SlabKey::index`]. Iterators rebuild keys with
//! [`SlabKey::from_index`], so borrowed iteration yields `(K, &V)` instead of
//! `(&K, &V)`.

#![no_std]

extern crate alloc;

#[cfg(test)]
extern crate std;

use alloc::vec::Vec;
use core::{fmt, hash::Hash, marker::PhantomData};

#[cfg(feature = "serde")]
use serde::de::{MapAccess, Visitor};
#[cfg(feature = "serde")]
use serde::ser::SerializeMap;
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A key whose value maps to a dense slot index.
///
/// Implement this trait for small `Copy` id newtypes. The key's index must be
/// stable while the key is in use.
pub trait SlabKey: Copy + Eq + Hash {
    /// Returns the dense slot index for this key.
    fn index(self) -> usize;

    /// Reconstructs the key from a dense slot index.
    fn from_index(index: usize) -> Self;
}

impl SlabKey for usize {
    #[inline]
    fn index(self) -> usize {
        self
    }

    #[inline]
    fn from_index(index: usize) -> Self {
        index
    }
}

impl SlabKey for u32 {
    #[inline]
    fn index(self) -> usize {
        self as usize
    }

    #[inline]
    fn from_index(index: usize) -> Self {
        assert!(index <= u32::MAX as usize, "slot index does not fit in u32");
        index as u32
    }
}

/// Dense `Vec<Option<V>>` storage keyed by a [`SlabKey`].
///
/// The slab stores values at `key.index()`. Removed values leave empty slots.
/// Therefore, memory use follows the highest inserted index, not only the live
/// value count.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "facet", derive(facet::Facet))]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
pub struct IdSlab<K, V> {
    slots: Vec<Option<V>>,
    len: usize,
    #[cfg_attr(feature = "rkyv", rkyv(omit_bounds))]
    key: PhantomData<fn() -> K>,
}

impl<K: SlabKey, V> IdSlab<K, V> {
    /// Creates an empty slab.
    #[must_use]
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            len: 0,
            key: PhantomData,
        }
    }

    /// Creates an empty slab with storage for at least `capacity` slots.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            slots: Vec::with_capacity(capacity),
            len: 0,
            key: PhantomData,
        }
    }

    /// Returns the number of live values.
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the slab contains no live values.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the number of allocated slots.
    ///
    /// This count includes empty slots left by removal.
    #[must_use]
    pub fn slot_count(&self) -> usize {
        self.slots.len()
    }

    /// Returns `true` if `key` has a live value.
    #[must_use]
    pub fn contains_key(&self, key: K) -> bool {
        self.slots.get(key.index()).is_some_and(Option::is_some)
    }

    /// Returns the value for `key`.
    #[must_use]
    pub fn get(&self, key: K) -> Option<&V> {
        self.slots.get(key.index()).and_then(Option::as_ref)
    }

    /// Returns the mutable value for `key`.
    #[must_use]
    pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
        self.slots.get_mut(key.index()).and_then(Option::as_mut)
    }

    /// Inserts `value` at `key`.
    ///
    /// Returns the old value if the slot was occupied.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        let index = key.index();
        if index >= self.slots.len() {
            self.slots.resize_with(index + 1, || None);
        }

        let previous = self.slots[index].replace(value);
        if previous.is_none() {
            self.len += 1;
        }
        previous
    }

    /// Removes and returns the value for `key`.
    pub fn remove(&mut self, key: K) -> Option<V> {
        let previous = self.slots.get_mut(key.index()).and_then(Option::take);
        if previous.is_some() {
            self.len -= 1;
        }
        previous
    }

    /// Removes all values and all allocated slots.
    pub fn clear(&mut self) {
        self.slots.clear();
        self.len = 0;
    }

    /// Creates a slab from slots that are already in slot order.
    ///
    /// Trailing empty slots are removed.
    #[must_use]
    pub fn from_slots(mut slots: Vec<Option<V>>) -> Self {
        while slots.last().is_some_and(Option::is_none) {
            slots.pop();
        }

        let len = slots.iter().filter(|slot| slot.is_some()).count();
        Self {
            slots,
            len,
            key: PhantomData,
        }
    }

    /// Returns the slots, including empty slots.
    #[must_use]
    pub fn into_slots(self) -> Vec<Option<V>> {
        self.slots
    }

    /// Returns an iterator over live values in ascending key order.
    pub fn values(&self) -> impl Iterator<Item = &V> {
        self.slots.iter().filter_map(Option::as_ref)
    }

    /// Returns a mutable iterator over live values in ascending key order.
    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
        self.slots.iter_mut().filter_map(Option::as_mut)
    }

    /// Returns an iterator over live keys in ascending key order.
    pub fn keys(&self) -> impl Iterator<Item = K> + '_ {
        self.slots
            .iter()
            .enumerate()
            .filter(|(_, slot)| slot.is_some())
            .map(|(index, _)| K::from_index(index))
    }

    /// Returns an iterator over live key-value pairs in ascending key order.
    #[must_use]
    pub fn iter(&self) -> Iter<'_, K, V> {
        Iter {
            inner: self.slots.iter().enumerate(),
            key: PhantomData,
        }
    }

    /// Returns a mutable iterator over live key-value pairs in ascending key
    /// order.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (K, &mut V)> + '_ {
        self.slots
            .iter_mut()
            .enumerate()
            .filter_map(|(index, slot)| {
                slot.as_mut().map(|value| (K::from_index(index), value))
            })
    }

    /// Keeps only the values for which `f` returns `true`.
    pub fn retain(&mut self, mut f: impl FnMut(K, &mut V) -> bool) {
        self.slots.iter_mut().enumerate().for_each(|(index, slot)| {
            if let Some(value) = slot.as_mut() {
                let keep = f(K::from_index(index), value);
                if !keep {
                    *slot = None;
                    self.len -= 1;
                }
            }
        });
    }

    /// Returns the internal slot slice.
    ///
    /// Empty slots represent missing values.
    #[must_use]
    pub fn as_slots(&self) -> &[Option<V>] {
        &self.slots
    }

    /// Returns the mutable internal slot slice.
    ///
    /// Changing slot liveness through this slice can make `len` incorrect.
    /// Prefer [`IdSlab::insert`], [`IdSlab::remove`], or [`IdSlab::retain`].
    #[must_use]
    pub fn as_slots_mut(&mut self) -> &mut [Option<V>] {
        &mut self.slots
    }
}

impl<K: SlabKey, V> Default for IdSlab<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K: SlabKey, V> FromIterator<(K, V)> for IdSlab<K, V> {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut slab = Self::new();
        iter.into_iter().for_each(|(key, value)| {
            slab.insert(key, value);
        });
        slab
    }
}

impl<K: SlabKey, V> core::ops::Index<K> for IdSlab<K, V> {
    type Output = V;

    fn index(&self, key: K) -> &Self::Output {
        self.get(key).expect("IdSlab: no entry for key")
    }
}

impl<K: SlabKey, V> core::ops::IndexMut<K> for IdSlab<K, V> {
    fn index_mut(&mut self, key: K) -> &mut Self::Output {
        self.get_mut(key).expect("IdSlab: no entry for key")
    }
}

/// An iterator over live key-value pairs in ascending key order.
pub struct Iter<'a, K, V> {
    inner: core::iter::Enumerate<core::slice::Iter<'a, Option<V>>>,
    key: PhantomData<fn() -> K>,
}

impl<K, V> Clone for Iter<'_, K, V> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            key: PhantomData,
        }
    }
}

impl<K, V> fmt::Debug for Iter<'_, K, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Iter").finish_non_exhaustive()
    }
}

impl<'a, K: SlabKey, V> Iterator for Iter<'a, K, V> {
    type Item = (K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.by_ref().find_map(|(index, slot)| {
            slot.as_ref().map(|value| (K::from_index(index), value))
        })
    }
}

/// An owning iterator over live key-value pairs in ascending key order.
pub struct IntoIter<K, V> {
    inner: core::iter::Enumerate<alloc::vec::IntoIter<Option<V>>>,
    key: PhantomData<fn() -> K>,
}

impl<K, V> fmt::Debug for IntoIter<K, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("IntoIter").finish_non_exhaustive()
    }
}

impl<K: SlabKey, V> Iterator for IntoIter<K, V> {
    type Item = (K, V);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.by_ref().find_map(|(index, slot)| {
            slot.map(|value| (K::from_index(index), value))
        })
    }
}

impl<'a, K: SlabKey, V> IntoIterator for &'a IdSlab<K, V> {
    type IntoIter = Iter<'a, K, V>;
    type Item = (K, &'a V);

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<K: SlabKey, V> IntoIterator for IdSlab<K, V> {
    type IntoIter = IntoIter<K, V>;
    type Item = (K, V);

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            inner: self.slots.into_iter().enumerate(),
            key: PhantomData,
        }
    }
}

#[cfg(feature = "serde")]
impl<K, V> Serialize for IdSlab<K, V>
where
    K: SlabKey + Serialize,
    V: Serialize,
{
    fn serialize<S: Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(self.len))?;
        self.iter()
            .try_for_each(|(key, value)| map.serialize_entry(&key, value))?;
        map.end()
    }
}

#[cfg(feature = "serde")]
impl<'de, K, V> Deserialize<'de> for IdSlab<K, V>
where
    K: SlabKey + Deserialize<'de>,
    V: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        deserializer.deserialize_map(IdSlabVisitor {
            key: PhantomData,
            value: PhantomData,
        })
    }
}

#[cfg(feature = "serde")]
struct IdSlabVisitor<K, V> {
    key: PhantomData<fn() -> K>,
    value: PhantomData<fn() -> V>,
}

#[cfg(feature = "serde")]
impl<'de, K, V> Visitor<'de> for IdSlabVisitor<K, V>
where
    K: SlabKey + Deserialize<'de>,
    V: Deserialize<'de>,
{
    type Value = IdSlab<K, V>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a map from dense ids to values")
    }

    fn visit_map<A: MapAccess<'de>>(
        self,
        mut access: A,
    ) -> Result<Self::Value, A::Error> {
        let mut slab = access
            .size_hint()
            .map(IdSlab::with_capacity)
            .unwrap_or_default();

        while let Some((key, value)) = access.next_entry()? {
            slab.insert(key, value);
        }

        Ok(slab)
    }
}

#[cfg(test)]
mod tests {
    use alloc::{vec, vec::Vec};

    use super::*;

    #[cfg(feature = "serde")]
    use alloc::string::String;

    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    #[cfg_attr(feature = "facet", derive(facet::Facet))]
    #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
    #[cfg_attr(
        feature = "rkyv",
        derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
    )]
    #[cfg_attr(feature = "rkyv", rkyv(derive(Debug, Eq, PartialEq)))]
    struct NodeId(u32);

    impl SlabKey for NodeId {
        fn index(self) -> usize {
            self.0 as usize
        }

        fn from_index(index: usize) -> Self {
            NodeId(index as u32)
        }
    }

    #[test]
    fn insert_get_and_replace_use_the_key_index() {
        let mut slab = IdSlab::new();

        assert_eq!(slab.insert(NodeId(2), "a"), None);
        assert_eq!(slab.get(NodeId(2)), Some(&"a"));
        assert_eq!(slab.insert(NodeId(2), "b"), Some("a"));
        assert_eq!(slab.get(NodeId(2)), Some(&"b"));
        assert_eq!(slab.len(), 1);
        assert_eq!(slab.slot_count(), 3);
    }

    #[test]
    fn remove_leaves_an_empty_slot() {
        let mut slab = IdSlab::new();

        slab.insert(NodeId(3), "a");

        assert_eq!(slab.remove(NodeId(3)), Some("a"));
        assert_eq!(slab.get(NodeId(3)), None);
        assert_eq!(slab.len(), 0);
        assert_eq!(slab.slot_count(), 4);
    }

    #[test]
    fn iteration_is_in_ascending_key_order() {
        let slab = [(NodeId(3), "c"), (NodeId(1), "a"), (NodeId(2), "b")]
            .into_iter()
            .collect::<IdSlab<_, _>>();

        let keys = slab.keys().map(|key| key.0).collect::<Vec<_>>();
        let values = slab.values().copied().collect::<Vec<_>>();
        let pairs = slab
            .iter()
            .map(|(key, value)| (key.0, *value))
            .collect::<Vec<_>>();

        assert_eq!(keys, vec![1, 2, 3]);
        assert_eq!(values, vec!["a", "b", "c"]);
        assert_eq!(pairs, vec![(1, "a"), (2, "b"), (3, "c")]);
    }

    #[test]
    fn from_slots_drops_trailing_empty_slots() {
        let slab = IdSlab::<NodeId, _>::from_slots(vec![
            Some("a"),
            None,
            Some("c"),
            None,
        ]);

        assert_eq!(slab.len(), 2);
        assert_eq!(slab.slot_count(), 3);
        assert_eq!(slab.get(NodeId(0)), Some(&"a"));
        assert_eq!(slab.get(NodeId(1)), None);
        assert_eq!(slab.get(NodeId(2)), Some(&"c"));
    }

    #[test]
    fn retain_updates_length() {
        let mut slab = [(NodeId(0), 10), (NodeId(1), 20), (NodeId(2), 30)]
            .into_iter()
            .collect::<IdSlab<_, _>>();

        slab.retain(|key, value| {
            *value += 1;
            key.0 != 1
        });

        assert_eq!(slab.len(), 2);
        assert_eq!(slab.get(NodeId(0)), Some(&11));
        assert_eq!(slab.get(NodeId(1)), None);
        assert_eq!(slab.get(NodeId(2)), Some(&31));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_serializes_live_values_as_a_map() {
        let slab = [(NodeId(2), "b"), (NodeId(0), "a")]
            .into_iter()
            .collect::<IdSlab<_, _>>();

        let json = serde_json::to_string(&slab).expect("slab must serialize");
        let decoded = serde_json::from_str::<IdSlab<NodeId, String>>(&json)
            .expect("slab must deserialize");

        assert_eq!(decoded.get(NodeId(0)).map(String::as_str), Some("a"));
        assert_eq!(decoded.get(NodeId(1)), None);
        assert_eq!(decoded.get(NodeId(2)).map(String::as_str), Some("b"));
    }

    #[cfg(feature = "rkyv")]
    #[test]
    fn rkyv_round_trips_the_slot_representation() {
        use rkyv::rancor::Error;

        let slab = [(NodeId(0), 10), (NodeId(2), 30)]
            .into_iter()
            .collect::<IdSlab<_, _>>();

        let bytes = rkyv::to_bytes::<Error>(&slab).expect("slab must archive");
        let archived =
            rkyv::access::<ArchivedIdSlab<NodeId, i32>, Error>(&bytes)
                .expect("archive is valid");
        let decoded = rkyv::deserialize::<IdSlab<NodeId, i32>, Error>(archived)
            .expect("slab must decode");

        assert_eq!(decoded, slab);
    }

    #[cfg(feature = "facet")]
    #[test]
    fn facet_exposes_a_shape() {
        let shape = <IdSlab<NodeId, i32> as facet::Facet>::SHAPE;

        assert_eq!(shape.type_identifier, "IdSlab");
    }
}