cycle_ptr 0.1.0

Smart pointers, with cycles
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
//! An implementation of a linked-list.
use crate::list::linked_list::state::ListEntry;
use crate::list::linked_list::traits::ListElement;
use crate::util::NonNull;
use std::fmt;
use std::marker::PhantomData;
use std::pin::Pin;
#[cfg(any(test, feature = "linked_list_reachability_assert"))]
use std::ptr;

/// A linked list containing `Type`.
pub(crate) struct List<Type, Tag>
where
    Type: ListElement<Tag, Type = Type> + ?Sized,
{
    /// First element of the list.
    ///
    /// [None] if the list is empty.
    head: Option<NonNull<Type>>,
    /// Last element of the list.
    ///
    /// [None] if the list is empty.
    tail: Option<NonNull<Type>>,
    /// Size of the list.
    sz: usize,

    /// Track tag.
    tag: PhantomData<Tag>,
}

/// Iterator for [List].
pub(crate) struct ListIterator<'elem_lifetime, Type, Tag>
where
    Type: 'elem_lifetime + ListElement<Tag, Type = Type> + ?Sized,
{
    /// Next element.
    next: Option<NonNull<Type>>,
    /// Remaining number of elements.
    remaining: usize,

    /// Track lifetime of elements.
    self_lifetime: PhantomData<&'elem_lifetime ()>,
    /// Track tag.
    tag: PhantomData<Tag>,
}

/// Consuming iterator for [List].
pub(crate) struct PopFrontIterator<Type, Tag>
where
    Type: 'static + ListElement<Tag, Type = Type> + ?Sized,
{
    /// List from which elements are consumed by this iterator.
    list: List<Type, Tag>,
}

/// Create an empty list.
impl<Type, Tag> Default for List<Type, Tag>
where
    Type: ListElement<Tag, Type = Type> + ?Sized,
{
    fn default() -> Self {
        List {
            head: None,
            tail: None,
            sz: 0,
            tag: PhantomData,
        }
    }
}

/// We implement [Drop] to assert a list is empty when it's dropped.
impl<Type, Tag> Drop for List<Type, Tag>
where
    Type: ListElement<Tag, Type = Type> + ?Sized,
{
    fn drop(&mut self) {
        self.clear();
        assert!(
            self.head.is_none() && self.tail.is_none(),
            "dropped list must be empty"
        );
    }
}

impl<Type, Tag> fmt::Debug for List<Type, Tag>
where
    Type: fmt::Debug + ListElement<Tag, Type = Type> + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<Type, Tag> IntoIterator for List<Type, Tag>
where
    Type: 'static + ListElement<Tag, Type = Type> + ?Sized,
{
    type Item = Pin<&'static Type>;
    type IntoIter = PopFrontIterator<Type, Tag>;

    fn into_iter(self) -> Self::IntoIter {
        PopFrontIterator { list: self }
    }
}

/// A list is [Send], if its contained type is [Send].
unsafe impl<Type, Tag> Send for List<Type, Tag>
where
    Type: ListElement<Tag, Type = Type> + Send + ?Sized,
    Tag: Send,
{
}

impl<Type, Tag> List<Type, Tag>
where
    Type: ListElement<Tag, Type = Type> + ?Sized,
{
    /// Dereference a pointer.
    const unsafe fn get_ref<'a>(p: NonNull<Type>) -> &'a Type {
        unsafe { p.into_ref() }
    }

    /// Get the [ListEntry] for a pointer.
    unsafe fn get_entry<'a>(p: NonNull<Type>) -> &'a ListEntry<Type> {
        unsafe { Self::get_ref(p).get_entry() }
    }

    /// Get the [ListEntry] for a pointer.
    unsafe fn get_entry_mut<'a>(p: NonNull<Type>) -> &'a mut ListEntry<Type> {
        unsafe { Self::get_ref(p).get_entry_mut() }
    }

    /// Run assertions to confirm the invariant holds.
    fn assert_invariant(&self) {
        assert!(
            self.head.is_none() == self.tail.is_none(),
            "head and tail must agree on if there are some/none elements in the list"
        );
    }

    /// Test if an element is present in the list.
    ///
    /// This function does not run [List::assert_invariant].
    #[cfg(any(test, feature = "linked_list_reachability_assert"))]
    fn reachable(&self, e: &Type) -> bool {
        let mut iter = self.head.clone();
        while let Some(iter_elem_ref) = iter.map(|ptr| unsafe { Self::get_ref(ptr) }) {
            if ptr::eq(iter_elem_ref, e) {
                return true;
            }
            // advance
            iter = iter_elem_ref.get_entry().succ.clone();
        }
        false
    }

    /// Link an element into the list.
    ///
    /// `e`: element that is to be inserted.
    /// `opt_pred`: predecessor of `e`. [None] indicates that `e` is inserted at the front of the list.
    /// `opt_succ`: successor of `e`. [None] indicates that `e` is inserted at the back of the list.
    ///
    /// Returns a pointer to the inserted element.
    fn link_element(
        &mut self,
        e: Pin<&Type>,
        opt_pred: Option<NonNull<Type>>,
        opt_succ: Option<NonNull<Type>>,
    ) -> NonNull<Type> {
        let e_ptr: NonNull<Type> = NonNull::from_ref(e.get_ref());
        let e_entry: &mut ListEntry<Type> = unsafe { Self::get_entry_mut(e_ptr.clone()) };

        // Confirm `e` isn't part of a list already.
        assert!(
            !e_entry.linked,
            "to-be-inserted element must not be part of a list already"
        );
        assert!(
            e_entry.succ.is_none() && e_entry.pred.is_none(),
            "predecessor and successor pointers should be None"
        );

        self.assert_invariant();

        // Confirm predecessor is correctly linked.
        match opt_pred
            .clone()
            .map(|pred| unsafe { Self::get_entry(pred) })
        {
            Some(pred_entry) => assert_eq!(
                pred_entry.succ, opt_succ,
                "pred's successor must match opt_succ"
            ),
            None => assert_eq!(self.head, opt_succ),
        }

        // Confirm successor is correctly linked.
        match opt_succ
            .clone()
            .map(|succ| unsafe { Self::get_entry(succ) })
        {
            Some(succ_entry) => assert_eq!(
                succ_entry.pred, opt_pred,
                "succ's predecessor must match opt_pred"
            ),
            None => assert_eq!(self.tail, opt_pred),
        }

        // Confirm that predecessor or successor is in the list.
        // (Since we've already asserted that they're eachother's predecessor/successor,
        // we know that if one of them is in the list, both of them are.)
        #[cfg(feature = "linked_list_reachability_assert")]
        if let Some(predecessor_or_successor_ref) = opt_pred
            .clone()
            .or(opt_succ.clone())
            .map(|ptr| unsafe { Self::get_ref(ptr) })
        {
            debug_assert!(self.reachable(predecessor_or_successor_ref));
        }

        // ------------------------------------------------------------
        // All assertions are completed.
        // Changes are only made past this point.

        // Update predecessor of `e`.
        match opt_pred
            .clone()
            .map(|ptr| unsafe { Self::get_entry_mut(ptr) })
        {
            Some(pred_state) => pred_state.succ = Some(e_ptr.clone()),
            None => self.head = Some(e_ptr.clone()),
        }

        // Update successor of `e`.
        match opt_succ
            .clone()
            .map(|ptr| unsafe { Self::get_entry_mut(ptr) })
        {
            Some(succ_state) => succ_state.pred = Some(e_ptr.clone()),
            None => self.tail = Some(e_ptr.clone()),
        }

        // Update `e`.
        e_entry.succ = opt_succ;
        e_entry.pred = opt_pred;
        e_entry.linked = true;

        // Update list size.
        self.sz += 1;

        self.assert_invariant(); // Invariant must be maintained.
        #[cfg(feature = "linked_list_reachability_assert")]
        debug_assert!(self.reachable(unsafe { Self::get_ref(e_ptr.clone()) }));
        e_ptr
    }

    /// Unlink an element.
    fn unlink_element<'a>(&mut self, e_ptr: NonNull<Type>) -> Pin<&'a Type> {
        let e_entry: &mut ListEntry<Type> = unsafe { Self::get_entry_mut(e_ptr.clone()) };
        let pred = e_entry.pred.clone();
        let succ = e_entry.succ.clone();

        self.assert_invariant();
        #[cfg(feature = "linked_list_reachability_assert")]
        debug_assert!(
            self.reachable(unsafe { Self::get_ref(e_ptr.clone()) }),
            "unlinked element must be part of this list"
        );

        // Confirm that the predecessor indeed links back to us.
        match pred.clone().map(|ptr| unsafe { Self::get_entry(ptr) }) {
            Some(pred_entry) => assert_eq!(pred_entry.succ, Some(e_ptr.clone())),
            None => assert_eq!(self.head, Some(e_ptr.clone())),
        }

        // Confirm that the successor indeed links back to us.
        match succ.clone().map(|ptr| unsafe { Self::get_entry(ptr) }) {
            Some(succ_entry) => assert_eq!(succ_entry.pred, Some(e_ptr.clone())),
            None => assert_eq!(self.tail, Some(e_ptr.clone())),
        }

        // ------------------------------------------------------------
        // All assertions are completed.
        // Changes are only made past this point.

        // Update predecessor of `e`.
        match pred.clone().map(|ptr| unsafe { Self::get_entry_mut(ptr) }) {
            Some(pred_entry) => pred_entry.succ = succ.clone(),
            None => self.head = succ.clone(),
        }

        // Update successor of `e`.
        match succ.clone().map(|ptr| unsafe { Self::get_entry_mut(ptr) }) {
            Some(succ_entry) => succ_entry.pred = pred.clone(),
            None => self.tail = pred.clone(),
        }

        // Update `e`.
        e_entry.succ = None;
        e_entry.pred = None;
        e_entry.linked = false;

        // Update list size.
        self.sz -= 1;

        self.assert_invariant(); // Invariant must be maintained.
        #[cfg(feature = "linked_list_reachability_assert")]
        debug_assert!(!self.reachable(unsafe { Self::get_ref(e_ptr.clone()) }));
        unsafe { Pin::new_unchecked(Self::get_ref(e_ptr)) }
    }

    /// Test if the [List] is empty.
    pub(crate) fn is_empty(&self) -> bool {
        self.assert_invariant();
        self.head.is_none()
    }

    /// Get the number of elements in the [List].
    pub(crate) fn len(&self) -> usize {
        self.assert_invariant();
        self.sz
    }

    /// Insert an element at the back of the list.
    pub(crate) fn push_back(&mut self, e: Pin<&Type>) {
        self.link_element(e, self.tail.clone(), None);
    }

    /// Test if an element is in the list.
    #[cfg(test)]
    pub(crate) fn contains(&self, e: &Type) -> bool {
        self.assert_invariant();
        self.reachable(e)
    }

    /// Remove an element from the list.
    pub(crate) fn remove<'a>(&mut self, e: &'a Type) -> Pin<&'a Type> {
        self.unlink_element(NonNull::from_ref(e))
    }

    /// Iterate over the list items.
    pub(crate) fn iter(&self) -> ListIterator<'_, Type, Tag> {
        self.assert_invariant();
        ListIterator {
            next: self.head.clone(),
            remaining: self.sz,
            self_lifetime: PhantomData,
            tag: self.tag,
        }
    }

    /// Unlink all elements on the list.
    pub(crate) fn clear(&mut self) {
        while let Some(entry) = self.head.clone() {
            self.unlink_element(entry);
        }
    }

    /// Unlink the first element on the list.
    ///
    /// Returns a reference to the unlinked element.
    /// Returns [None] if the list is empty.
    fn pop_front(&mut self) -> Option<Pin<&'static Type>> {
        self.head.clone().map(|ptr| self.unlink_element(ptr))
    }

    /// Unlink the last element on the list.
    ///
    /// Returns a reference to the unlinked element.
    /// Returns [None] if the list is empty.
    pub(crate) fn pop_back<'a>(&mut self) -> Option<Pin<&'a Type>> {
        self.tail.clone().map(|ptr| self.unlink_element(ptr))
    }

    /// Merge all elements from `other` into the list.
    ///
    /// `other` will become empty.
    #[cfg(not(all(
        feature = "single_generation",
        any(feature = "single_generation_mt", not(feature = "multi_thread"))
    )))]
    pub(crate) fn merge(&mut self, other: &mut Self) {
        self.assert_invariant();
        other.assert_invariant();

        if !other.is_empty() {
            if self.is_empty() {
                self.head = other.head.take();
                self.tail = other.tail.take();
            } else {
                unsafe {
                    Self::get_entry_mut(other.head.as_ref().unwrap().clone()).pred =
                        self.tail.clone();
                    Self::get_entry_mut(self.tail.as_ref().unwrap().clone()).succ =
                        other.head.clone();
                    self.tail = other.tail.take();
                    other.head = None;
                }
            }

            self.sz += other.sz;
            other.sz = 0;
        }

        self.assert_invariant();
        other.assert_invariant();
    }
}

impl<'elem_lifetime, Type, Tag> Default for ListIterator<'elem_lifetime, Type, Tag>
where
    Type: 'elem_lifetime + ListElement<Tag, Type = Type> + ?Sized,
{
    fn default() -> Self {
        ListIterator {
            next: None,
            remaining: 0,
            self_lifetime: PhantomData,
            tag: PhantomData,
        }
    }
}

impl<'elem_lifetime, Type, Tag> Clone for ListIterator<'elem_lifetime, Type, Tag>
where
    Type: 'elem_lifetime + ListElement<Tag, Type = Type> + ?Sized,
{
    fn clone(&self) -> Self {
        ListIterator {
            next: self.next.clone(),
            remaining: self.remaining,
            self_lifetime: self.self_lifetime,
            tag: self.tag,
        }
    }
}

impl<'elem_lifetime, Type, Tag> Iterator for ListIterator<'elem_lifetime, Type, Tag>
where
    Type: 'elem_lifetime + ListElement<Tag, Type = Type> + ?Sized,
{
    type Item = Pin<&'elem_lifetime Type>;

    fn next(&mut self) -> Option<Self::Item> {
        match self
            .next
            .clone()
            .map(|ptr| unsafe { List::<Type, Tag>::get_ref(ptr) })
        {
            Some(next_elem) => {
                assert!(self.remaining > 0);
                self.next = next_elem.get_entry().succ.clone();
                self.remaining -= 1;
                Some(unsafe { Pin::new_unchecked(next_elem) })
            }
            None => {
                assert_eq!(self.remaining, 0);
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'elem_lifetime, Type, Tag> ExactSizeIterator for ListIterator<'elem_lifetime, Type, Tag>
where
    Type: 'elem_lifetime + ListElement<Tag, Type = Type> + ?Sized,
{
    fn len(&self) -> usize {
        self.remaining
    }
}

impl<Type, Tag> Iterator for PopFrontIterator<Type, Tag>
where
    Type: 'static + ListElement<Tag, Type = Type> + ?Sized,
{
    type Item = Pin<&'static Type>;

    fn next(&mut self) -> Option<Self::Item> {
        self.list.pop_front()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.list.len(), Some(self.list.len()))
    }
}

impl<Type, Tag> ExactSizeIterator for PopFrontIterator<Type, Tag>
where
    Type: 'static + ListElement<Tag, Type = Type> + ?Sized,
{
    fn len(&self) -> usize {
        self.list.len()
    }
}