1use crate::{Refs, Variant};
2use core::fmt::Debug;
3
4pub struct Node<V>
6where
7    V: Variant,
8{
9    data: Option<V::Item>,
10    prev: V::Prev,
11    next: V::Next,
12}
13
14unsafe impl<V: Variant> Send for Node<V> where V::Item: Send {}
15
16unsafe impl<V: Variant> Sync for Node<V> where V::Item: Sync {}
17
18impl<V> Node<V>
19where
20    V: Variant,
21{
22    pub fn new_active(data: V::Item, prev: V::Prev, next: V::Next) -> Self {
24        Self {
25            data: Some(data),
26            prev,
27            next,
28        }
29    }
30
31    pub fn new_free_node(data: V::Item) -> Self {
33        Self {
34            data: Some(data),
35            prev: Refs::empty(),
36            next: Refs::empty(),
37        }
38    }
39
40    pub fn into_data(self) -> Option<V::Item> {
44        self.data
45    }
46
47    pub fn data(&self) -> Option<&V::Item> {
51        self.data.as_ref()
52    }
53
54    pub fn prev(&self) -> &V::Prev {
56        &self.prev
57    }
58
59    pub fn next(&self) -> &V::Next {
61        &self.next
62    }
63
64    #[inline(always)]
66    pub fn is_active(&self) -> bool {
67        self.data.is_some()
68    }
69
70    #[inline(always)]
72    pub fn is_closed(&self) -> bool {
73        self.data.is_none()
74    }
75
76    pub fn data_mut(&mut self) -> Option<&mut V::Item> {
80        self.data.as_mut()
81    }
82
83    pub fn prev_mut(&mut self) -> &mut V::Prev {
85        &mut self.prev
86    }
87
88    pub fn next_mut(&mut self) -> &mut V::Next {
90        &mut self.next
91    }
92
93    pub fn close(&mut self) -> V::Item {
99        self.prev.clear();
100        self.next.clear();
101        self.data.take().expect("must be an open node")
102    }
103
104    pub fn swap_data(&mut self, new_value: V::Item) -> V::Item {
110        debug_assert!(self.is_active());
111        self.data.replace(new_value).expect("must be active")
112    }
113
114    pub fn take_data(&mut self) -> Option<V::Item> {
118        self.data.take()
119    }
120}
121
122impl<V: Variant> Debug for Node<V>
123where
124    V::Item: Debug,
125{
126    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
127        f.debug_struct("Node")
128            .field("data", &self.data)
129            .field("prev", &self.prev)
130            .field("next", &self.next)
131            .finish()
132    }
133}