depacked 0.2.3

Minimalistic Rust Crate for handling memory packed data to aid CPU caching.
Documentation
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
use skiplist::OrderedSkipList;
#[cfg(not(debug_assertions))]
use std::hint::unreachable_unchecked;
use std::{fmt, marker::PhantomData, num::NonZeroU32};

/// A growable container for data.
///
/// The inserted data themselves are kept in continuous stretch of memory to
/// aid CPU memory caching. Information about unused spots / holes in the
/// allocated memory is kept in a separate ordered skip list.
///
/// The allocated memory never shrinks and is linearly proportional to peak
/// number of stored elements.
///
/// Accessing the data is very fast and with time complexity O(1). Inserting
/// and removing is slower.
///
/// Inserting has amortized time complexity O(1). Worst case single insertion
/// complexity is linear in number of stored items because the underlying
/// memory might need to be reallocated.
///
/// Removing is slowest as it has average complexity O(log(n)) in number of
/// holes in the allocated memory. Removing is fastest when number of stored
/// elements is kept close to peak number of stored elements. Actual removal
/// time is stochastic due to usage of skip list under the hood.
pub struct PackedData<T> {
    holes: OrderedSkipList<usize>,
    data: Vec<Slot<T>>,
}

impl<T> PackedData<T> {
    /// Constructs new, empty `PackedData<T>` with specific maximum expected
    /// capacity. The underlying data structures are optimized for performance
    /// for up to this capacity.
    ///
    /// Performance of item removing deteriorates if the maximum capacity is
    /// surpassed.
    ///
    /// # Arguments
    ///
    /// * `capacity` - maximum expected capacity used for optimal performance.
    pub fn with_max_capacity(capacity: usize) -> Self {
        Self {
            holes: OrderedSkipList::with_capacity(capacity),
            data: Vec::new(),
        }
    }

    /// Returns allocated capacity. This is equal to the number of items which
    /// could be stored without reallocation.
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Returns number of currently stored items.
    pub fn len(&self) -> usize {
        self.data.len() - self.holes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Inserts an item to first free spot in the underlying memory and returns
    /// ID of the item.
    ///
    /// # Arguments
    ///
    /// * `item` - item to be inserted.
    pub fn insert(&mut self, item: T) -> Item<T> {
        match self.holes.pop_front() {
            Some(index) => {
                let slot = Slot::used(self.data[index].generation(), item);
                let generation = slot.generation();
                self.data[index] = slot;
                Item {
                    index,
                    generation,
                    _marker: PhantomData,
                }
            }
            None => {
                let index = self.data.len();
                let generation = unsafe { NonZeroU32::new_unchecked(1) };
                self.data.push(Slot::used(generation, item));
                Item {
                    generation,
                    index,
                    _marker: PhantomData,
                }
            }
        }
    }

    /// Removes and returns an item and marks its spot as free (thus reusable
    /// for inserting).
    ///
    /// # Arguments
    ///
    /// * `item` - ID of item to be removed.
    ///
    /// # Panics
    ///
    /// Panics if such an item is not stored.
    pub fn remove(&mut self, item: Item<T>) -> T {
        let generation = self.data[item.index]
            .generation()
            .get()
            .checked_add(1)
            .unwrap_or(1);
        let mut old = Slot::empty(unsafe { NonZeroU32::new_unchecked(generation) });
        std::mem::swap(&mut old, &mut self.data[item.index]);
        self.holes.insert(item.index);
        match old {
            Slot::Used(generation, inner_item) => {
                if generation != item.generation {
                    panic!("The item is not stored!");
                }
                inner_item
            }
            _ => panic!("The item is not stored!"),
        }
    }

    /// Returns a reference to an item.
    ///
    /// # Arguments
    ///
    /// * `item` - ID of the item to be retrieved.
    ///
    /// # Panics
    ///
    /// Panics if such an item is not stored.
    pub fn get(&self, item: Item<T>) -> &T {
        match self.data.get(item.index) {
            Some(slot) => match slot {
                Slot::Used(generation, inner_item) => {
                    if *generation != item.generation {
                        panic!("The item is not stored!");
                    }
                    inner_item
                }
                Slot::Empty(_) => panic!("The item is not stored!"),
            },
            None => panic!("The item is not stored!"),
        }
    }

    /// Returns a reference to an item without any safety checks.
    ///
    /// # Arguments
    ///
    /// * `item` - ID of the item to be retrieved.
    ///
    /// # Safety
    ///
    /// `item` has to be stored.
    #[inline]
    pub unsafe fn get_unchecked(&self, item: Item<T>) -> &T {
        #[cfg(debug_assertions)]
        {
            self.get(item)
        }

        #[cfg(not(debug_assertions))]
        match self.data.get_unchecked(item.index) {
            Slot::Used(_, inner_item) => inner_item,
            Slot::Empty(_) => unreachable_unchecked(),
        }
    }

    /// Returns a mutable reference to an item.
    ///
    /// # Arguments
    ///
    /// * `item` - ID of the item to be retrieved.
    ///
    /// # Panics
    ///
    /// Panics if such an item is not stored.
    pub fn get_mut(&mut self, item: Item<T>) -> &mut T {
        match self.data.get_mut(item.index) {
            Some(slot) => match slot {
                Slot::Used(generation, inner_item) => {
                    if *generation != item.generation {
                        panic!("The item is not stored!");
                    }
                    inner_item
                }
                Slot::Empty(_) => panic!("The item is not stored!"),
            },
            None => panic!("The item is not stored!"),
        }
    }

    /// Returns a mutable reference to an item.
    ///
    /// # Arguments
    ///
    /// * `item` - ID of the item to be retrieved.
    ///
    /// # Safety
    ///
    /// `item` has to be stored.
    #[inline]
    pub unsafe fn get_unchecked_mut(&mut self, item: Item<T>) -> &mut T {
        #[cfg(debug_assertions)]
        {
            self.get_mut(item)
        }

        #[cfg(not(debug_assertions))]
        match self.data.get_unchecked_mut(item.index) {
            Slot::Used(_, inner_item) => inner_item,
            Slot::Empty(_) => unreachable_unchecked(),
        }
    }
}

#[derive(Eq)]
pub struct Item<T> {
    index: usize,
    generation: NonZeroU32,
    _marker: PhantomData<T>,
}

// derive(Clone, Copy) doesn't work because of this
// https://github.com/rust-lang/rust/issues/26925
impl<T> Clone for Item<T> {
    fn clone(&self) -> Self {
        Self {
            index: self.index,
            generation: self.generation,
            _marker: PhantomData,
        }
    }
}

impl<T> Copy for Item<T> {}

impl<T> PartialEq for Item<T> {
    fn eq(&self, other: &Self) -> bool {
        self.index == other.index && self.generation == other.generation
    }
}

impl<T> fmt::Debug for Item<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Item")
            .field("index", &self.index)
            .field("generation", &self.generation)
            .finish()
    }
}

enum Slot<T> {
    Empty(NonZeroU32),
    Used(NonZeroU32, T),
}

impl<T> Slot<T> {
    fn used(generation: NonZeroU32, item: T) -> Self {
        Self::Used(generation, item)
    }

    fn empty(generation: NonZeroU32) -> Self {
        Self::Empty(generation)
    }

    fn generation(&self) -> NonZeroU32 {
        match self {
            Self::Empty(generation) => *generation,
            Self::Used(generation, _) => *generation,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_packed_data() {
        struct Number {
            number: u32,
        }

        let num_numbers = 100;
        let mut packed = PackedData::with_max_capacity(num_numbers * 2);

        let mut items: Vec<Item<Number>> = Vec::new();
        for number in 0..num_numbers {
            items.push(packed.insert(Number {
                number: (number as u32) + 1,
            }));
        }

        assert_eq!(packed.len(), num_numbers as usize);
        let initial_capacity = packed.capacity();
        assert!(initial_capacity >= packed.len());

        for (i, &item) in items.iter().enumerate() {
            let number = packed.get(item);
            assert_eq!(number.number, (i as u32) + 1);

            let number = packed.get_mut(item);
            number.number += 2;

            let number = packed.get(item);
            assert_eq!(number.number, (i as u32) + 3);
        }

        assert_eq!(packed.len(), num_numbers as usize);
        assert!(initial_capacity >= packed.len());

        for i in 0..(num_numbers / 2) {
            let removed: Number = packed.remove(items[i * 2]);
            assert_eq!(removed.number, (i as u32) * 2 + 3);

            assert_eq!(packed.len(), num_numbers - i - 1);
            assert_eq!(packed.capacity(), initial_capacity);
        }
    }

    #[test]
    fn test_get_unsafe() {
        struct Data {
            value: u64,
        }

        let mut packed = PackedData::with_max_capacity(100);
        let a = packed.insert(Data { value: 1 });
        let b = packed.insert(Data { value: 2 });
        let c = packed.insert(Data { value: 3 });

        assert_eq!(packed.get(a).value, 1);
        assert_eq!(packed.get(b).value, 2);
        assert_eq!(packed.get(c).value, 3);

        packed.get_mut(b).value = 8;
        assert_eq!(packed.get(a).value, 1);
        assert_eq!(packed.get(b).value, 8);
        assert_eq!(packed.get(c).value, 3);
    }

    #[test]
    fn test_eq() {
        struct Something(u32);
        let mut packed = PackedData::with_max_capacity(2);
        let item_a = packed.insert(Something(1));
        let item_b = packed.insert(Something(1));
        assert_eq!(item_a, item_a);
        assert_ne!(item_a, item_b);
    }

    #[test]
    #[should_panic]
    fn test_remove_twice_panic() {
        struct Something(u32);
        let mut packed = PackedData::with_max_capacity(2);
        let item = packed.insert(Something(1));
        packed.remove(item);
        packed.remove(item);
    }

    #[test]
    #[should_panic]
    fn test_get_removed_panic_a() {
        struct Something(u32);
        let mut packed = PackedData::with_max_capacity(2);
        let item = packed.insert(Something(1));
        packed.remove(item);
        packed.get(item);
    }

    #[test]
    #[should_panic]
    fn test_get_removed_panic_b() {
        struct Something(u32);
        let mut packed = PackedData::with_max_capacity(2);
        packed.insert(Something(0));
        let item = packed.insert(Something(1));
        packed.insert(Something(1));
        packed.remove(item);
        packed.insert(Something(2));
        packed.get(item);
    }

    #[test]
    #[should_panic]
    fn test_get_mut_removed_panic_a() {
        struct Something(u32);
        let mut packed = PackedData::with_max_capacity(2);
        let item = packed.insert(Something(1));
        packed.remove(item);
        packed.get_mut(item);
    }

    #[test]
    #[should_panic]
    fn test_get_mut_removed_panic_b() {
        struct Something(u32);
        let mut packed = PackedData::with_max_capacity(2);
        packed.insert(Something(0));
        let item = packed.insert(Something(1));
        packed.insert(Something(2));
        packed.remove(item);
        packed.insert(Something(3));
        packed.get_mut(item);
    }

    #[test]
    fn test_size() {
        assert_eq!(std::mem::size_of::<Slot<u64>>(), 16);
    }
}