orx_selfref_col/references/
single.rs

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