sparse_slot/
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
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
/*
 * 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::fmt::Debug;

#[derive(Debug, PartialEq, Eq)]
pub enum SparseSlotError {
    IndexOutOfBounds(usize),
    Occupied(usize),
    GenerationMismatch(u16),
    IllegalZeroGeneration,
}

/// A fixed-size sparse collection that maintains optional values at specified indices.
///
/// `SparseSlot<T>` provides a fixed-capacity container where each slot can either be empty (`None`)
/// or contain a value (`Some(T)`). Once initialized, the capacity cannot be changed. Values can only
/// be set once in empty slots - attempting to overwrite an existing value will be ignored.
///
/// # Type Parameters
///
/// * `T` - The type of elements stored in the collection
///
/// # Characteristics
///
/// * Fixed size - Capacity is determined at creation
/// * Sparse storage - Slots can be empty or filled
/// * One-time assignment - Values can only be set once per slot
/// * Index-based access - Direct access to elements via indices
/// * Iterator support - Both immutable and mutable iteration over non-empty slots
///
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]

pub struct Id {
    pub index: usize,
    pub generation: u16,
}

impl Id {
    #[must_use]
    pub fn new(index: usize, generation: u16) -> Self {
        Self { index, generation }
    }

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

    #[must_use]
    pub fn generation(&self) -> u16 {
        self.generation
    }

    #[must_use]
    pub fn next(&self) -> Self {
        Self {
            index: self.index,
            generation: self.generation.wrapping_add(1),
        }
    }
}

impl From<((usize, u16),)> for Id {
    fn from(((index, generation), ): ((usize, u16),)) -> Self {
        Self { index, generation }
    }
}

#[derive(Debug)]
struct Entry<T> {
    pub generation: u16,
    pub item: Option<T>,
}

impl<T> Default for Entry<T> {
    fn default() -> Self {
        Self {
            generation: 0,
            item: None,
        }
    }
}

#[derive(Debug)]
pub struct SparseSlot<T> {
    items: Vec<Entry<T>>,
}

impl<T> SparseSlot<T> {
    /// Creates a new `SparseSlot` with the specified capacity.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The fixed size of the collection
    ///
    /// # Returns
    ///
    /// A new `SparseSlot` instance with all slots initialized to `None`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sparse_slot::SparseSlot;
    /// let slot: SparseSlot<i32> = SparseSlot::new(5);
    /// assert_eq!(slot.len(), 0);
    /// assert_eq!(slot.capacity(), 5);
    /// ```
    #[must_use]
    pub fn new(capacity: usize) -> Self {
        let mut items = Vec::with_capacity(capacity);
        items.extend((0..capacity).map(|_| Entry::default()));
        Self { items }
    }

    pub fn try_set(&mut self, id: Id, item: T) -> Result<(), SparseSlotError> {
        if id.index >= self.items.len() {
            return Err(SparseSlotError::IndexOutOfBounds(id.index));
        }

        let entry = self
            .items
            .get_mut(id.index)
            .ok_or(SparseSlotError::IndexOutOfBounds(id.index))?;

        if entry.item.is_some() {
            return Err(SparseSlotError::Occupied(id.index));
        }

        if entry.generation != id.generation {
            return Err(SparseSlotError::GenerationMismatch(entry.generation));
        }

        entry.item = Some(item);
        Ok(())
    }

    #[must_use]
    #[inline(always)]
    pub fn get(&self, id: Id) -> Option<&T> {
        let entry = &self.items[id.index];
        if entry.generation != id.generation {
            return None;
        }
        entry.item.as_ref()
    }

    #[must_use]
    #[inline(always)]
    pub fn get_mut(&mut self, id: Id) -> Option<&mut T> {
        let entry = self.items.get_mut(id.index)?;
        if entry.generation != id.generation {
            return None;
        }
        entry.item.as_mut()
    }

    pub fn remove(&mut self, id: Id) -> Option<T> {
        let entry = self.items.get_mut(id.index)?;
        if entry.generation != id.generation {
            return None;
        }
        let item = entry.item.take();
        if item.is_some() {
            entry.generation = entry.generation.wrapping_add(1);
        }
        item
    }

    pub fn iter(&self) -> impl Iterator<Item=(Id, &T)> {
        self.items.iter().enumerate().filter_map(|(idx, entry)| {
            entry
                .item
                .as_ref()
                .map(|item| (Id::new(idx, entry.generation), item))
        })
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item=(Id, &mut T)> {
        self.items
            .iter_mut()
            .enumerate()
            .filter_map(|(idx, entry)| {
                entry
                    .item
                    .as_mut()
                    .map(|item| (Id::new(idx, entry.generation), item))
            })
    }

    pub fn capacity(&self) -> usize {
        self.items.len()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.items.iter().filter(|x| x.item.is_some()).count()
    }

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

    pub fn clear(&mut self) {
        for entry in &mut self.items {
            if entry.item.take().is_some() {
                entry.generation = entry.generation.wrapping_add(1);
            }
        }
    }
}