Skip to main content

arctic/sequential/
set.rs

1//! Auxiliary types for use with [`SequentialSet`][crate::sequential::Set].
2
3use core::borrow::Borrow as _;
4
5use crate::raw;
6use crate::raw::key;
7use crate::sequential::Map;
8
9/// Non-concurrent set.
10#[repr(transparent)]
11pub struct Set<K: key::Split> {
12    map: Map<K, raw::Set>,
13}
14
15impl<K> Default for Set<K>
16where
17    K: key::Split,
18{
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl<K> Set<K>
25where
26    K: key::Split,
27{
28    /// Constructs a new empty set. Does not allocate.
29    #[inline]
30    pub const fn new() -> Self {
31        Self { map: Map::new() }
32    }
33
34    /// Returns `true` if this set contains `key`.
35    ///
36    /// # Examples
37    ///
38    /// ```rust
39    /// use arctic::sequential;
40    ///
41    /// let mut set = sequential::Set::<[u8; 4]>::new();
42    /// let key = [8, 2, 3, 255];
43    /// assert!(set.insert(&key), "Key is not present");
44    /// assert!(set.contains(&key), "Key is present");
45    ///
46    /// ```
47    pub fn contains(&self, key: &K::Borrowed) -> bool {
48        let (reader, byte) = K::split_last(key);
49
50        self.map
51            .get_raw(reader)
52            .map(|value| unsafe { value.cast::<raw::Set>().as_ref() })
53            .is_some_and(|set| set.contains(byte))
54    }
55
56    /// Insert `key` into this set.
57    ///
58    /// Returns `true` if successful, i.e., the key was not present and was newly inserted.
59    ///
60    /// # Examples
61    ///
62    /// ```rust
63    /// use arctic::sequential;
64    ///
65    /// let mut set = sequential::Set::<u128>::new();
66    /// assert!(set.insert(5), "Key is not present");
67    /// assert!(!set.insert(5), "Key is present");
68    /// ```
69    pub fn insert(&mut self, key: K::Insert<'_>) -> bool {
70        let (reader, byte) = K::split_last(key.borrow());
71
72        unsafe { self.map.entry_raw(reader) }
73            .or_default()
74            .insert_mut(byte)
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use crate::sequential::Set;
81
82    #[test]
83    fn smoke_insert() {
84        let mut set = Set::<u64>::default();
85        assert!(set.insert(5));
86        assert!(set.insert(0xdeadbeef));
87        assert!(!set.insert(5));
88    }
89
90    #[test]
91    fn smoke_contains() {
92        let mut set = Set::<u64>::default();
93        assert!(set.insert(0xdeadbeef));
94        assert!(set.contains(&0xdeadbeef));
95    }
96}