kernel/
list.rs

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