kernel/
list.rs

1// SPDX-License-Identifier: GPL-2.0
2
3// Copyright (C) 2024 Google LLC.
4
5//! A linked list implementation.
6
7use crate::sync::ArcBorrow;
8use crate::types::Opaque;
9use core::iter::{DoubleEndedIterator, FusedIterator};
10use core::marker::PhantomData;
11use core::ptr;
12use pin_init::PinInit;
13
14mod impl_list_item_mod;
15pub use self::impl_list_item_mod::{
16    impl_has_list_links, impl_has_list_links_self_ptr, impl_list_item, HasListLinks, HasSelfPtr,
17};
18
19mod arc;
20pub use self::arc::{impl_list_arc_safe, AtomicTracker, ListArc, ListArcSafe, TryNewListArc};
21
22mod arc_field;
23pub use self::arc_field::{define_list_arc_field_getter, ListArcField};
24
25/// A linked list.
26///
27/// All elements in this linked list will be [`ListArc`] references to the value. Since a value can
28/// only have one `ListArc` (for each pair of prev/next pointers), this ensures that the same
29/// prev/next pointers are not used for several linked lists.
30///
31/// # Invariants
32///
33/// * If the list is empty, then `first` is null. Otherwise, `first` points at the `ListLinks`
34///   field of the first element in the list.
35/// * All prev/next pointers in `ListLinks` fields of items in the list are valid and form a cycle.
36/// * For every item in the list, the list owns the associated [`ListArc`] reference and has
37///   exclusive access to the `ListLinks` field.
38pub struct List<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
39    first: *mut ListLinksFields,
40    _ty: PhantomData<ListArc<T, ID>>,
41}
42
43// SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same
44// type of access to the `ListArc<T, ID>` elements.
45unsafe impl<T, const ID: u64> Send for List<T, ID>
46where
47    ListArc<T, ID>: Send,
48    T: ?Sized + ListItem<ID>,
49{
50}
51// SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same
52// type of access to the `ListArc<T, ID>` elements.
53unsafe impl<T, const ID: u64> Sync for List<T, ID>
54where
55    ListArc<T, ID>: Sync,
56    T: ?Sized + ListItem<ID>,
57{
58}
59
60/// Implemented by types where a [`ListArc<Self>`] can be inserted into a [`List`].
61///
62/// # Safety
63///
64/// Implementers must ensure that they provide the guarantees documented on methods provided by
65/// this trait.
66///
67/// [`ListArc<Self>`]: ListArc
68pub unsafe trait ListItem<const ID: u64 = 0>: ListArcSafe<ID> {
69    /// Views the [`ListLinks`] for this value.
70    ///
71    /// # Guarantees
72    ///
73    /// If there is a previous call to `prepare_to_insert` and there is no call to `post_remove`
74    /// since the most recent such call, then this returns the same pointer as the one returned by
75    /// the most recent call to `prepare_to_insert`.
76    ///
77    /// Otherwise, the returned pointer points at a read-only [`ListLinks`] with two null pointers.
78    ///
79    /// # Safety
80    ///
81    /// The provided pointer must point at a valid value. (It need not be in an `Arc`.)
82    unsafe fn view_links(me: *const Self) -> *mut ListLinks<ID>;
83
84    /// View the full value given its [`ListLinks`] field.
85    ///
86    /// Can only be used when the value is in a list.
87    ///
88    /// # Guarantees
89    ///
90    /// * Returns the same pointer as the one passed to the most recent call to `prepare_to_insert`.
91    /// * The returned pointer is valid until the next call to `post_remove`.
92    ///
93    /// # Safety
94    ///
95    /// * The provided pointer must originate from the most recent call to `prepare_to_insert`, or
96    ///   from a call to `view_links` that happened after the most recent call to
97    ///   `prepare_to_insert`.
98    /// * Since the most recent call to `prepare_to_insert`, the `post_remove` method must not have
99    ///   been called.
100    unsafe fn view_value(me: *mut ListLinks<ID>) -> *const Self;
101
102    /// This is called when an item is inserted into a [`List`].
103    ///
104    /// # Guarantees
105    ///
106    /// The caller is granted exclusive access to the returned [`ListLinks`] until `post_remove` is
107    /// called.
108    ///
109    /// # Safety
110    ///
111    /// * The provided pointer must point at a valid value in an [`Arc`].
112    /// * Calls to `prepare_to_insert` and `post_remove` on the same value must alternate.
113    /// * The caller must own the [`ListArc`] for this value.
114    /// * The caller must not give up ownership of the [`ListArc`] unless `post_remove` has been
115    ///   called after this call to `prepare_to_insert`.
116    ///
117    /// [`Arc`]: crate::sync::Arc
118    unsafe fn prepare_to_insert(me: *const Self) -> *mut ListLinks<ID>;
119
120    /// This undoes a previous call to `prepare_to_insert`.
121    ///
122    /// # Guarantees
123    ///
124    /// The returned pointer is the pointer that was originally passed to `prepare_to_insert`.
125    ///
126    /// # Safety
127    ///
128    /// The provided pointer must be the pointer returned by the most recent call to
129    /// `prepare_to_insert`.
130    unsafe fn post_remove(me: *mut ListLinks<ID>) -> *const Self;
131}
132
133#[repr(C)]
134#[derive(Copy, Clone)]
135struct ListLinksFields {
136    next: *mut ListLinksFields,
137    prev: *mut ListLinksFields,
138}
139
140/// The prev/next pointers for an item in a linked list.
141///
142/// # Invariants
143///
144/// The fields are null if and only if this item is not in a list.
145#[repr(transparent)]
146pub struct ListLinks<const ID: u64 = 0> {
147    // This type is `!Unpin` for aliasing reasons as the pointers are part of an intrusive linked
148    // list.
149    inner: Opaque<ListLinksFields>,
150}
151
152// SAFETY: The only way to access/modify the pointers inside of `ListLinks<ID>` is via holding the
153// associated `ListArc<T, ID>`. Since that type correctly implements `Send`, it is impossible to
154// move this an instance of this type to a different thread if the pointees are `!Send`.
155unsafe impl<const ID: u64> Send for ListLinks<ID> {}
156// SAFETY: The type is opaque so immutable references to a ListLinks are useless. Therefore, it's
157// okay to have immutable access to a ListLinks from several threads at once.
158unsafe impl<const ID: u64> Sync for ListLinks<ID> {}
159
160impl<const ID: u64> ListLinks<ID> {
161    /// Creates a new initializer for this type.
162    pub fn new() -> impl PinInit<Self> {
163        // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
164        // not be constructed in an `Arc` that already has a `ListArc`.
165        ListLinks {
166            inner: Opaque::new(ListLinksFields {
167                prev: ptr::null_mut(),
168                next: ptr::null_mut(),
169            }),
170        }
171    }
172
173    /// # Safety
174    ///
175    /// `me` must be dereferenceable.
176    #[inline]
177    unsafe fn fields(me: *mut Self) -> *mut ListLinksFields {
178        // SAFETY: The caller promises that the pointer is valid.
179        unsafe { Opaque::raw_get(ptr::addr_of!((*me).inner)) }
180    }
181
182    /// # Safety
183    ///
184    /// `me` must be dereferenceable.
185    #[inline]
186    unsafe fn from_fields(me: *mut ListLinksFields) -> *mut Self {
187        me.cast()
188    }
189}
190
191/// Similar to [`ListLinks`], but also contains a pointer to the full value.
192///
193/// This type can be used instead of [`ListLinks`] to support lists with trait objects.
194#[repr(C)]
195pub struct ListLinksSelfPtr<T: ?Sized, const ID: u64 = 0> {
196    /// The `ListLinks` field inside this value.
197    ///
198    /// This is public so that it can be used with `impl_has_list_links!`.
199    pub inner: ListLinks<ID>,
200    // UnsafeCell is not enough here because we use `Opaque::uninit` as a dummy value, and
201    // `ptr::null()` doesn't work for `T: ?Sized`.
202    self_ptr: Opaque<*const T>,
203}
204
205// SAFETY: The fields of a ListLinksSelfPtr can be moved across thread boundaries.
206unsafe impl<T: ?Sized + Send, const ID: u64> Send for ListLinksSelfPtr<T, ID> {}
207// SAFETY: The type is opaque so immutable references to a ListLinksSelfPtr are useless. Therefore,
208// it's okay to have immutable access to a ListLinks from several threads at once.
209//
210// Note that `inner` being a public field does not prevent this type from being opaque, since
211// `inner` is a opaque type.
212unsafe impl<T: ?Sized + Sync, const ID: u64> Sync for ListLinksSelfPtr<T, ID> {}
213
214impl<T: ?Sized, const ID: u64> ListLinksSelfPtr<T, ID> {
215    /// The offset from the [`ListLinks`] to the self pointer field.
216    pub const LIST_LINKS_SELF_PTR_OFFSET: usize = core::mem::offset_of!(Self, self_ptr);
217
218    /// Creates a new initializer for this type.
219    pub fn new() -> impl PinInit<Self> {
220        // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
221        // not be constructed in an `Arc` that already has a `ListArc`.
222        Self {
223            inner: ListLinks {
224                inner: Opaque::new(ListLinksFields {
225                    prev: ptr::null_mut(),
226                    next: ptr::null_mut(),
227                }),
228            },
229            self_ptr: Opaque::uninit(),
230        }
231    }
232}
233
234impl<T: ?Sized + ListItem<ID>, const ID: u64> List<T, ID> {
235    /// Creates a new empty list.
236    pub const fn new() -> Self {
237        Self {
238            first: ptr::null_mut(),
239            _ty: PhantomData,
240        }
241    }
242
243    /// Returns whether this list is empty.
244    pub fn is_empty(&self) -> bool {
245        self.first.is_null()
246    }
247
248    /// Inserts `item` before `next` in the cycle.
249    ///
250    /// Returns a pointer to the newly inserted element. Never changes `self.first` unless the list
251    /// is empty.
252    ///
253    /// # Safety
254    ///
255    /// * `next` must be an element in this list or null.
256    /// * if `next` is null, then the list must be empty.
257    unsafe fn insert_inner(
258        &mut self,
259        item: ListArc<T, ID>,
260        next: *mut ListLinksFields,
261    ) -> *mut ListLinksFields {
262        let raw_item = ListArc::into_raw(item);
263        // SAFETY:
264        // * We just got `raw_item` from a `ListArc`, so it's in an `Arc`.
265        // * Since we have ownership of the `ListArc`, `post_remove` must have been called after
266        //   the most recent call to `prepare_to_insert`, if any.
267        // * We own the `ListArc`.
268        // * Removing items from this list is always done using `remove_internal_inner`, which
269        //   calls `post_remove` before giving up ownership.
270        let list_links = unsafe { T::prepare_to_insert(raw_item) };
271        // SAFETY: We have not yet called `post_remove`, so `list_links` is still valid.
272        let item = unsafe { ListLinks::fields(list_links) };
273
274        // Check if the list is empty.
275        if next.is_null() {
276            // SAFETY: The caller just gave us ownership of these fields.
277            // INVARIANT: A linked list with one item should be cyclic.
278            unsafe {
279                (*item).next = item;
280                (*item).prev = item;
281            }
282            self.first = item;
283        } else {
284            // SAFETY: By the type invariant, this pointer is valid or null. We just checked that
285            // it's not null, so it must be valid.
286            let prev = unsafe { (*next).prev };
287            // SAFETY: Pointers in a linked list are never dangling, and the caller just gave us
288            // ownership of the fields on `item`.
289            // INVARIANT: This correctly inserts `item` between `prev` and `next`.
290            unsafe {
291                (*item).next = next;
292                (*item).prev = prev;
293                (*prev).next = item;
294                (*next).prev = item;
295            }
296        }
297
298        item
299    }
300
301    /// Add the provided item to the back of the list.
302    pub fn push_back(&mut self, item: ListArc<T, ID>) {
303        // SAFETY:
304        // * `self.first` is null or in the list.
305        // * `self.first` is only null if the list is empty.
306        unsafe { self.insert_inner(item, self.first) };
307    }
308
309    /// Add the provided item to the front of the list.
310    pub fn push_front(&mut self, item: ListArc<T, ID>) {
311        // SAFETY:
312        // * `self.first` is null or in the list.
313        // * `self.first` is only null if the list is empty.
314        let new_elem = unsafe { self.insert_inner(item, self.first) };
315
316        // INVARIANT: `new_elem` is in the list because we just inserted it.
317        self.first = new_elem;
318    }
319
320    /// Removes the last item from this list.
321    pub fn pop_back(&mut self) -> Option<ListArc<T, ID>> {
322        if self.first.is_null() {
323            return None;
324        }
325
326        // SAFETY: We just checked that the list is not empty.
327        let last = unsafe { (*self.first).prev };
328        // SAFETY: The last item of this list is in this list.
329        Some(unsafe { self.remove_internal(last) })
330    }
331
332    /// Removes the first item from this list.
333    pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {
334        if self.first.is_null() {
335            return None;
336        }
337
338        // SAFETY: The first item of this list is in this list.
339        Some(unsafe { self.remove_internal(self.first) })
340    }
341
342    /// Removes the provided item from this list and returns it.
343    ///
344    /// This returns `None` if the item is not in the list. (Note that by the safety requirements,
345    /// this means that the item is not in any list.)
346    ///
347    /// # Safety
348    ///
349    /// `item` must not be in a different linked list (with the same id).
350    pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
351        // SAFETY: TODO.
352        let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
353        // SAFETY: The user provided a reference, and reference are never dangling.
354        //
355        // As for why this is not a data race, there are two cases:
356        //
357        //  * If `item` is not in any list, then these fields are read-only and null.
358        //  * If `item` is in this list, then we have exclusive access to these fields since we
359        //    have a mutable reference to the list.
360        //
361        // In either case, there's no race.
362        let ListLinksFields { next, prev } = unsafe { *item };
363
364        debug_assert_eq!(next.is_null(), prev.is_null());
365        if !next.is_null() {
366            // This is really a no-op, but this ensures that `item` is a raw pointer that was
367            // obtained without going through a pointer->reference->pointer conversion roundtrip.
368            // This ensures that the list is valid under the more restrictive strict provenance
369            // ruleset.
370            //
371            // SAFETY: We just checked that `next` is not null, and it's not dangling by the
372            // list invariants.
373            unsafe {
374                debug_assert_eq!(item, (*next).prev);
375                item = (*next).prev;
376            }
377
378            // SAFETY: We just checked that `item` is in a list, so the caller guarantees that it
379            // is in this list. The pointers are in the right order.
380            Some(unsafe { self.remove_internal_inner(item, next, prev) })
381        } else {
382            None
383        }
384    }
385
386    /// Removes the provided item from the list.
387    ///
388    /// # Safety
389    ///
390    /// `item` must point at an item in this list.
391    unsafe fn remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID> {
392        // SAFETY: The caller promises that this pointer is not dangling, and there's no data race
393        // since we have a mutable reference to the list containing `item`.
394        let ListLinksFields { next, prev } = unsafe { *item };
395        // SAFETY: The pointers are ok and in the right order.
396        unsafe { self.remove_internal_inner(item, next, prev) }
397    }
398
399    /// Removes the provided item from the list.
400    ///
401    /// # Safety
402    ///
403    /// The `item` pointer must point at an item in this list, and we must have `(*item).next ==
404    /// next` and `(*item).prev == prev`.
405    unsafe fn remove_internal_inner(
406        &mut self,
407        item: *mut ListLinksFields,
408        next: *mut ListLinksFields,
409        prev: *mut ListLinksFields,
410    ) -> ListArc<T, ID> {
411        // SAFETY: We have exclusive access to the pointers of items in the list, and the prev/next
412        // pointers are always valid for items in a list.
413        //
414        // INVARIANT: There are three cases:
415        //  * If the list has at least three items, then after removing the item, `prev` and `next`
416        //    will be next to each other.
417        //  * If the list has two items, then the remaining item will point at itself.
418        //  * If the list has one item, then `next == prev == item`, so these writes have no
419        //    effect. The list remains unchanged and `item` is still in the list for now.
420        unsafe {
421            (*next).prev = prev;
422            (*prev).next = next;
423        }
424        // SAFETY: We have exclusive access to items in the list.
425        // INVARIANT: `item` is being removed, so the pointers should be null.
426        unsafe {
427            (*item).prev = ptr::null_mut();
428            (*item).next = ptr::null_mut();
429        }
430        // INVARIANT: There are three cases:
431        //  * If `item` was not the first item, then `self.first` should remain unchanged.
432        //  * If `item` was the first item and there is another item, then we just updated
433        //    `prev->next` to `next`, which is the new first item, and setting `item->next` to null
434        //    did not modify `prev->next`.
435        //  * If `item` was the only item in the list, then `prev == item`, and we just set
436        //    `item->next` to null, so this correctly sets `first` to null now that the list is
437        //    empty.
438        if self.first == item {
439            // SAFETY: The `prev` pointer is the value that `item->prev` had when it was in this
440            // list, so it must be valid. There is no race since `prev` is still in the list and we
441            // still have exclusive access to the list.
442            self.first = unsafe { (*prev).next };
443        }
444
445        // SAFETY: `item` used to be in the list, so it is dereferenceable by the type invariants
446        // of `List`.
447        let list_links = unsafe { ListLinks::from_fields(item) };
448        // SAFETY: Any pointer in the list originates from a `prepare_to_insert` call.
449        let raw_item = unsafe { T::post_remove(list_links) };
450        // SAFETY: The above call to `post_remove` guarantees that we can recreate the `ListArc`.
451        unsafe { ListArc::from_raw(raw_item) }
452    }
453
454    /// Moves all items from `other` into `self`.
455    ///
456    /// The items of `other` are added to the back of `self`, so the last item of `other` becomes
457    /// the last item of `self`.
458    pub fn push_all_back(&mut self, other: &mut List<T, ID>) {
459        // First, we insert the elements into `self`. At the end, we make `other` empty.
460        if self.is_empty() {
461            // INVARIANT: All of the elements in `other` become elements of `self`.
462            self.first = other.first;
463        } else if !other.is_empty() {
464            let other_first = other.first;
465            // SAFETY: The other list is not empty, so this pointer is valid.
466            let other_last = unsafe { (*other_first).prev };
467            let self_first = self.first;
468            // SAFETY: The self list is not empty, so this pointer is valid.
469            let self_last = unsafe { (*self_first).prev };
470
471            // SAFETY: We have exclusive access to both lists, so we can update the pointers.
472            // INVARIANT: This correctly sets the pointers to merge both lists. We do not need to
473            // update `self.first` because the first element of `self` does not change.
474            unsafe {
475                (*self_first).prev = other_last;
476                (*other_last).next = self_first;
477                (*self_last).next = other_first;
478                (*other_first).prev = self_last;
479            }
480        }
481
482        // INVARIANT: The other list is now empty, so update its pointer.
483        other.first = ptr::null_mut();
484    }
485
486    /// Returns a cursor that points before the first element of the list.
487    pub fn cursor_front(&mut self) -> Cursor<'_, T, ID> {
488        // INVARIANT: `self.first` is in this list.
489        Cursor {
490            next: self.first,
491            list: self,
492        }
493    }
494
495    /// Returns a cursor that points after the last element in the list.
496    pub fn cursor_back(&mut self) -> Cursor<'_, T, ID> {
497        // INVARIANT: `next` is allowed to be null.
498        Cursor {
499            next: core::ptr::null_mut(),
500            list: self,
501        }
502    }
503
504    /// Creates an iterator over the list.
505    pub fn iter(&self) -> Iter<'_, T, ID> {
506        // INVARIANT: If the list is empty, both pointers are null. Otherwise, both pointers point
507        // at the first element of the same list.
508        Iter {
509            current: self.first,
510            stop: self.first,
511            _ty: PhantomData,
512        }
513    }
514}
515
516impl<T: ?Sized + ListItem<ID>, const ID: u64> Default for List<T, ID> {
517    fn default() -> Self {
518        List::new()
519    }
520}
521
522impl<T: ?Sized + ListItem<ID>, const ID: u64> Drop for List<T, ID> {
523    fn drop(&mut self) {
524        while let Some(item) = self.pop_front() {
525            drop(item);
526        }
527    }
528}
529
530/// An iterator over a [`List`].
531///
532/// # Invariants
533///
534/// * There must be a [`List`] that is immutably borrowed for the duration of `'a`.
535/// * The `current` pointer is null or points at a value in that [`List`].
536/// * The `stop` pointer is equal to the `first` field of that [`List`].
537#[derive(Clone)]
538pub struct Iter<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
539    current: *mut ListLinksFields,
540    stop: *mut ListLinksFields,
541    _ty: PhantomData<&'a ListArc<T, ID>>,
542}
543
544impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Iterator for Iter<'a, T, ID> {
545    type Item = ArcBorrow<'a, T>;
546
547    fn next(&mut self) -> Option<ArcBorrow<'a, T>> {
548        if self.current.is_null() {
549            return None;
550        }
551
552        let current = self.current;
553
554        // SAFETY: We just checked that `current` is not null, so it is in a list, and hence not
555        // dangling. There's no race because the iterator holds an immutable borrow to the list.
556        let next = unsafe { (*current).next };
557        // INVARIANT: If `current` was the last element of the list, then this updates it to null.
558        // Otherwise, we update it to the next element.
559        self.current = if next != self.stop {
560            next
561        } else {
562            ptr::null_mut()
563        };
564
565        // SAFETY: The `current` pointer points at a value in the list.
566        let item = unsafe { T::view_value(ListLinks::from_fields(current)) };
567        // SAFETY:
568        // * All values in a list are stored in an `Arc`.
569        // * The value cannot be removed from the list for the duration of the lifetime annotated
570        //   on the returned `ArcBorrow`, because removing it from the list would require mutable
571        //   access to the list. However, the `ArcBorrow` is annotated with the iterator's
572        //   lifetime, and the list is immutably borrowed for that lifetime.
573        // * Values in a list never have a `UniqueArc` reference.
574        Some(unsafe { ArcBorrow::from_raw(item) })
575    }
576}
577
578/// A cursor into a [`List`].
579///
580/// A cursor always rests between two elements in the list. This means that a cursor has a previous
581/// and next element, but no current element. It also means that it's possible to have a cursor
582/// into an empty list.
583///
584/// # Examples
585///
586/// ```
587/// use kernel::prelude::*;
588/// use kernel::list::{List, ListArc, ListLinks};
589///
590/// #[pin_data]
591/// struct ListItem {
592///     value: u32,
593///     #[pin]
594///     links: ListLinks,
595/// }
596///
597/// impl ListItem {
598///     fn new(value: u32) -> Result<ListArc<Self>> {
599///         ListArc::pin_init(try_pin_init!(Self {
600///             value,
601///             links <- ListLinks::new(),
602///         }), GFP_KERNEL)
603///     }
604/// }
605///
606/// kernel::list::impl_has_list_links! {
607///     impl HasListLinks<0> for ListItem { self.links }
608/// }
609/// kernel::list::impl_list_arc_safe! {
610///     impl ListArcSafe<0> for ListItem { untracked; }
611/// }
612/// kernel::list::impl_list_item! {
613///     impl ListItem<0> for ListItem { using ListLinks; }
614/// }
615///
616/// // Use a cursor to remove the first element with the given value.
617/// fn remove_first(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {
618///     let mut cursor = list.cursor_front();
619///     while let Some(next) = cursor.peek_next() {
620///         if next.value == value {
621///             return Some(next.remove());
622///         }
623///         cursor.move_next();
624///     }
625///     None
626/// }
627///
628/// // Use a cursor to remove the last element with the given value.
629/// fn remove_last(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {
630///     let mut cursor = list.cursor_back();
631///     while let Some(prev) = cursor.peek_prev() {
632///         if prev.value == value {
633///             return Some(prev.remove());
634///         }
635///         cursor.move_prev();
636///     }
637///     None
638/// }
639///
640/// // Use a cursor to remove all elements with the given value. The removed elements are moved to
641/// // a new list.
642/// fn remove_all(list: &mut List<ListItem>, value: u32) -> List<ListItem> {
643///     let mut out = List::new();
644///     let mut cursor = list.cursor_front();
645///     while let Some(next) = cursor.peek_next() {
646///         if next.value == value {
647///             out.push_back(next.remove());
648///         } else {
649///             cursor.move_next();
650///         }
651///     }
652///     out
653/// }
654///
655/// // Use a cursor to insert a value at a specific index. Returns an error if the index is out of
656/// // bounds.
657/// fn insert_at(list: &mut List<ListItem>, new: ListArc<ListItem>, idx: usize) -> Result {
658///     let mut cursor = list.cursor_front();
659///     for _ in 0..idx {
660///         if !cursor.move_next() {
661///             return Err(EINVAL);
662///         }
663///     }
664///     cursor.insert_next(new);
665///     Ok(())
666/// }
667///
668/// // Merge two sorted lists into a single sorted list.
669/// fn merge_sorted(list: &mut List<ListItem>, merge: List<ListItem>) {
670///     let mut cursor = list.cursor_front();
671///     for to_insert in merge {
672///         while let Some(next) = cursor.peek_next() {
673///             if to_insert.value < next.value {
674///                 break;
675///             }
676///             cursor.move_next();
677///         }
678///         cursor.insert_prev(to_insert);
679///     }
680/// }
681///
682/// let mut list = List::new();
683/// list.push_back(ListItem::new(14)?);
684/// list.push_back(ListItem::new(12)?);
685/// list.push_back(ListItem::new(10)?);
686/// list.push_back(ListItem::new(12)?);
687/// list.push_back(ListItem::new(15)?);
688/// list.push_back(ListItem::new(14)?);
689/// assert_eq!(remove_all(&mut list, 12).iter().count(), 2);
690/// // [14, 10, 15, 14]
691/// assert!(remove_first(&mut list, 14).is_some());
692/// // [10, 15, 14]
693/// insert_at(&mut list, ListItem::new(12)?, 2)?;
694/// // [10, 15, 12, 14]
695/// assert!(remove_last(&mut list, 15).is_some());
696/// // [10, 12, 14]
697///
698/// let mut list2 = List::new();
699/// list2.push_back(ListItem::new(11)?);
700/// list2.push_back(ListItem::new(13)?);
701/// merge_sorted(&mut list, list2);
702///
703/// let mut items = list.into_iter();
704/// assert_eq!(items.next().unwrap().value, 10);
705/// assert_eq!(items.next().unwrap().value, 11);
706/// assert_eq!(items.next().unwrap().value, 12);
707/// assert_eq!(items.next().unwrap().value, 13);
708/// assert_eq!(items.next().unwrap().value, 14);
709/// assert!(items.next().is_none());
710/// # Result::<(), Error>::Ok(())
711/// ```
712///
713/// # Invariants
714///
715/// The `next` pointer is null or points a value in `list`.
716pub struct Cursor<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
717    list: &'a mut List<T, ID>,
718    /// Points at the element after this cursor, or null if the cursor is after the last element.
719    next: *mut ListLinksFields,
720}
721
722impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Cursor<'a, T, ID> {
723    /// Returns a pointer to the element before the cursor.
724    ///
725    /// Returns null if there is no element before the cursor.
726    fn prev_ptr(&self) -> *mut ListLinksFields {
727        let mut next = self.next;
728        let first = self.list.first;
729        if next == first {
730            // We are before the first element.
731            return core::ptr::null_mut();
732        }
733
734        if next.is_null() {
735            // We are after the last element, so we need a pointer to the last element, which is
736            // the same as `(*first).prev`.
737            next = first;
738        }
739
740        // SAFETY: `next` can't be null, because then `first` must also be null, but in that case
741        // we would have exited at the `next == first` check. Thus, `next` is an element in the
742        // list, so we can access its `prev` pointer.
743        unsafe { (*next).prev }
744    }
745
746    /// Access the element after this cursor.
747    pub fn peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>> {
748        if self.next.is_null() {
749            return None;
750        }
751
752        // INVARIANT:
753        // * We just checked that `self.next` is non-null, so it must be in `self.list`.
754        // * `ptr` is equal to `self.next`.
755        Some(CursorPeek {
756            ptr: self.next,
757            cursor: self,
758        })
759    }
760
761    /// Access the element before this cursor.
762    pub fn peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>> {
763        let prev = self.prev_ptr();
764
765        if prev.is_null() {
766            return None;
767        }
768
769        // INVARIANT:
770        // * We just checked that `prev` is non-null, so it must be in `self.list`.
771        // * `self.prev_ptr()` never returns `self.next`.
772        Some(CursorPeek {
773            ptr: prev,
774            cursor: self,
775        })
776    }
777
778    /// Move the cursor one element forward.
779    ///
780    /// If the cursor is after the last element, then this call does nothing. This call returns
781    /// `true` if the cursor's position was changed.
782    pub fn move_next(&mut self) -> bool {
783        if self.next.is_null() {
784            return false;
785        }
786
787        // SAFETY: `self.next` is an element in the list and we borrow the list mutably, so we can
788        // access the `next` field.
789        let mut next = unsafe { (*self.next).next };
790
791        if next == self.list.first {
792            next = core::ptr::null_mut();
793        }
794
795        // INVARIANT: `next` is either null or the next element after an element in the list.
796        self.next = next;
797        true
798    }
799
800    /// Move the cursor one element backwards.
801    ///
802    /// If the cursor is before the first element, then this call does nothing. This call returns
803    /// `true` if the cursor's position was changed.
804    pub fn move_prev(&mut self) -> bool {
805        if self.next == self.list.first {
806            return false;
807        }
808
809        // INVARIANT: `prev_ptr()` always returns a pointer that is null or in the list.
810        self.next = self.prev_ptr();
811        true
812    }
813
814    /// Inserts an element where the cursor is pointing and get a pointer to the new element.
815    fn insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields {
816        let ptr = if self.next.is_null() {
817            self.list.first
818        } else {
819            self.next
820        };
821        // SAFETY:
822        // * `ptr` is an element in the list or null.
823        // * if `ptr` is null, then `self.list.first` is null so the list is empty.
824        let item = unsafe { self.list.insert_inner(item, ptr) };
825        if self.next == self.list.first {
826            // INVARIANT: We just inserted `item`, so it's a member of list.
827            self.list.first = item;
828        }
829        item
830    }
831
832    /// Insert an element at this cursor's location.
833    pub fn insert(mut self, item: ListArc<T, ID>) {
834        // This is identical to `insert_prev`, but consumes the cursor. This is helpful because it
835        // reduces confusion when the last operation on the cursor is an insertion; in that case,
836        // you just want to insert the element at the cursor, and it is confusing that the call
837        // involves the word prev or next.
838        self.insert_inner(item);
839    }
840
841    /// Inserts an element after this cursor.
842    ///
843    /// After insertion, the new element will be after the cursor.
844    pub fn insert_next(&mut self, item: ListArc<T, ID>) {
845        self.next = self.insert_inner(item);
846    }
847
848    /// Inserts an element before this cursor.
849    ///
850    /// After insertion, the new element will be before the cursor.
851    pub fn insert_prev(&mut self, item: ListArc<T, ID>) {
852        self.insert_inner(item);
853    }
854
855    /// Remove the next element from the list.
856    pub fn remove_next(&mut self) -> Option<ListArc<T, ID>> {
857        self.peek_next().map(|v| v.remove())
858    }
859
860    /// Remove the previous element from the list.
861    pub fn remove_prev(&mut self) -> Option<ListArc<T, ID>> {
862        self.peek_prev().map(|v| v.remove())
863    }
864}
865
866/// References the element in the list next to the cursor.
867///
868/// # Invariants
869///
870/// * `ptr` is an element in `self.cursor.list`.
871/// * `ISNEXT == (self.ptr == self.cursor.next)`.
872pub struct CursorPeek<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> {
873    cursor: &'a mut Cursor<'b, T, ID>,
874    ptr: *mut ListLinksFields,
875}
876
877impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64>
878    CursorPeek<'a, 'b, T, ISNEXT, ID>
879{
880    /// Remove the element from the list.
881    pub fn remove(self) -> ListArc<T, ID> {
882        if ISNEXT {
883            self.cursor.move_next();
884        }
885
886        // INVARIANT: `self.ptr` is not equal to `self.cursor.next` due to the above `move_next`
887        // call.
888        // SAFETY: By the type invariants of `Self`, `next` is not null, so `next` is an element of
889        // `self.cursor.list` by the type invariants of `Cursor`.
890        unsafe { self.cursor.list.remove_internal(self.ptr) }
891    }
892
893    /// Access this value as an [`ArcBorrow`].
894    pub fn arc(&self) -> ArcBorrow<'_, T> {
895        // SAFETY: `self.ptr` points at an element in `self.cursor.list`.
896        let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };
897        // SAFETY:
898        // * All values in a list are stored in an `Arc`.
899        // * The value cannot be removed from the list for the duration of the lifetime annotated
900        //   on the returned `ArcBorrow`, because removing it from the list would require mutable
901        //   access to the `CursorPeek`, the `Cursor` or the `List`. However, the `ArcBorrow` holds
902        //   an immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the
903        //   `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable
904        //   access requires first releasing the immutable borrow on the `CursorPeek`.
905        // * Values in a list never have a `UniqueArc` reference, because the list has a `ListArc`
906        //   reference, and `UniqueArc` references must be unique.
907        unsafe { ArcBorrow::from_raw(me) }
908    }
909}
910
911impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> core::ops::Deref
912    for CursorPeek<'a, 'b, T, ISNEXT, ID>
913{
914    // If you change the `ptr` field to have type `ArcBorrow<'a, T>`, it might seem like you could
915    // get rid of the `CursorPeek::arc` method and change the deref target to `ArcBorrow<'a, T>`.
916    // However, that doesn't work because 'a is too long. You could obtain an `ArcBorrow<'a, T>`
917    // and then call `CursorPeek::remove` without giving up the `ArcBorrow<'a, T>`, which would be
918    // unsound.
919    type Target = T;
920
921    fn deref(&self) -> &T {
922        // SAFETY: `self.ptr` points at an element in `self.cursor.list`.
923        let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };
924
925        // SAFETY: The value cannot be removed from the list for the duration of the lifetime
926        // annotated on the returned `&T`, because removing it from the list would require mutable
927        // access to the `CursorPeek`, the `Cursor` or the `List`. However, the `&T` holds an
928        // immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the
929        // `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable access
930        // requires first releasing the immutable borrow on the `CursorPeek`.
931        unsafe { &*me }
932    }
933}
934
935impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for Iter<'a, T, ID> {}
936
937impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for &'a List<T, ID> {
938    type IntoIter = Iter<'a, T, ID>;
939    type Item = ArcBorrow<'a, T>;
940
941    fn into_iter(self) -> Iter<'a, T, ID> {
942        self.iter()
943    }
944}
945
946/// An owning iterator into a [`List`].
947pub struct IntoIter<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
948    list: List<T, ID>,
949}
950
951impl<T: ?Sized + ListItem<ID>, const ID: u64> Iterator for IntoIter<T, ID> {
952    type Item = ListArc<T, ID>;
953
954    fn next(&mut self) -> Option<ListArc<T, ID>> {
955        self.list.pop_front()
956    }
957}
958
959impl<T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for IntoIter<T, ID> {}
960
961impl<T: ?Sized + ListItem<ID>, const ID: u64> DoubleEndedIterator for IntoIter<T, ID> {
962    fn next_back(&mut self) -> Option<ListArc<T, ID>> {
963        self.list.pop_back()
964    }
965}
966
967impl<T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for List<T, ID> {
968    type IntoIter = IntoIter<T, ID>;
969    type Item = ListArc<T, ID>;
970
971    fn into_iter(self) -> IntoIter<T, ID> {
972        IntoIter { list: self }
973    }
974}