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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use crate::data::node_data::NodeData;
use crate::variants::variant::Variant;
use crate::{NodeDataLazyClose, NodeRefsArray, NodeRefsVec, SelfRefColMut};
use orx_split_vec::prelude::PinnedVec;

/// A node of the self referential collection.
///
/// Each node is composed of the following three pieces of data:
/// * `data: V::Storage`: data of the element
/// * `prev: V::Prev`: references to the previous nodes in the collection
/// * `next: V::Next`: references to the previous nodes in the collection
pub struct Node<'a, V, T>
where
    V: Variant<'a, T>,
{
    pub(crate) data: V::Storage,
    pub(crate) prev: V::Prev,
    pub(crate) next: V::Next,
}

impl<'a, V, T> Node<'a, V, T>
where
    V: Variant<'a, T>,
{
    // new
    /// Creates a new free node with the given `data` without any previous or next references.
    #[inline(always)]
    pub fn new_free_node(data: T) -> Self {
        Self {
            data: V::Storage::active(data),
            prev: V::Prev::default(),
            next: V::Next::default(),
        }
    }

    /// Creates a new node with the given `data` and `prev` and `next` references.
    #[inline(always)]
    pub fn new(data: V::Storage, prev: V::Prev, next: V::Next) -> Self {
        Self { data, prev, next }
    }

    // get
    /// Returns a reference to the data stored in the node; None if the node is closed.
    #[inline(always)]
    pub fn data(&self) -> Option<&T> {
        self.data.get()
    }

    /// Returns a reference to previous references of the node.
    #[inline(always)]
    pub fn prev(&self) -> &V::Prev {
        &self.prev
    }

    /// Returns a reference to next references of the node.
    #[inline(always)]
    pub fn next(&self) -> &V::Next {
        &self.next
    }

    // mut
    /// Returns a mutable reference to the data stored in the node; None if the node is closed.
    pub fn data_mut(&mut self) -> Option<&mut T> {
        self.data.get_mut()
    }

    // mut with mut key
    /// Swaps the data stored in the node with the `new_value` and returns the old data.
    ///
    /// # Panics
    ///
    /// Panics if the node is closed.
    #[inline(always)]
    pub fn swap_data<'rf, P>(&'a self, vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>, new_value: T) -> T
    where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.swap_data(self, new_value)
    }

    /// Updates the previous references of the node as the given `prev`.
    #[inline(always)]
    pub fn set_prev_refs<'rf, P>(&'a self, vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>, prev: V::Prev)
    where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.set_prev_of(self, prev)
    }

    /// Updates the next references of the node as the given `next`.
    #[inline(always)]
    pub fn set_next_refs<'rf, P>(&'a self, vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>, next: V::Next)
    where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.set_next_of(self, next)
    }

    /// Updates the next reference of the node as the given `next`.
    #[inline(always)]
    pub fn set_next<'rf, P, Next: Into<V::Next>>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
        next: Next,
    ) where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.set_next_of(self, next.into())
    }

    /// Updates the previous reference of the node as the given `prev`.
    #[inline(always)]
    pub fn set_prev<'rf, P, Prev: Into<V::Prev>>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
        prev: Prev,
    ) where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.set_prev_of(self, prev.into())
    }

    /// Clears next references of the node.
    #[inline(always)]
    pub fn clear_next<'rf, P>(&'a self, vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>)
    where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.clear_next_of(self)
    }

    /// Clears previous references of the node.
    #[inline(always)]
    pub fn clear_prev<'rf, P>(&'a self, vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>)
    where
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.clear_prev_of(self)
    }

    // with mut key - NodeDataLazyClose
    /// Closes the lazy node, takes out and returns its data.
    ///
    /// # Panics
    ///
    /// Panics if the node is already closed; i.e., if `self.is_closed()`.
    #[inline(always)]
    pub fn close_node_take_data<'rf, P>(&'a self, vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>) -> T
    where
        V: Variant<'a, T, Storage = NodeDataLazyClose<T>>,
        P: PinnedVec<Node<'a, V, T>> + 'a,
    {
        vec_mut.close_node_take_data(self)
    }

    /// Closes the lazy node, takes out and returns its data.
    /// Skips memory reclaim operation regardless of the utilization.
    ///
    /// # Panics
    ///
    /// Panics if the node is already closed; i.e., if `self.is_closed()`.
    #[inline(always)]
    pub fn close_node_take_data_no_reclaim<'rf, P>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
    ) -> T
    where
        V: Variant<'a, T, Storage = NodeDataLazyClose<T>>,
        P: PinnedVec<Node<'a, V, T>> + 'a,
    {
        vec_mut.close_node_take_data_no_reclaim(self)
    }

    // with mut key - NodeRefsVec
    /// Returns a mutable reference to previous references of the node.
    #[inline(always)]
    pub fn prev_vec_mut<'rf, P>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
    ) -> &mut Vec<&'a Node<'a, V, T>>
    where
        V: Variant<'a, T, Prev = NodeRefsVec<'a, V, T>>,
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.get_prev_vec_mut(self)
    }

    /// Returns a mutable reference to next references of the node.
    #[inline(always)]
    pub fn next_vec_mut<'rf, P>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
    ) -> &mut Vec<&'a Node<'a, V, T>>
    where
        V: Variant<'a, T, Next = NodeRefsVec<'a, V, T>>,
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.get_next_vec_mut(self)
    }

    // with mut key - NodeRefsArray
    /// Returns a mutable reference to previous references of the node.
    #[inline(always)]
    pub fn prev_array_mut<'rf, P, const N: usize>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
    ) -> &mut [Option<&'a Node<'a, V, T>>; N]
    where
        V: Variant<'a, T, Prev = NodeRefsArray<'a, N, V, T>>,
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.get_prev_array_mut(self)
    }

    /// Returns a mutable reference to next references of the node.
    #[inline(always)]
    pub fn next_array_mut<'rf, P, const N: usize>(
        &'a self,
        vec_mut: &SelfRefColMut<'rf, 'a, V, T, P>,
    ) -> &mut [Option<&'a Node<'a, V, T>>; N]
    where
        V: Variant<'a, T, Next = NodeRefsArray<'a, N, V, T>>,
        P: PinnedVec<Node<'a, V, T>>,
    {
        vec_mut.get_next_array_mut(self)
    }

    // helpers - test
    pub(crate) fn ref_eq(&self, other: &Self) -> bool {
        let left = self as *const Self;
        let right = other as *const Self;
        left == right
    }

    pub(crate) fn ref_eq_to_ptr(&self, other: *const Node<'a, V, T>) -> bool {
        let left = self as *const Self;
        left == other
    }
}

impl<'a, V, T> Clone for Node<'a, V, T>
where
    V: Variant<'a, T>,
    V::Storage: Clone,
    T: Clone,
{
    /// Clones the node data without the references.
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            prev: Default::default(),
            next: Default::default(),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::{
        MemoryReclaimOnThreshold, NodeData, NodeRefSingle, NodeRefs, NodeRefsArray, NodeRefsVec,
        SelfRefCol,
    };
    use orx_split_vec::prelude::PinnedVec;

    struct Var;
    impl<'a> Variant<'a, char> for Var {
        type Storage = NodeDataLazyClose<char>;
        type Prev = NodeRefSingle<'a, Self, char>;
        type Next = NodeRefsVec<'a, Self, char>;
        type Ends = NodeRefsArray<'a, 2, Self, char>;
        type MemoryReclaim = MemoryReclaimOnThreshold<2>;
    }

    #[test]
    fn new_free_node() {
        let node = Node::<Var, _>::new_free_node('x');
        assert!(node.prev().get().is_none());
        assert!(node.next().get().is_empty());
        assert_eq!(Some(&'x'), node.data());
    }

    #[test]
    fn new() {
        let x = Node::<Var, _>::new_free_node('x');
        let y = Node::<Var, _>::new_free_node('y');
        let node = Node::<Var, _>::new(
            NodeDataLazyClose::active('z'),
            NodeRefSingle::new(Some(&x)),
            NodeRefsVec::new(vec![&y]),
        );

        assert!(node.prev().get().unwrap().ref_eq(&x));
        assert!(node.next().get()[0].ref_eq(&y));
        assert_eq!(Some(&'z'), node.data());
    }

    #[test]
    fn data_mut() {
        let mut node = Node::<Var, _>::new_free_node('x');
        assert_eq!(Some(&'x'), node.data());

        *node.data_mut().unwrap() = 'y';
        assert_eq!(Some(&'y'), node.data());
    }

    #[test]
    fn swap_data() {
        let mut vec = SelfRefCol::<Var, _>::new();

        {
            let x = SelfRefColMut::new(&mut vec);
            let rf = x.push_get_ref('a');
            x.set_ends([Some(rf), None]);
        }

        assert_eq!(vec.pinned_vec.len(), 1);
        assert_eq!(vec.pinned_vec.get(0).unwrap().data().unwrap(), &'a');

        {
            let x = SelfRefColMut::new(&mut vec);
            let first = x.ends().get()[0].unwrap();
            let old_value = x.swap_data(first, 'z');
            assert_eq!('a', old_value);
        }

        assert_eq!(vec.pinned_vec.len(), 1);
        assert_eq!(vec.pinned_vec.get(0).unwrap().data().unwrap(), &'z');

        {
            let x = SelfRefColMut::new(&mut vec);
            let first = x.ends().get()[0].unwrap();
            let old_value = first.swap_data(&x, 'o');
            assert_eq!('z', old_value);
        }

        assert_eq!(vec.pinned_vec.len(), 1);
        assert_eq!(vec.pinned_vec.get(0).unwrap().data().unwrap(), &'o');
    }

    #[test]
    fn close_node_take_data() {
        let mut vec = SelfRefCol::<Var, _>::new();
        assert!(vec.pinned_vec.is_empty());

        {
            let x = SelfRefColMut::new(&mut vec);
            let a = x.push_get_ref('a');
            assert!(a.is_active());

            let val_a = a.close_node_take_data(&x);
            assert_eq!('a', val_a);
            assert!(a.is_closed());
        }
    }

    #[test]
    #[should_panic]
    fn close_node_take_data_on_closed_node() {
        let mut vec = SelfRefCol::<Var, _>::new();
        let x = SelfRefColMut::new(&mut vec);
        let a = x.push_get_ref('a');
        assert!(a.is_active());

        let val_a = a.close_node_take_data(&x);
        assert_eq!('a', val_a);
        assert!(a.is_closed());

        let _ = a.close_node_take_data(&x); // panics!
    }

    #[test]
    fn set_clear_prev_next_single() {
        struct Var;
        impl<'a> Variant<'a, char> for Var {
            type Storage = NodeDataLazyClose<char>;
            type Prev = NodeRefSingle<'a, Self, char>;
            type Next = NodeRefSingle<'a, Self, char>;
            type Ends = NodeRefsArray<'a, 2, Self, char>;
            type MemoryReclaim = MemoryReclaimOnThreshold<2>;
        }

        let mut vec = SelfRefCol::<Var, _>::new();
        assert!(vec.pinned_vec.is_empty());

        {
            let x = SelfRefColMut::new(&mut vec);
            let a = x.push_get_ref('a');
            let b = x.push_get_ref('b');

            a.set_prev_refs(&x, b.into());
            assert!(a.prev().get().unwrap().ref_eq(b));

            a.set_prev(&x, b);
            assert!(a.prev().get().unwrap().ref_eq(b));

            a.set_prev(&x, b);
            assert!(a.prev().get().unwrap().ref_eq(b));

            a.clear_prev(&x);
            assert!(a.prev().get().is_none());

            a.set_prev_refs(&x, NodeRefSingle::empty());
            assert!(a.prev().get().is_none());

            b.set_next(&x, a);
            assert!(b.next().get().unwrap().ref_eq(a));

            b.set_next(&x, a);
            assert!(b.next().get().unwrap().ref_eq(a));

            b.clear_next(&x);
            assert!(b.next().get().is_none());

            a.set_next(&x, b);
            b.set_prev(&x, a);
        }

        let a = &vec.pinned_vec[0];
        let b = &vec.pinned_vec[1];
        assert!(a.next().get().unwrap().ref_eq(b));
        assert!(b.prev().get().unwrap().ref_eq(a));
    }

    #[test]
    fn set_clear_prev_next_vec() {
        struct Var;
        impl<'a> Variant<'a, char> for Var {
            type Storage = NodeDataLazyClose<char>;
            type Prev = NodeRefsVec<'a, Self, char>;
            type Next = NodeRefsVec<'a, Self, char>;
            type Ends = NodeRefsArray<'a, 2, Self, char>;
            type MemoryReclaim = MemoryReclaimOnThreshold<2>;
        }

        let mut vec = SelfRefCol::<Var, _>::new();
        assert!(vec.pinned_vec.is_empty());

        {
            let x = SelfRefColMut::new(&mut vec);
            let a = x.push_get_ref('a');
            let b = x.push_get_ref('b');
            let c = x.push_get_ref('c');

            a.set_next_refs(&x, NodeRefsVec::new(vec![b]));
            assert_eq!(a.next().get().len(), 1);
            assert!(a.next().get().first().unwrap().ref_eq(b));

            a.set_next(&x, vec![b]);
            assert_eq!(a.next().get().len(), 1);
            assert!(a.next().get().first().unwrap().ref_eq(b));

            a.next_vec_mut(&x).push(c);

            assert_eq!(a.next().get().len(), 2);
            assert!(a.next().get().first().unwrap().ref_eq(b));
            assert!(a.next().get().get(1).unwrap().ref_eq(c));

            a.clear_next(&x);
            assert!(a.next().get().is_empty());

            a.set_next(&x, NodeRefsVec::empty());
            assert!(a.next().get().is_empty());

            b.set_prev(&x, vec![a]);
            assert_eq!(b.prev().get().len(), 1);
            assert!(b.prev().get().first().unwrap().ref_eq(a));

            c.set_prev(&x, vec![a, b]);
            assert_eq!(c.prev().get().len(), 2);
            assert!(c.prev().get().first().unwrap().ref_eq(a));
            assert!(c.prev().get().get(1).unwrap().ref_eq(b));

            c.prev_vec_mut(&x).remove(0);
            assert_eq!(c.prev().get().len(), 1);
            assert!(c.prev().get().first().unwrap().ref_eq(b));

            c.clear_prev(&x);
            assert!(c.prev().get().is_empty());
        }
    }

    #[test]
    fn set_clear_prev_next_array() {
        struct Var;
        impl<'a> Variant<'a, char> for Var {
            type Storage = NodeDataLazyClose<char>;
            type Prev = NodeRefsArray<'a, 1, Self, char>;
            type Next = NodeRefsArray<'a, 2, Self, char>;
            type Ends = NodeRefsArray<'a, 2, Self, char>;
            type MemoryReclaim = MemoryReclaimOnThreshold<2>;
        }

        let mut vec = SelfRefCol::<Var, _>::new();
        assert!(vec.pinned_vec.is_empty());

        {
            let x = SelfRefColMut::new(&mut vec);
            let a = x.push_get_ref('a');
            let b = x.push_get_ref('b');
            let c = x.push_get_ref('c');

            a.set_next_refs(&x, NodeRefsArray::new([Some(b), Some(c)]));
            assert!(a.next().get()[0].unwrap().ref_eq(b));
            assert!(a.next().get()[1].unwrap().ref_eq(c));

            a.set_next(&x, [Some(b), None]);
            assert!(a.next().get()[0].unwrap().ref_eq(b));
            assert!(a.next().get()[1].is_none());

            a.next_array_mut(&x)[1] = Some(c);
            assert!(a.next().get()[1].unwrap().ref_eq(c));

            a.clear_next(&x);
            assert!(a.next().get()[0].is_none());
            assert!(a.next().get()[1].is_none());

            a.set_next(&x, NodeRefsArray::empty());
            assert!(a.next().get()[0].is_none());
            assert!(a.next().get()[1].is_none());

            b.set_prev_refs(&x, NodeRefsArray::new([Some(a)]));
            assert!(b.prev().get()[0].unwrap().ref_eq(a));

            b.prev_array_mut(&x)[0] = None;
            assert!(b.prev().get()[0].is_none());

            b.set_prev(&x, [Some(c)]);
            assert!(b.prev().get()[0].unwrap().ref_eq(c));

            b.clear_prev(&x);
            assert!(b.prev().get()[0].is_none());
        }
    }
}