orx_selfref_col/references/
array.rs

1use super::{NodePtr, refs::Refs};
2use crate::variant::Variant;
3use core::fmt::Debug;
4
5/// A constant number of references.
6pub struct RefsArray<const N: usize, V>([Option<NodePtr<V>>; N])
7where
8    V: Variant;
9
10impl<const N: usize, V: Variant> Clone for RefsArray<N, V> {
11    fn clone(&self) -> Self {
12        Self(self.0.clone())
13    }
14}
15
16impl<const N: usize, V: Variant> Debug for RefsArray<N, V> {
17    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
18        f.debug_tuple("RefsArray").field(&self.0).finish()
19    }
20}
21
22impl<const N: usize, V> Refs for RefsArray<N, V>
23where
24    V: Variant,
25{
26    #[inline(always)]
27    fn empty() -> Self {
28        Self([const { None }; N])
29    }
30
31    #[inline(always)]
32    fn is_empty(&self) -> bool {
33        self.0.iter().all(|x| x.is_none())
34    }
35
36    #[inline(always)]
37    fn clear(&mut self) {
38        self.0.iter_mut().for_each(|x| _ = x.take());
39    }
40
41    #[inline(always)]
42    fn remove_at(&mut self, ref_idx: usize) {
43        self.0[ref_idx] = None;
44    }
45
46    #[inline(always)]
47    fn remove(&mut self, ptr: usize) -> Option<usize> {
48        let x = self.0.iter().enumerate().find(|x| match x.1 {
49            Some(x) => x.ptr() as usize == ptr,
50            None => false,
51        });
52        match x {
53            Some((ref_idx, _)) => {
54                self.0[ref_idx] = None;
55                Some(ref_idx)
56            }
57            None => None,
58        }
59    }
60}
61
62impl<const N: usize, V: Variant> RefsArray<N, V> {
63    /// Returns the node pointer at the `ref_idx` position of the references array.
64    pub fn get(&self, ref_idx: usize) -> Option<&NodePtr<V>> {
65        self.0[ref_idx].as_ref()
66    }
67
68    // mut
69
70    /// Sets the the node pointer at the `ref_idx` position of the references array to the given `node_idx`.
71    pub fn set(&mut self, ref_idx: usize, node_idx: Option<NodePtr<V>>) {
72        self.0[ref_idx] = node_idx;
73    }
74
75    /// Sets the the node pointer at the `ref_idx` position of the references array to the given `node_idx`.
76    pub fn set_some(&mut self, ref_idx: usize, node_idx: NodePtr<V>) {
77        self.0[ref_idx] = Some(node_idx)
78    }
79
80    /// Un-sets the the node pointer at the `ref_idx` position of the references array.
81    pub fn set_none(&mut self, ref_idx: usize) {
82        self.0[ref_idx] = None
83    }
84}