orx_selfref_col/references/
node_ptr.rs

1use crate::{Node, Variant};
2use core::fmt::Debug;
3
4/// A wrapper around a node pointer.
5pub struct NodePtr<V: Variant> {
6    ptr: *mut Node<V>,
7}
8
9unsafe impl<V: Variant> Send for NodePtr<V> where V::Item: Send {}
10
11unsafe impl<V: Variant> Sync for NodePtr<V> where V::Item: Sync {}
12
13impl<V: Variant> PartialEq for NodePtr<V> {
14    fn eq(&self, other: &Self) -> bool {
15        self.ptr == other.ptr
16    }
17}
18
19impl<V: Variant> Debug for NodePtr<V> {
20    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21        f.debug_struct("NodeIdx")
22            .field("ptr", &(self.ptr as usize))
23            .finish()
24    }
25}
26
27impl<V: Variant> Clone for NodePtr<V> {
28    fn clone(&self) -> Self {
29        Self { ptr: self.ptr }
30    }
31}
32
33impl<V: Variant> NodePtr<V> {
34    /// Creates a new node pointer by wrapping the given `ptr`.
35    pub fn new(ptr: *const Node<V>) -> Self {
36        Self {
37            ptr: ptr as *mut Node<V>,
38        }
39    }
40
41    /// Returns the const raw pointer.
42    #[inline(always)]
43    pub fn ptr(&self) -> *const Node<V> {
44        self.ptr
45    }
46
47    /// Returns the mutable raw pointer.
48    #[inline(always)]
49    pub fn ptr_mut(&self) -> *mut Node<V> {
50        self.ptr
51    }
52
53    // unsafe api
54    /// Returns a reference to the node.
55    ///
56    /// # Safety
57    ///
58    /// The caller must ensure that:
59    /// * this pointer is created from a self referential collection,
60    /// * the collection is still alive, and finally,
61    /// * the memory state of the collection has not changed since the pointer was created.
62    #[inline]
63    pub unsafe fn node(&self) -> &Node<V> {
64        unsafe { &*self.ptr }
65    }
66
67    /// Returns a mutable reference to the node.
68    ///
69    /// # Safety
70    ///
71    /// The caller must ensure that:
72    /// * this pointer is created from a self referential collection,
73    /// * the collection is still alive, and finally,
74    /// * the memory state of the collection has not changed since the pointer was created.
75    #[inline]
76    #[allow(clippy::mut_from_ref)]
77    pub unsafe fn node_mut(&self) -> &mut Node<V> {
78        unsafe { &mut *self.ptr }
79    }
80}