orx_selfref_col/references/
single.rs

1use super::{refs::Refs, NodePtr};
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 {} is out of bounds for RefsSingle.",
43            ref_idx
44        );
45        self.clear();
46    }
47
48    #[inline(always)]
49    fn remove(&mut self, ptr: usize) -> Option<usize> {
50        match &mut self.0 {
51            None => None,
52            Some(x) => match x.ptr() as usize == ptr {
53                true => {
54                    self.clear();
55                    Some(0)
56                }
57                false => None,
58            },
59        }
60    }
61}
62
63impl<V: Variant> RefsSingle<V> {
64    /// Returns the pointer to the referenced node.
65    pub fn get(&self) -> Option<&NodePtr<V>> {
66        self.0.as_ref()
67    }
68
69    /// Sets the pointer to the referenced node with the given `node_idx`.
70    pub fn set(&mut self, node_idx: Option<NodePtr<V>>) {
71        self.0 = node_idx
72    }
73
74    /// Sets the pointer to the referenced node with the given `node_idx`.
75    pub fn set_some(&mut self, node_idx: NodePtr<V>) {
76        self.0 = Some(node_idx)
77    }
78
79    /// Un-sets the reference.
80    pub fn set_none(&mut self) {
81        self.0 = None
82    }
83}