podded 0.7.0

Zero-copy types for constraint environments
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
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
use bytemuck::{Pod, Zeroable};
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
};

/// Constant to represent an empty value.
const SENTINEL: u32 = 0;

/// Enum representing the fields of a node.
#[derive(Copy, Clone)]
enum Register {
    Bucket,
    Next,
}

/// Enum representing the fields of the allocator.
enum Field {
    Size,
    Capacity,
    FreeListHead,
    Sequence,
}

/// Macro to access a bucket node.
macro_rules! bucket_node {
    ( $array:expr, $index:expr ) => {
        $array[$index as usize]
    };
}

/// Macro to access a node.
macro_rules! node {
    ( $array:expr, $index:expr ) => {
        $array[($index - 1) as usize]
    };
}

/// Macro to implement the readonly interface for an AVL tree type.
macro_rules! readonly_impl {
    ( $name:tt ) => {
        impl<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> $name<'a, V> {
            /// Returns the required data length (in bytes) to store a set with the specified capacity.
            pub const fn data_len(capacity: usize) -> usize {
                std::mem::size_of::<Allocator>() + (capacity * std::mem::size_of::<Node<V>>())
            }

            /// Returns the capacity of the set.
            pub fn capacity(&self) -> usize {
                self.allocator.get_field(Field::Capacity) as usize
            }

            /// Returns the number of values in the set.
            pub fn size(&self) -> usize {
                self.allocator.get_field(Field::Size) as usize
            }

            /// Indicates whether the set is full or not.
            pub fn is_full(&self) -> bool {
                self.allocator.get_field(Field::Size) >= self.allocator.get_field(Field::Capacity)
            }

            /// Indicates whether the set is empty or not.
            pub fn is_empty(&self) -> bool {
                self.allocator.get_field(Field::Size) == 0
            }

            /// Checks whether a value is present in the set or not.
            ///
            /// # Arguments
            ///
            /// * `value` - the value to check.
            pub fn contains(&self, value: &V) -> bool {
                let mut hasher = DefaultHasher::new();
                value.hash(&mut hasher);
                let index = hasher.finish() as u32 % self.allocator.get_field(Field::Capacity);

                let head = bucket_node!(self.nodes, index).get_register(Register::Bucket);
                let mut current = head;

                while current != SENTINEL {
                    let node = node!(self.nodes, current);
                    if &node.value == value {
                        return true;
                    }

                    current = node.get_register(Register::Next);
                }

                false
            }
        }
    };
}

/// Simple `HashSet` implementation where values are stored in a contiguous array.
///
/// This type can be used to reference a read-only set.
pub struct HashSet<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> {
    /// Node allocator.
    allocator: &'a Allocator,

    /// Array to store the values.
    nodes: &'a [Node<V>],
}

readonly_impl!(HashSet);

impl<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> HashSet<'a, V> {
    /// Loads a set from a byte array.
    pub fn from_bytes(bytes: &'a [u8]) -> Self {
        let (allocator, nodes) = bytes.split_at(std::mem::size_of::<Allocator>());

        let allocator = bytemuck::from_bytes::<Allocator>(allocator);
        let nodes = bytemuck::cast_slice(nodes);

        Self { allocator, nodes }
    }

    /// An iterator visiting all elements in arbitrary order.
    /// The iterator element type is `&'a V`.
    pub fn iter(&self) -> HashSetIterator<'_, V> {
        HashSetIterator::<V> {
            hash_set: self,
            bucket: SENTINEL,
            node: SENTINEL,
        }
    }
}

pub struct HashSetIterator<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> {
    hash_set: &'a HashSet<'a, V>,
    bucket: u32,
    node: u32,
}

impl<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> Iterator
    for HashSetIterator<'a, V>
{
    type Item = &'a V;

    fn next(&mut self) -> Option<Self::Item> {
        if self.bucket <= self.hash_set.capacity() as u32 {
            while self.node == SENTINEL {
                self.bucket += 1;
                if self.bucket > self.hash_set.capacity() as u32 {
                    return None;
                }
                self.node = node!(self.hash_set.nodes, self.bucket).get_register(Register::Bucket);
            }
            let node = &node!(self.hash_set.nodes, self.node);
            self.node = node.get_register(Register::Next);
            Some(&node.value)
        } else {
            None
        }
    }
}

/// Simple `HashSet` implementation where values are stored in a contiguous array.
///
/// This type can be used to reference a mutable set.
pub struct HashSetMut<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> {
    /// Node allocator.
    allocator: &'a mut Allocator,

    /// Array to store the values.
    nodes: &'a mut [Node<V>],
}

readonly_impl!(HashSetMut);

impl<'a, V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> HashSetMut<'a, V> {
    /// Loads a set from a byte array.
    pub fn from_bytes_mut(bytes: &'a mut [u8]) -> Self {
        let (allocator, nodes) = bytes.split_at_mut(std::mem::size_of::<Allocator>());

        let allocator = bytemuck::from_bytes_mut::<Allocator>(allocator);
        let nodes = bytemuck::cast_slice_mut(nodes);

        Self { allocator, nodes }
    }

    /// Initializes the set with the specified capacity.
    ///
    /// This function should be called once when the set is created.
    pub fn initialize(&mut self, capacity: u32) {
        self.allocator.initialize(capacity)
    }

    /// Insert a value on the set.
    ///
    /// Returns whether the value was newly inserted.  That is:
    ///   - If the set did not previously contain this value, `true` is returned.
    ///   - If the set already contained this value, `false` is returned, and the set is not modified.
    ///   - If the set is full, `false` is returned.
    ///
    /// # Arguments
    ///
    /// * `value` - the value to add.
    pub fn insert(&mut self, value: V) -> bool {
        if self.size() == self.capacity() {
            return false;
        }

        let mut hasher = DefaultHasher::new();
        value.hash(&mut hasher);
        let index = hasher.finish() as u32 % self.allocator.get_field(Field::Capacity);

        let head = bucket_node!(self.nodes, index).get_register(Register::Bucket);
        let mut current = head;

        while current != SENTINEL {
            let node = node!(self.nodes, current);
            // if the value is already present, we won't add
            // it again
            if node.value == value {
                return false;
            }

            current = node.get_register(Register::Next);
        }

        let node = self.add_node(value);
        bucket_node!(self.nodes, index).set_register(Register::Bucket, node);
        node!(self.nodes, node).set_register(Register::Next, head);

        true
    }

    /// Remove a value from the set.
    ///
    /// If the value is not present in the set, this function will return `false`.
    ///
    /// # Arguments
    ///
    /// * `value` - the value to remove.
    pub fn remove(&mut self, value: &V) -> bool {
        if self.is_empty() {
            return false;
        }

        let mut hasher = DefaultHasher::new();
        value.hash(&mut hasher);
        let index = hasher.finish() as u32 % self.allocator.get_field(Field::Capacity);

        let head = bucket_node!(self.nodes, index).get_register(Register::Bucket);
        let mut current = head;
        let mut previous = SENTINEL;

        while current != SENTINEL {
            let node = node!(self.nodes, current);
            // if the value is already present, we won't add
            // it again
            if &node.value == value {
                if previous == SENTINEL {
                    bucket_node!(self.nodes, index).set_register(Register::Bucket, SENTINEL);
                } else {
                    node!(self.nodes, previous)
                        .set_register(Register::Next, node.get_register(Register::Next));
                }

                return self.remove_node(current).is_some();
            }

            previous = current;
            current = node.get_register(Register::Next);
        }

        false
    }

    /// Adds a node to the set.
    ///
    /// The node is only added if there is space on the nodes' array. The index
    /// where the node was added is returned.
    ///
    /// # Arguments
    ///
    /// * `value` - the value of the node.
    fn add_node(&mut self, value: V) -> u32 {
        let free_node = self.allocator.get_field(Field::FreeListHead);
        let sequence = self.allocator.get_field(Field::Sequence);

        if free_node == sequence {
            if (sequence - 1) == self.allocator.get_field(Field::Capacity) {
                panic!(
                    "set is full ({} nodes)",
                    self.allocator.get_field(Field::Size)
                );
            }

            self.allocator.set_field(Field::Sequence, sequence + 1);
            self.allocator.set_field(Field::FreeListHead, sequence + 1);
        } else {
            self.allocator.set_field(
                Field::FreeListHead,
                node!(self.nodes, free_node).get_register(Register::Next),
            );
        }

        let entry = &mut node!(self.nodes, free_node);

        entry.value = value;
        // the height field is used to store the free list head, so we make
        // sure we reset its value
        entry.set_register(Register::Next, SENTINEL);

        self.allocator
            .set_field(Field::Size, self.allocator.get_field(Field::Size) + 1);

        free_node
    }

    /// Remove a node from the set, returning its value.
    ///
    /// # Arguments
    ///
    /// * `index` - index of the node to remove.
    fn remove_node(&mut self, index: u32) -> Option<V> {
        if index == SENTINEL {
            return None;
        }

        let node = &mut node!(self.nodes, index);
        let value = node.value;
        // clears the node value
        node.value = V::default();

        let free_list_head = self.allocator.get_field(Field::FreeListHead);
        // we use the `Next` register to create a linked list
        // of free nodes
        node.set_register(Register::Next, free_list_head);
        self.allocator.set_field(Field::FreeListHead, index);
        self.allocator
            .set_field(Field::Size, self.allocator.get_field(Field::Size) - 1);

        Some(value)
    }
}

/// The allocator is responsible to keep track of the status of the tree.
///
/// It uses two special fields to determine if the set is full and to reuse
/// deleted nodes. Until the set is full, the `sequence` has the same value
/// as the `free_list_head` field. When the set is full, the `sequence` field
/// will be equal to the capacity of the set. At this point, the `free_list_head`
/// is used to determine the index of free nodes.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct Allocator {
    /// Allocator fields:
    ///   [0] - size
    ///   [1] - capacity
    ///   [2] - free_list_head
    ///   [3] - sequence
    fields: [u32; 4],
}

impl Allocator {
    pub fn initialize(&mut self, capacity: u32) {
        self.fields = [0, capacity, 1, 1];
    }

    #[inline(always)]
    fn get_field(&self, field: Field) -> u32 {
        self.fields[field as usize]
    }

    #[inline(always)]
    fn set_field(&mut self, field: Field, value: u32) {
        self.fields[field as usize] = value;
    }
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct Node<V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> {
    /// Registers for a node. This is fixed to include:
    ///   [0] - bucket
    ///   [1] - next
    ///
    /// Note that the index of nodes are always stored as `index + 1` to
    /// reserve the index 0 as the SENTINEL value.
    registers: [u32; 2],

    /// The value associated with the node.
    value: V,
}

impl<V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> Node<V> {
    #[inline(always)]
    fn get_register(&self, register: Register) -> u32 {
        self.registers[register as usize]
    }

    #[inline(always)]
    fn set_register(&mut self, register: Register, value: u32) {
        self.registers[register as usize] = value;
    }
}

unsafe impl<V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> Zeroable for Node<V> {}

unsafe impl<V: Default + Copy + Clone + Hash + PartialEq + Pod + Zeroable> Pod for Node<V> {}

#[cfg(test)]
mod tests {
    use crate::collections::HashSetMut;

    #[test]
    fn test_insert() {
        const CAPACITY: usize = 10;

        let mut data = [0u8; HashSetMut::<u64>::data_len(CAPACITY)];
        let mut set = HashSetMut::<u64>::from_bytes_mut(&mut data);

        set.allocator.initialize(CAPACITY as u32);
        assert_eq!(set.capacity(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.insert(value));
        }

        assert_eq!(set.size(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.contains(&value));
        }
    }

    #[test]
    fn test_large_insert() {
        const CAPACITY: usize = 10_000;

        let mut data = [0u8; HashSetMut::<u64>::data_len(CAPACITY)];
        let mut set = HashSetMut::<u64>::from_bytes_mut(&mut data);

        set.allocator.initialize(CAPACITY as u32);
        assert_eq!(set.capacity(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.insert(value));
        }

        assert_eq!(set.size(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.contains(&value));
        }
    }

    #[test]
    fn test_large_remove() {
        const CAPACITY: usize = 10_000;

        let mut data = [0u8; HashSetMut::<u64>::data_len(CAPACITY)];
        let mut set = HashSetMut::<u64>::from_bytes_mut(&mut data);

        set.allocator.initialize(CAPACITY as u32);
        assert_eq!(set.capacity(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.insert(value));
        }

        assert_eq!(set.size(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.remove(&value));
        }

        assert_eq!(set.size(), 0);
    }

    #[test]
    fn test_large_remove_insert() {
        const CAPACITY: usize = 10_000;

        let mut data = [0u8; HashSetMut::<u64>::data_len(CAPACITY)];
        let mut set = HashSetMut::<u64>::from_bytes_mut(&mut data);

        set.allocator.initialize(CAPACITY as u32);
        assert_eq!(set.capacity(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.insert(value));
        }

        assert_eq!(set.size(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.remove(&value));
        }

        assert_eq!(set.size(), 0);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.insert(value));
        }

        assert_eq!(set.size(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.contains(&value));
        }
    }

    #[test]
    fn test_insert_when_full() {
        const CAPACITY: usize = 10;

        let mut data = [0u8; HashSetMut::<u64>::data_len(CAPACITY)];
        let mut set = HashSetMut::<u64>::from_bytes_mut(&mut data);

        set.allocator.initialize(CAPACITY as u32);
        assert_eq!(set.capacity(), CAPACITY);

        for i in 0..CAPACITY {
            let value = (i + 1) as u64;
            assert!(set.insert(value));
        }

        assert_eq!(set.size(), CAPACITY);
        assert!(set.is_full());

        // we should not be able to insert when full
        assert!(!set.insert(10));

        // when we remove an item
        assert!(set.remove(&1));
        // we can insert a value
        assert!(set.insert(11));

        // and then the set is full again
        assert!(set.is_full());
        assert!(!set.insert(20));
    }
}