orx_selfref_col/
selfref_col.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use crate::{
    node::Node, CoreCol, MemoryPolicy, MemoryState, NodeIdx, NodeIdxError, NodePtr, Variant,
};
use core::ops::{Deref, DerefMut};
use orx_pinned_vec::PinnedVec;

/// `SelfRefCol` is a core data structure to conveniently build safe and efficient self referential collections, such as linked lists and trees.
pub struct SelfRefCol<V, M, P>
where
    V: Variant,
    M: MemoryPolicy<V>,
    P: PinnedVec<Node<V>>,
{
    core: CoreCol<V, P>,
    policy: M,
    state: MemoryState,
}

impl<V, M, P> Default for SelfRefCol<V, M, P>
where
    V: Variant,
    M: MemoryPolicy<V>,
    P: PinnedVec<Node<V>> + Default,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<V, M, P> Deref for SelfRefCol<V, M, P>
where
    V: Variant,
    M: MemoryPolicy<V>,
    P: PinnedVec<Node<V>>,
{
    type Target = CoreCol<V, P>;

    fn deref(&self) -> &Self::Target {
        &self.core
    }
}

impl<V, M, P> DerefMut for SelfRefCol<V, M, P>
where
    V: Variant,
    M: MemoryPolicy<V>,
    P: PinnedVec<Node<V>>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.core
    }
}

impl<V, M, P> SelfRefCol<V, M, P>
where
    V: Variant,
    M: MemoryPolicy<V>,
    P: PinnedVec<Node<V>>,
{
    /// Creates a new empty collection.
    pub fn new() -> Self
    where
        P: Default,
    {
        Self {
            core: CoreCol::new(),
            policy: M::default(),
            state: MemoryState::default(),
        }
    }

    /// Breaks the self referential collection into its core collection and memory state.
    pub fn into_inner(self) -> (CoreCol<V, P>, MemoryState) {
        let state = self.memory_state();
        (self.core, state)
    }

    pub(crate) fn from_raw_parts(core: CoreCol<V, P>, policy: M, state: MemoryState) -> Self {
        Self {
            core,
            policy,
            state,
        }
    }

    pub(crate) fn with_active_nodes(nodes: P) -> Self {
        Self {
            core: CoreCol::with_active_nodes(nodes),
            policy: M::default(),
            state: MemoryState::default(),
        }
    }

    // get

    /// Memory state of the collection.
    pub fn memory_state(&self) -> MemoryState {
        self.state
    }

    /// Memory policy of the collection.
    pub fn memory(&self) -> &M {
        &self.policy
    }

    /// Closes the node with the given `node_ptr`, returns its taken out value,
    /// and reclaims closed nodes if necessary.
    pub fn close_and_reclaim(&mut self, node_ptr: &NodePtr<V>) -> V::Item {
        let data = self.core.close(node_ptr);

        let state_changed = M::reclaim_closed_nodes(self, node_ptr);
        self.update_state(state_changed);

        data
    }

    /// Succeeding the operation of closing of node with the given `node_ptr`,
    /// reclaims closed nodes if necessary.
    ///
    /// Returns whether the memory state changed.
    pub fn reclaim_from_closed_node(&mut self, node_ptr: &NodePtr<V>) -> bool {
        let state_changed = M::reclaim_closed_nodes(self, node_ptr);
        self.update_state(state_changed);
        state_changed
    }

    /// If `state_changed` is true, proceeds to the next memory state.
    #[inline(always)]
    pub fn update_state(&mut self, state_changed: bool) {
        if state_changed {
            self.state = self.state.successor_state();
        }
    }

    /// Returns a reference to the node with the given `NodeIdx`;
    /// returns None if the index is invalid.
    #[inline(always)]
    pub fn node_from_idx(&self, idx: &NodeIdx<V>) -> Option<&Node<V>> {
        match idx.is_in_state(self.state) && self.nodes().contains_ptr(idx.ptr()) {
            true => Some(unsafe { &*idx.ptr() }),
            false => None,
        }
    }

    /// Tries to create a reference to the node with the given `NodeIdx`;
    /// returns the error if the index is invalid.
    #[inline(always)]
    pub fn try_node_from_idx(&self, idx: &NodeIdx<V>) -> Result<&Node<V>, NodeIdxError> {
        match self.nodes().contains_ptr(idx.ptr()) {
            true => match idx.is_in_state(self.state) {
                true => Ok(unsafe { &*idx.ptr() }),
                false => Err(NodeIdxError::ReorganizedCollection),
            },
            false => Err(NodeIdxError::OutOfBounds),
        }
    }

    /// Returns the node index error if the index is invalid.
    /// Returns None if it is valid.
    #[inline(always)]
    pub fn node_idx_error(&self, idx: &NodeIdx<V>) -> Option<NodeIdxError> {
        match self.try_node_from_idx(idx) {
            Ok(node) => match node.is_active() {
                true => None,
                false => Some(NodeIdxError::RemovedNode),
            },
            Err(err) => Some(err),
        }
    }

    /// Tries to get a valid pointer to the node with the given `NodeIdx`;
    /// returns the error if the index is invalid.
    #[inline(always)]
    pub fn try_get_ptr(&self, idx: &NodeIdx<V>) -> Result<NodePtr<V>, NodeIdxError> {
        match self.nodes().contains_ptr(idx.ptr()) {
            true => match idx.is_in_state(self.state) {
                true => {
                    let ptr = idx.ptr();
                    match unsafe { &*ptr }.is_active() {
                        true => Ok(NodePtr::new(ptr)),
                        false => Err(NodeIdxError::RemovedNode),
                    }
                }
                false => Err(NodeIdxError::ReorganizedCollection),
            },
            false => Err(NodeIdxError::OutOfBounds),
        }
    }

    /// Tries to get a valid pointer to the node with the given `NodeIdx`;
    /// returns None if the index is invalid.
    #[inline(always)]
    pub fn get_ptr(&self, idx: &NodeIdx<V>) -> Option<NodePtr<V>> {
        match self.nodes().contains_ptr(idx.ptr()) {
            true => match idx.is_in_state(self.state) {
                true => {
                    let ptr = idx.ptr();
                    match unsafe { &*ptr }.is_active() {
                        true => Some(NodePtr::new(ptr)),
                        false => None,
                    }
                }
                false => None,
            },
            false => None,
        }
    }

    // mut

    /// Clears the collection and changes the memory state.
    pub fn clear(&mut self) {
        self.core.clear_core();
        self.state = self.state.successor_state();
    }

    /// Returns a mutable reference to the node with the given `NodeIdx`;
    /// returns None if the index is invalid.
    #[inline(always)]
    pub fn node_mut_from_idx(&mut self, idx: &NodeIdx<V>) -> Option<&mut Node<V>> {
        match idx.is_in_state(self.state) && self.nodes().contains_ptr(idx.ptr()) {
            true => Some(unsafe { &mut *idx.ptr_mut() }),
            false => None,
        }
    }

    /// Tries to create a mutable reference to the node with the given `NodeIdx`;
    /// returns the error if the index is invalid.
    #[inline(always)]
    pub fn try_node_mut_from_idx(
        &mut self,
        idx: &NodeIdx<V>,
    ) -> Result<&mut Node<V>, NodeIdxError> {
        match self.nodes().contains_ptr(idx.ptr()) {
            true => match idx.is_in_state(self.state) {
                true => Ok(unsafe { &mut *idx.ptr_mut() }),
                false => Err(NodeIdxError::ReorganizedCollection),
            },
            false => Err(NodeIdxError::OutOfBounds),
        }
    }

    /// Pushes the element with the given `data` and returns its index.
    pub fn push_get_idx(&mut self, data: V::Item) -> NodeIdx<V> {
        let node_ptr = self.push(data);
        NodeIdx::new(self.memory_state(), &node_ptr)
    }
}