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