use crate::{Refs, Variant};
use core::fmt::Debug;
pub struct Node<V>
where
V: Variant,
{
data: Option<V::Item>,
prev: V::Prev,
next: V::Next,
}
unsafe impl<V: Variant> Send for Node<V> where V::Item: Send {}
unsafe impl<V: Variant> Sync for Node<V> where V::Item: Sync {}
impl<V> Node<V>
where
V: Variant,
{
pub fn new_active(data: V::Item, prev: V::Prev, next: V::Next) -> Self {
Self {
data: Some(data),
prev,
next,
}
}
pub fn new_free_node(data: V::Item) -> Self {
Self {
data: Some(data),
prev: Refs::empty(),
next: Refs::empty(),
}
}
pub fn into_data(self) -> Option<V::Item> {
self.data
}
pub fn data(&self) -> Option<&V::Item> {
self.data.as_ref()
}
pub fn prev(&self) -> &V::Prev {
&self.prev
}
pub fn next(&self) -> &V::Next {
&self.next
}
#[inline(always)]
pub fn is_active(&self) -> bool {
self.data.is_some()
}
#[inline(always)]
pub fn is_closed(&self) -> bool {
self.data.is_none()
}
pub fn data_mut(&mut self) -> Option<&mut V::Item> {
self.data.as_mut()
}
pub fn prev_mut(&mut self) -> &mut V::Prev {
&mut self.prev
}
pub fn next_mut(&mut self) -> &mut V::Next {
&mut self.next
}
pub fn close(&mut self) -> V::Item {
self.prev.clear();
self.next.clear();
self.data.take().expect("must be an open node")
}
pub fn swap_data(&mut self, new_value: V::Item) -> V::Item {
debug_assert!(self.is_active());
self.data.replace(new_value).expect("must be active")
}
pub fn take_data(&mut self) -> Option<V::Item> {
self.data.take()
}
}
impl<V: Variant> Debug for Node<V>
where
V::Item: Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Node")
.field("data", &self.data)
.field("prev", &self.prev)
.field("next", &self.next)
.finish()
}
}