Skip to main content

ssplayer_wgpu/
roster.rs

1//! Generation-tagged slot storage, shared by the hosts that hand out handles.
2//!
3//! A [`SlotId`] stays meaningful after the value it named is removed: it
4//! resolves to `None` rather than to whichever value later reuses the slot.
5//! Slots are reused, so churn does not grow the roster.
6
7/// Names one value in a `Roster`. Safe to hold past its removal.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct SlotId {
10    index: u32,
11    generation: u32,
12}
13
14/// One slot. `generation` lives on the slot rather than the value so it keeps
15/// counting while the slot is empty.
16pub struct Slot<T> {
17    value: Option<T>,
18    generation: u32,
19}
20
21/// Values addressable by [`SlotId`].
22pub struct Roster<T> {
23    /// Values by slot. Empty slots are reused, so this does not grow with churn.
24    slots: Vec<Slot<T>>,
25    /// Indices of empty slots, so `insert` is O(1).
26    free: Vec<u32>,
27}
28
29impl<T> Slot<T> {
30    /// The value this slot holds, or `None` while it is free.
31    pub fn value_mut(&mut self) -> Option<&mut T> {
32        self.value.as_mut()
33    }
34}
35
36// Derived `Default` would demand `T: Default`, which no value here has.
37impl<T> Default for Roster<T> {
38    fn default() -> Self {
39        Self { slots: Vec::new(), free: Vec::new() }
40    }
41}
42
43impl<T> Roster<T> {
44    /// Store `value` and return the id naming it.
45    pub fn insert(&mut self, value: T) -> SlotId {
46        if let Some(index) = self.free.pop() {
47            let slot = &mut self.slots[index as usize];
48            slot.value = Some(value);
49            return SlotId { index, generation: slot.generation };
50        }
51        let index = self.slots.len() as u32;
52        self.slots.push(Slot { value: Some(value), generation: 0 });
53        SlotId { index, generation: 0 }
54    }
55
56    /// Drop the value `id` names. Returns whether it named a live one; a stale
57    /// id is an inert no-op.
58    pub fn remove(&mut self, id: SlotId) -> bool {
59        let Some(slot) = self.slots.get_mut(id.index as usize) else { return false };
60        if slot.generation != id.generation || slot.value.is_none() {
61            return false;
62        }
63        slot.value = None;
64        // Retiring the generation stops the next value in this slot from
65        // answering to the id just released.
66        slot.generation = slot.generation.wrapping_add(1);
67        self.free.push(id.index);
68        true
69    }
70
71    /// The value `id` names, or `None` once it has been removed.
72    pub fn get_mut(&mut self, id: SlotId) -> Option<&mut T> {
73        let slot = self.slots.get_mut(id.index as usize)?;
74        if slot.generation != id.generation { None } else { slot.value.as_mut() }
75    }
76
77    /// Every live value, in slot order. Holes left by removals are skipped.
78    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
79        self.slots.iter_mut().filter_map(|s| s.value.as_mut())
80    }
81
82    /// Every slot, free ones included, in slot order: what lets
83    /// `SSScene::update_with` walk the roster without collecting it first.
84    pub fn slots_mut(&mut self) -> &mut [Slot<T>] {
85        &mut self.slots
86    }
87
88    /// How many live values the roster holds.
89    pub fn len(&self) -> usize {
90        self.slots.iter().filter(|s| s.value.is_some()).count()
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    /// A handle outliving its value resolves to "gone", not to whatever took
99    /// over the slot.
100    #[test]
101    fn a_removed_id_never_names_its_successor() {
102        let mut roster: Roster<u32> = Roster::default();
103
104        let first = roster.insert(1);
105        assert_eq!(roster.get_mut(first).copied(), Some(1));
106        assert_eq!(roster.len(), 1);
107
108        assert!(roster.remove(first), "removing a live value reported failure");
109        assert!(roster.get_mut(first).is_none(), "a removed id still resolved");
110        assert_eq!(roster.len(), 0);
111        // A double destroy must be inert: no panic, no second slot release.
112        assert!(!roster.remove(first), "removing the same id twice reported success");
113
114        // The slot comes back, but the id does not.
115        let second = roster.insert(2);
116        assert_eq!(second.index, first.index, "the empty slot was not reused");
117        assert_ne!(second.generation, first.generation);
118        assert!(roster.get_mut(first).is_none(), "the old id resolved to the value that reused its slot");
119        assert_eq!(roster.get_mut(second).copied(), Some(2));
120        assert_eq!(roster.len(), 1);
121    }
122
123    /// Live values are handed out in slot order; holes left by removed ones are
124    /// skipped rather than yielded as blanks.
125    #[test]
126    fn only_live_values_are_iterated() {
127        let mut roster: Roster<u32> = Roster::default();
128        let ids: Vec<SlotId> = (0..4).map(|i| roster.insert(i)).collect();
129        assert_eq!(roster.iter_mut().count(), 4);
130
131        roster.remove(ids[1]);
132        roster.remove(ids[2]);
133        assert_eq!(roster.len(), 2);
134        assert_eq!(roster.iter_mut().map(|v| *v).collect::<Vec<_>>(), vec![0, 3]);
135
136        // Refilling the holes must not produce duplicates or lose anyone.
137        roster.insert(4);
138        roster.insert(5);
139        roster.insert(6);
140        assert_eq!(roster.len(), 5);
141        assert_eq!(roster.iter_mut().count(), 5);
142    }
143}