xref: /linux-6.15/rust/kernel/list.rs (revision a39f3087)
16cd34171SAlice Ryhl // SPDX-License-Identifier: GPL-2.0
26cd34171SAlice Ryhl 
36cd34171SAlice Ryhl // Copyright (C) 2024 Google LLC.
46cd34171SAlice Ryhl 
56cd34171SAlice Ryhl //! A linked list implementation.
66cd34171SAlice Ryhl 
7*a39f3087SMiguel Ojeda // May not be needed in Rust 1.87.0 (pending beta backport).
8*a39f3087SMiguel Ojeda #![allow(clippy::ptr_eq)]
9*a39f3087SMiguel Ojeda 
10deeecc9cSAlice Ryhl use crate::sync::ArcBorrow;
1114176295SAlice Ryhl use crate::types::Opaque;
12deeecc9cSAlice Ryhl use core::iter::{DoubleEndedIterator, FusedIterator};
13db841866SAlice Ryhl use core::marker::PhantomData;
1414176295SAlice Ryhl use core::ptr;
15dbd5058bSBenno Lossin use pin_init::PinInit;
1614176295SAlice Ryhl 
1740c53294SAlice Ryhl mod impl_list_item_mod;
182003c04bSAlice Ryhl pub use self::impl_list_item_mod::{
192003c04bSAlice Ryhl     impl_has_list_links, impl_has_list_links_self_ptr, impl_list_item, HasListLinks, HasSelfPtr,
202003c04bSAlice Ryhl };
2140c53294SAlice Ryhl 
226cd34171SAlice Ryhl mod arc;
23a4802631SAlice Ryhl pub use self::arc::{impl_list_arc_safe, AtomicTracker, ListArc, ListArcSafe, TryNewListArc};
2414176295SAlice Ryhl 
25b204bbc5SAlice Ryhl mod arc_field;
26b204bbc5SAlice Ryhl pub use self::arc_field::{define_list_arc_field_getter, ListArcField};
27b204bbc5SAlice Ryhl 
28db841866SAlice Ryhl /// A linked list.
29db841866SAlice Ryhl ///
30db841866SAlice Ryhl /// All elements in this linked list will be [`ListArc`] references to the value. Since a value can
31db841866SAlice Ryhl /// only have one `ListArc` (for each pair of prev/next pointers), this ensures that the same
32db841866SAlice Ryhl /// prev/next pointers are not used for several linked lists.
33db841866SAlice Ryhl ///
34db841866SAlice Ryhl /// # Invariants
35db841866SAlice Ryhl ///
36db841866SAlice Ryhl /// * If the list is empty, then `first` is null. Otherwise, `first` points at the `ListLinks`
37db841866SAlice Ryhl ///   field of the first element in the list.
38db841866SAlice Ryhl /// * All prev/next pointers in `ListLinks` fields of items in the list are valid and form a cycle.
39db841866SAlice Ryhl /// * For every item in the list, the list owns the associated [`ListArc`] reference and has
40db841866SAlice Ryhl ///   exclusive access to the `ListLinks` field.
41db841866SAlice Ryhl pub struct List<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
42db841866SAlice Ryhl     first: *mut ListLinksFields,
43db841866SAlice Ryhl     _ty: PhantomData<ListArc<T, ID>>,
44db841866SAlice Ryhl }
45db841866SAlice Ryhl 
46db841866SAlice Ryhl // SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same
47db841866SAlice Ryhl // type of access to the `ListArc<T, ID>` elements.
48db841866SAlice Ryhl unsafe impl<T, const ID: u64> Send for List<T, ID>
49db841866SAlice Ryhl where
50db841866SAlice Ryhl     ListArc<T, ID>: Send,
51db841866SAlice Ryhl     T: ?Sized + ListItem<ID>,
52db841866SAlice Ryhl {
53db841866SAlice Ryhl }
54db841866SAlice Ryhl // SAFETY: This is a container of `ListArc<T, ID>`, and access to the container allows the same
55db841866SAlice Ryhl // type of access to the `ListArc<T, ID>` elements.
56db841866SAlice Ryhl unsafe impl<T, const ID: u64> Sync for List<T, ID>
57db841866SAlice Ryhl where
58db841866SAlice Ryhl     ListArc<T, ID>: Sync,
59db841866SAlice Ryhl     T: ?Sized + ListItem<ID>,
60db841866SAlice Ryhl {
61db841866SAlice Ryhl }
62db841866SAlice Ryhl 
63db841866SAlice Ryhl /// Implemented by types where a [`ListArc<Self>`] can be inserted into a [`List`].
6414176295SAlice Ryhl ///
6514176295SAlice Ryhl /// # Safety
6614176295SAlice Ryhl ///
6714176295SAlice Ryhl /// Implementers must ensure that they provide the guarantees documented on methods provided by
6814176295SAlice Ryhl /// this trait.
6914176295SAlice Ryhl ///
7014176295SAlice Ryhl /// [`ListArc<Self>`]: ListArc
7114176295SAlice Ryhl pub unsafe trait ListItem<const ID: u64 = 0>: ListArcSafe<ID> {
7214176295SAlice Ryhl     /// Views the [`ListLinks`] for this value.
7314176295SAlice Ryhl     ///
7414176295SAlice Ryhl     /// # Guarantees
7514176295SAlice Ryhl     ///
7614176295SAlice Ryhl     /// If there is a previous call to `prepare_to_insert` and there is no call to `post_remove`
7714176295SAlice Ryhl     /// since the most recent such call, then this returns the same pointer as the one returned by
7814176295SAlice Ryhl     /// the most recent call to `prepare_to_insert`.
7914176295SAlice Ryhl     ///
8014176295SAlice Ryhl     /// Otherwise, the returned pointer points at a read-only [`ListLinks`] with two null pointers.
8114176295SAlice Ryhl     ///
8214176295SAlice Ryhl     /// # Safety
8314176295SAlice Ryhl     ///
8414176295SAlice Ryhl     /// The provided pointer must point at a valid value. (It need not be in an `Arc`.)
view_links(me: *const Self) -> *mut ListLinks<ID>8514176295SAlice Ryhl     unsafe fn view_links(me: *const Self) -> *mut ListLinks<ID>;
8614176295SAlice Ryhl 
8714176295SAlice Ryhl     /// View the full value given its [`ListLinks`] field.
8814176295SAlice Ryhl     ///
8914176295SAlice Ryhl     /// Can only be used when the value is in a list.
9014176295SAlice Ryhl     ///
9114176295SAlice Ryhl     /// # Guarantees
9214176295SAlice Ryhl     ///
9314176295SAlice Ryhl     /// * Returns the same pointer as the one passed to the most recent call to `prepare_to_insert`.
9414176295SAlice Ryhl     /// * The returned pointer is valid until the next call to `post_remove`.
9514176295SAlice Ryhl     ///
9614176295SAlice Ryhl     /// # Safety
9714176295SAlice Ryhl     ///
9814176295SAlice Ryhl     /// * The provided pointer must originate from the most recent call to `prepare_to_insert`, or
9914176295SAlice Ryhl     ///   from a call to `view_links` that happened after the most recent call to
10014176295SAlice Ryhl     ///   `prepare_to_insert`.
10114176295SAlice Ryhl     /// * Since the most recent call to `prepare_to_insert`, the `post_remove` method must not have
10214176295SAlice Ryhl     ///   been called.
view_value(me: *mut ListLinks<ID>) -> *const Self10314176295SAlice Ryhl     unsafe fn view_value(me: *mut ListLinks<ID>) -> *const Self;
10414176295SAlice Ryhl 
105db841866SAlice Ryhl     /// This is called when an item is inserted into a [`List`].
10614176295SAlice Ryhl     ///
10714176295SAlice Ryhl     /// # Guarantees
10814176295SAlice Ryhl     ///
10914176295SAlice Ryhl     /// The caller is granted exclusive access to the returned [`ListLinks`] until `post_remove` is
11014176295SAlice Ryhl     /// called.
11114176295SAlice Ryhl     ///
11214176295SAlice Ryhl     /// # Safety
11314176295SAlice Ryhl     ///
11414176295SAlice Ryhl     /// * The provided pointer must point at a valid value in an [`Arc`].
11514176295SAlice Ryhl     /// * Calls to `prepare_to_insert` and `post_remove` on the same value must alternate.
11614176295SAlice Ryhl     /// * The caller must own the [`ListArc`] for this value.
11714176295SAlice Ryhl     /// * The caller must not give up ownership of the [`ListArc`] unless `post_remove` has been
11814176295SAlice Ryhl     ///   called after this call to `prepare_to_insert`.
11914176295SAlice Ryhl     ///
12014176295SAlice Ryhl     /// [`Arc`]: crate::sync::Arc
prepare_to_insert(me: *const Self) -> *mut ListLinks<ID>12114176295SAlice Ryhl     unsafe fn prepare_to_insert(me: *const Self) -> *mut ListLinks<ID>;
12214176295SAlice Ryhl 
12314176295SAlice Ryhl     /// This undoes a previous call to `prepare_to_insert`.
12414176295SAlice Ryhl     ///
12514176295SAlice Ryhl     /// # Guarantees
12614176295SAlice Ryhl     ///
12714176295SAlice Ryhl     /// The returned pointer is the pointer that was originally passed to `prepare_to_insert`.
12814176295SAlice Ryhl     ///
12914176295SAlice Ryhl     /// # Safety
13014176295SAlice Ryhl     ///
13114176295SAlice Ryhl     /// The provided pointer must be the pointer returned by the most recent call to
13214176295SAlice Ryhl     /// `prepare_to_insert`.
post_remove(me: *mut ListLinks<ID>) -> *const Self13314176295SAlice Ryhl     unsafe fn post_remove(me: *mut ListLinks<ID>) -> *const Self;
13414176295SAlice Ryhl }
13514176295SAlice Ryhl 
13614176295SAlice Ryhl #[repr(C)]
13714176295SAlice Ryhl #[derive(Copy, Clone)]
13814176295SAlice Ryhl struct ListLinksFields {
13914176295SAlice Ryhl     next: *mut ListLinksFields,
14014176295SAlice Ryhl     prev: *mut ListLinksFields,
14114176295SAlice Ryhl }
14214176295SAlice Ryhl 
14314176295SAlice Ryhl /// The prev/next pointers for an item in a linked list.
14414176295SAlice Ryhl ///
14514176295SAlice Ryhl /// # Invariants
14614176295SAlice Ryhl ///
14714176295SAlice Ryhl /// The fields are null if and only if this item is not in a list.
14814176295SAlice Ryhl #[repr(transparent)]
14914176295SAlice Ryhl pub struct ListLinks<const ID: u64 = 0> {
15014176295SAlice Ryhl     // This type is `!Unpin` for aliasing reasons as the pointers are part of an intrusive linked
15114176295SAlice Ryhl     // list.
15214176295SAlice Ryhl     inner: Opaque<ListLinksFields>,
15314176295SAlice Ryhl }
15414176295SAlice Ryhl 
15514176295SAlice Ryhl // SAFETY: The only way to access/modify the pointers inside of `ListLinks<ID>` is via holding the
15614176295SAlice Ryhl // associated `ListArc<T, ID>`. Since that type correctly implements `Send`, it is impossible to
15714176295SAlice Ryhl // move this an instance of this type to a different thread if the pointees are `!Send`.
15814176295SAlice Ryhl unsafe impl<const ID: u64> Send for ListLinks<ID> {}
15914176295SAlice Ryhl // SAFETY: The type is opaque so immutable references to a ListLinks are useless. Therefore, it's
16014176295SAlice Ryhl // okay to have immutable access to a ListLinks from several threads at once.
16114176295SAlice Ryhl unsafe impl<const ID: u64> Sync for ListLinks<ID> {}
16214176295SAlice Ryhl 
16314176295SAlice Ryhl impl<const ID: u64> ListLinks<ID> {
16414176295SAlice Ryhl     /// Creates a new initializer for this type.
new() -> impl PinInit<Self>16514176295SAlice Ryhl     pub fn new() -> impl PinInit<Self> {
16614176295SAlice Ryhl         // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
16714176295SAlice Ryhl         // not be constructed in an `Arc` that already has a `ListArc`.
16814176295SAlice Ryhl         ListLinks {
16914176295SAlice Ryhl             inner: Opaque::new(ListLinksFields {
17014176295SAlice Ryhl                 prev: ptr::null_mut(),
17114176295SAlice Ryhl                 next: ptr::null_mut(),
17214176295SAlice Ryhl             }),
17314176295SAlice Ryhl         }
17414176295SAlice Ryhl     }
175db841866SAlice Ryhl 
176db841866SAlice Ryhl     /// # Safety
177db841866SAlice Ryhl     ///
178db841866SAlice Ryhl     /// `me` must be dereferenceable.
179db841866SAlice Ryhl     #[inline]
fields(me: *mut Self) -> *mut ListLinksFields180db841866SAlice Ryhl     unsafe fn fields(me: *mut Self) -> *mut ListLinksFields {
181db841866SAlice Ryhl         // SAFETY: The caller promises that the pointer is valid.
182db841866SAlice Ryhl         unsafe { Opaque::raw_get(ptr::addr_of!((*me).inner)) }
183db841866SAlice Ryhl     }
184db841866SAlice Ryhl 
185db841866SAlice Ryhl     /// # Safety
186db841866SAlice Ryhl     ///
187db841866SAlice Ryhl     /// `me` must be dereferenceable.
188db841866SAlice Ryhl     #[inline]
from_fields(me: *mut ListLinksFields) -> *mut Self189db841866SAlice Ryhl     unsafe fn from_fields(me: *mut ListLinksFields) -> *mut Self {
190db841866SAlice Ryhl         me.cast()
191db841866SAlice Ryhl     }
192db841866SAlice Ryhl }
193db841866SAlice Ryhl 
1942003c04bSAlice Ryhl /// Similar to [`ListLinks`], but also contains a pointer to the full value.
1952003c04bSAlice Ryhl ///
1962003c04bSAlice Ryhl /// This type can be used instead of [`ListLinks`] to support lists with trait objects.
1972003c04bSAlice Ryhl #[repr(C)]
1982003c04bSAlice Ryhl pub struct ListLinksSelfPtr<T: ?Sized, const ID: u64 = 0> {
1992003c04bSAlice Ryhl     /// The `ListLinks` field inside this value.
2002003c04bSAlice Ryhl     ///
2012003c04bSAlice Ryhl     /// This is public so that it can be used with `impl_has_list_links!`.
2022003c04bSAlice Ryhl     pub inner: ListLinks<ID>,
2032003c04bSAlice Ryhl     // UnsafeCell is not enough here because we use `Opaque::uninit` as a dummy value, and
2042003c04bSAlice Ryhl     // `ptr::null()` doesn't work for `T: ?Sized`.
2052003c04bSAlice Ryhl     self_ptr: Opaque<*const T>,
2062003c04bSAlice Ryhl }
2072003c04bSAlice Ryhl 
2082003c04bSAlice Ryhl // SAFETY: The fields of a ListLinksSelfPtr can be moved across thread boundaries.
2092003c04bSAlice Ryhl unsafe impl<T: ?Sized + Send, const ID: u64> Send for ListLinksSelfPtr<T, ID> {}
2102003c04bSAlice Ryhl // SAFETY: The type is opaque so immutable references to a ListLinksSelfPtr are useless. Therefore,
2112003c04bSAlice Ryhl // it's okay to have immutable access to a ListLinks from several threads at once.
2122003c04bSAlice Ryhl //
2132003c04bSAlice Ryhl // Note that `inner` being a public field does not prevent this type from being opaque, since
2142003c04bSAlice Ryhl // `inner` is a opaque type.
2152003c04bSAlice Ryhl unsafe impl<T: ?Sized + Sync, const ID: u64> Sync for ListLinksSelfPtr<T, ID> {}
2162003c04bSAlice Ryhl 
2172003c04bSAlice Ryhl impl<T: ?Sized, const ID: u64> ListLinksSelfPtr<T, ID> {
2182003c04bSAlice Ryhl     /// The offset from the [`ListLinks`] to the self pointer field.
2192003c04bSAlice Ryhl     pub const LIST_LINKS_SELF_PTR_OFFSET: usize = core::mem::offset_of!(Self, self_ptr);
2202003c04bSAlice Ryhl 
2212003c04bSAlice Ryhl     /// Creates a new initializer for this type.
new() -> impl PinInit<Self>2222003c04bSAlice Ryhl     pub fn new() -> impl PinInit<Self> {
2232003c04bSAlice Ryhl         // INVARIANT: Pin-init initializers can't be used on an existing `Arc`, so this value will
2242003c04bSAlice Ryhl         // not be constructed in an `Arc` that already has a `ListArc`.
2252003c04bSAlice Ryhl         Self {
2262003c04bSAlice Ryhl             inner: ListLinks {
2272003c04bSAlice Ryhl                 inner: Opaque::new(ListLinksFields {
2282003c04bSAlice Ryhl                     prev: ptr::null_mut(),
2292003c04bSAlice Ryhl                     next: ptr::null_mut(),
2302003c04bSAlice Ryhl                 }),
2312003c04bSAlice Ryhl             },
2322003c04bSAlice Ryhl             self_ptr: Opaque::uninit(),
2332003c04bSAlice Ryhl         }
2342003c04bSAlice Ryhl     }
2352003c04bSAlice Ryhl }
2362003c04bSAlice Ryhl 
237db841866SAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> List<T, ID> {
238db841866SAlice Ryhl     /// Creates a new empty list.
new() -> Self239db841866SAlice Ryhl     pub const fn new() -> Self {
240db841866SAlice Ryhl         Self {
241db841866SAlice Ryhl             first: ptr::null_mut(),
242db841866SAlice Ryhl             _ty: PhantomData,
243db841866SAlice Ryhl         }
244db841866SAlice Ryhl     }
245db841866SAlice Ryhl 
246db841866SAlice Ryhl     /// Returns whether this list is empty.
is_empty(&self) -> bool247db841866SAlice Ryhl     pub fn is_empty(&self) -> bool {
248db841866SAlice Ryhl         self.first.is_null()
249db841866SAlice Ryhl     }
250db841866SAlice Ryhl 
251998c6573SAlice Ryhl     /// Inserts `item` before `next` in the cycle.
252998c6573SAlice Ryhl     ///
253998c6573SAlice Ryhl     /// Returns a pointer to the newly inserted element. Never changes `self.first` unless the list
254998c6573SAlice Ryhl     /// is empty.
255998c6573SAlice Ryhl     ///
256998c6573SAlice Ryhl     /// # Safety
257998c6573SAlice Ryhl     ///
258998c6573SAlice Ryhl     /// * `next` must be an element in this list or null.
259998c6573SAlice Ryhl     /// * if `next` is null, then the list must be empty.
insert_inner( &mut self, item: ListArc<T, ID>, next: *mut ListLinksFields, ) -> *mut ListLinksFields260998c6573SAlice Ryhl     unsafe fn insert_inner(
261998c6573SAlice Ryhl         &mut self,
262998c6573SAlice Ryhl         item: ListArc<T, ID>,
263998c6573SAlice Ryhl         next: *mut ListLinksFields,
264998c6573SAlice Ryhl     ) -> *mut ListLinksFields {
265db841866SAlice Ryhl         let raw_item = ListArc::into_raw(item);
266db841866SAlice Ryhl         // SAFETY:
267db841866SAlice Ryhl         // * We just got `raw_item` from a `ListArc`, so it's in an `Arc`.
268db841866SAlice Ryhl         // * Since we have ownership of the `ListArc`, `post_remove` must have been called after
269db841866SAlice Ryhl         //   the most recent call to `prepare_to_insert`, if any.
270db841866SAlice Ryhl         // * We own the `ListArc`.
271db841866SAlice Ryhl         // * Removing items from this list is always done using `remove_internal_inner`, which
272db841866SAlice Ryhl         //   calls `post_remove` before giving up ownership.
273db841866SAlice Ryhl         let list_links = unsafe { T::prepare_to_insert(raw_item) };
274db841866SAlice Ryhl         // SAFETY: We have not yet called `post_remove`, so `list_links` is still valid.
275db841866SAlice Ryhl         let item = unsafe { ListLinks::fields(list_links) };
276db841866SAlice Ryhl 
277998c6573SAlice Ryhl         // Check if the list is empty.
278998c6573SAlice Ryhl         if next.is_null() {
279db841866SAlice Ryhl             // SAFETY: The caller just gave us ownership of these fields.
280db841866SAlice Ryhl             // INVARIANT: A linked list with one item should be cyclic.
281db841866SAlice Ryhl             unsafe {
282db841866SAlice Ryhl                 (*item).next = item;
283db841866SAlice Ryhl                 (*item).prev = item;
284db841866SAlice Ryhl             }
285998c6573SAlice Ryhl             self.first = item;
286db841866SAlice Ryhl         } else {
287db841866SAlice Ryhl             // SAFETY: By the type invariant, this pointer is valid or null. We just checked that
288db841866SAlice Ryhl             // it's not null, so it must be valid.
289db841866SAlice Ryhl             let prev = unsafe { (*next).prev };
290db841866SAlice Ryhl             // SAFETY: Pointers in a linked list are never dangling, and the caller just gave us
291db841866SAlice Ryhl             // ownership of the fields on `item`.
292db841866SAlice Ryhl             // INVARIANT: This correctly inserts `item` between `prev` and `next`.
293db841866SAlice Ryhl             unsafe {
294db841866SAlice Ryhl                 (*item).next = next;
295db841866SAlice Ryhl                 (*item).prev = prev;
296db841866SAlice Ryhl                 (*prev).next = item;
297db841866SAlice Ryhl                 (*next).prev = item;
298db841866SAlice Ryhl             }
299db841866SAlice Ryhl         }
300998c6573SAlice Ryhl 
301998c6573SAlice Ryhl         item
302998c6573SAlice Ryhl     }
303998c6573SAlice Ryhl 
304998c6573SAlice Ryhl     /// Add the provided item to the back of the list.
push_back(&mut self, item: ListArc<T, ID>)305998c6573SAlice Ryhl     pub fn push_back(&mut self, item: ListArc<T, ID>) {
306998c6573SAlice Ryhl         // SAFETY:
307998c6573SAlice Ryhl         // * `self.first` is null or in the list.
308998c6573SAlice Ryhl         // * `self.first` is only null if the list is empty.
309998c6573SAlice Ryhl         unsafe { self.insert_inner(item, self.first) };
310db841866SAlice Ryhl     }
311db841866SAlice Ryhl 
312db841866SAlice Ryhl     /// Add the provided item to the front of the list.
push_front(&mut self, item: ListArc<T, ID>)313db841866SAlice Ryhl     pub fn push_front(&mut self, item: ListArc<T, ID>) {
314db841866SAlice Ryhl         // SAFETY:
315998c6573SAlice Ryhl         // * `self.first` is null or in the list.
316998c6573SAlice Ryhl         // * `self.first` is only null if the list is empty.
317998c6573SAlice Ryhl         let new_elem = unsafe { self.insert_inner(item, self.first) };
318db841866SAlice Ryhl 
319998c6573SAlice Ryhl         // INVARIANT: `new_elem` is in the list because we just inserted it.
320998c6573SAlice Ryhl         self.first = new_elem;
321db841866SAlice Ryhl     }
322db841866SAlice Ryhl 
323db841866SAlice Ryhl     /// Removes the last item from this list.
pop_back(&mut self) -> Option<ListArc<T, ID>>324db841866SAlice Ryhl     pub fn pop_back(&mut self) -> Option<ListArc<T, ID>> {
325db841866SAlice Ryhl         if self.first.is_null() {
326db841866SAlice Ryhl             return None;
327db841866SAlice Ryhl         }
328db841866SAlice Ryhl 
329db841866SAlice Ryhl         // SAFETY: We just checked that the list is not empty.
330db841866SAlice Ryhl         let last = unsafe { (*self.first).prev };
331db841866SAlice Ryhl         // SAFETY: The last item of this list is in this list.
332db841866SAlice Ryhl         Some(unsafe { self.remove_internal(last) })
333db841866SAlice Ryhl     }
334db841866SAlice Ryhl 
335db841866SAlice Ryhl     /// Removes the first item from this list.
pop_front(&mut self) -> Option<ListArc<T, ID>>336db841866SAlice Ryhl     pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {
337db841866SAlice Ryhl         if self.first.is_null() {
338db841866SAlice Ryhl             return None;
339db841866SAlice Ryhl         }
340db841866SAlice Ryhl 
341db841866SAlice Ryhl         // SAFETY: The first item of this list is in this list.
342db841866SAlice Ryhl         Some(unsafe { self.remove_internal(self.first) })
343db841866SAlice Ryhl     }
344db841866SAlice Ryhl 
345db841866SAlice Ryhl     /// Removes the provided item from this list and returns it.
346db841866SAlice Ryhl     ///
347db841866SAlice Ryhl     /// This returns `None` if the item is not in the list. (Note that by the safety requirements,
348db841866SAlice Ryhl     /// this means that the item is not in any list.)
349db841866SAlice Ryhl     ///
350db841866SAlice Ryhl     /// # Safety
351db841866SAlice Ryhl     ///
352db841866SAlice Ryhl     /// `item` must not be in a different linked list (with the same id).
remove(&mut self, item: &T) -> Option<ListArc<T, ID>>353db841866SAlice Ryhl     pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
354db4f72c9SMiguel Ojeda         // SAFETY: TODO.
355db841866SAlice Ryhl         let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
356db841866SAlice Ryhl         // SAFETY: The user provided a reference, and reference are never dangling.
357db841866SAlice Ryhl         //
358db841866SAlice Ryhl         // As for why this is not a data race, there are two cases:
359db841866SAlice Ryhl         //
360db841866SAlice Ryhl         //  * If `item` is not in any list, then these fields are read-only and null.
361db841866SAlice Ryhl         //  * If `item` is in this list, then we have exclusive access to these fields since we
362db841866SAlice Ryhl         //    have a mutable reference to the list.
363db841866SAlice Ryhl         //
364db841866SAlice Ryhl         // In either case, there's no race.
365db841866SAlice Ryhl         let ListLinksFields { next, prev } = unsafe { *item };
366db841866SAlice Ryhl 
367db841866SAlice Ryhl         debug_assert_eq!(next.is_null(), prev.is_null());
368db841866SAlice Ryhl         if !next.is_null() {
369db841866SAlice Ryhl             // This is really a no-op, but this ensures that `item` is a raw pointer that was
370db841866SAlice Ryhl             // obtained without going through a pointer->reference->pointer conversion roundtrip.
371db841866SAlice Ryhl             // This ensures that the list is valid under the more restrictive strict provenance
372db841866SAlice Ryhl             // ruleset.
373db841866SAlice Ryhl             //
374db841866SAlice Ryhl             // SAFETY: We just checked that `next` is not null, and it's not dangling by the
375db841866SAlice Ryhl             // list invariants.
376db841866SAlice Ryhl             unsafe {
377db841866SAlice Ryhl                 debug_assert_eq!(item, (*next).prev);
378db841866SAlice Ryhl                 item = (*next).prev;
379db841866SAlice Ryhl             }
380db841866SAlice Ryhl 
381db841866SAlice Ryhl             // SAFETY: We just checked that `item` is in a list, so the caller guarantees that it
382db841866SAlice Ryhl             // is in this list. The pointers are in the right order.
383db841866SAlice Ryhl             Some(unsafe { self.remove_internal_inner(item, next, prev) })
384db841866SAlice Ryhl         } else {
385db841866SAlice Ryhl             None
386db841866SAlice Ryhl         }
387db841866SAlice Ryhl     }
388db841866SAlice Ryhl 
389db841866SAlice Ryhl     /// Removes the provided item from the list.
390db841866SAlice Ryhl     ///
391db841866SAlice Ryhl     /// # Safety
392db841866SAlice Ryhl     ///
393db841866SAlice Ryhl     /// `item` must point at an item in this list.
remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID>394db841866SAlice Ryhl     unsafe fn remove_internal(&mut self, item: *mut ListLinksFields) -> ListArc<T, ID> {
395db841866SAlice Ryhl         // SAFETY: The caller promises that this pointer is not dangling, and there's no data race
396db841866SAlice Ryhl         // since we have a mutable reference to the list containing `item`.
397db841866SAlice Ryhl         let ListLinksFields { next, prev } = unsafe { *item };
398db841866SAlice Ryhl         // SAFETY: The pointers are ok and in the right order.
399db841866SAlice Ryhl         unsafe { self.remove_internal_inner(item, next, prev) }
400db841866SAlice Ryhl     }
401db841866SAlice Ryhl 
402db841866SAlice Ryhl     /// Removes the provided item from the list.
403db841866SAlice Ryhl     ///
404db841866SAlice Ryhl     /// # Safety
405db841866SAlice Ryhl     ///
406db841866SAlice Ryhl     /// The `item` pointer must point at an item in this list, and we must have `(*item).next ==
407db841866SAlice Ryhl     /// next` and `(*item).prev == prev`.
remove_internal_inner( &mut self, item: *mut ListLinksFields, next: *mut ListLinksFields, prev: *mut ListLinksFields, ) -> ListArc<T, ID>408db841866SAlice Ryhl     unsafe fn remove_internal_inner(
409db841866SAlice Ryhl         &mut self,
410db841866SAlice Ryhl         item: *mut ListLinksFields,
411db841866SAlice Ryhl         next: *mut ListLinksFields,
412db841866SAlice Ryhl         prev: *mut ListLinksFields,
413db841866SAlice Ryhl     ) -> ListArc<T, ID> {
414db841866SAlice Ryhl         // SAFETY: We have exclusive access to the pointers of items in the list, and the prev/next
415db841866SAlice Ryhl         // pointers are always valid for items in a list.
416db841866SAlice Ryhl         //
417db841866SAlice Ryhl         // INVARIANT: There are three cases:
418db841866SAlice Ryhl         //  * If the list has at least three items, then after removing the item, `prev` and `next`
419db841866SAlice Ryhl         //    will be next to each other.
420db841866SAlice Ryhl         //  * If the list has two items, then the remaining item will point at itself.
421db841866SAlice Ryhl         //  * If the list has one item, then `next == prev == item`, so these writes have no
422db841866SAlice Ryhl         //    effect. The list remains unchanged and `item` is still in the list for now.
423db841866SAlice Ryhl         unsafe {
424db841866SAlice Ryhl             (*next).prev = prev;
425db841866SAlice Ryhl             (*prev).next = next;
426db841866SAlice Ryhl         }
427db841866SAlice Ryhl         // SAFETY: We have exclusive access to items in the list.
428db841866SAlice Ryhl         // INVARIANT: `item` is being removed, so the pointers should be null.
429db841866SAlice Ryhl         unsafe {
430db841866SAlice Ryhl             (*item).prev = ptr::null_mut();
431db841866SAlice Ryhl             (*item).next = ptr::null_mut();
432db841866SAlice Ryhl         }
433db841866SAlice Ryhl         // INVARIANT: There are three cases:
434db841866SAlice Ryhl         //  * If `item` was not the first item, then `self.first` should remain unchanged.
435db841866SAlice Ryhl         //  * If `item` was the first item and there is another item, then we just updated
436db841866SAlice Ryhl         //    `prev->next` to `next`, which is the new first item, and setting `item->next` to null
437db841866SAlice Ryhl         //    did not modify `prev->next`.
438db841866SAlice Ryhl         //  * If `item` was the only item in the list, then `prev == item`, and we just set
439db841866SAlice Ryhl         //    `item->next` to null, so this correctly sets `first` to null now that the list is
440db841866SAlice Ryhl         //    empty.
441db841866SAlice Ryhl         if self.first == item {
442db841866SAlice Ryhl             // SAFETY: The `prev` pointer is the value that `item->prev` had when it was in this
443db841866SAlice Ryhl             // list, so it must be valid. There is no race since `prev` is still in the list and we
444db841866SAlice Ryhl             // still have exclusive access to the list.
445db841866SAlice Ryhl             self.first = unsafe { (*prev).next };
446db841866SAlice Ryhl         }
447db841866SAlice Ryhl 
448db841866SAlice Ryhl         // SAFETY: `item` used to be in the list, so it is dereferenceable by the type invariants
449db841866SAlice Ryhl         // of `List`.
450db841866SAlice Ryhl         let list_links = unsafe { ListLinks::from_fields(item) };
451db841866SAlice Ryhl         // SAFETY: Any pointer in the list originates from a `prepare_to_insert` call.
452db841866SAlice Ryhl         let raw_item = unsafe { T::post_remove(list_links) };
453db841866SAlice Ryhl         // SAFETY: The above call to `post_remove` guarantees that we can recreate the `ListArc`.
454db841866SAlice Ryhl         unsafe { ListArc::from_raw(raw_item) }
455db841866SAlice Ryhl     }
456db841866SAlice Ryhl 
457db841866SAlice Ryhl     /// Moves all items from `other` into `self`.
458db841866SAlice Ryhl     ///
459db841866SAlice Ryhl     /// The items of `other` are added to the back of `self`, so the last item of `other` becomes
460db841866SAlice Ryhl     /// the last item of `self`.
push_all_back(&mut self, other: &mut List<T, ID>)461db841866SAlice Ryhl     pub fn push_all_back(&mut self, other: &mut List<T, ID>) {
462db841866SAlice Ryhl         // First, we insert the elements into `self`. At the end, we make `other` empty.
463db841866SAlice Ryhl         if self.is_empty() {
464db841866SAlice Ryhl             // INVARIANT: All of the elements in `other` become elements of `self`.
465db841866SAlice Ryhl             self.first = other.first;
466db841866SAlice Ryhl         } else if !other.is_empty() {
467db841866SAlice Ryhl             let other_first = other.first;
468db841866SAlice Ryhl             // SAFETY: The other list is not empty, so this pointer is valid.
469db841866SAlice Ryhl             let other_last = unsafe { (*other_first).prev };
470db841866SAlice Ryhl             let self_first = self.first;
471db841866SAlice Ryhl             // SAFETY: The self list is not empty, so this pointer is valid.
472db841866SAlice Ryhl             let self_last = unsafe { (*self_first).prev };
473db841866SAlice Ryhl 
474db841866SAlice Ryhl             // SAFETY: We have exclusive access to both lists, so we can update the pointers.
475db841866SAlice Ryhl             // INVARIANT: This correctly sets the pointers to merge both lists. We do not need to
476db841866SAlice Ryhl             // update `self.first` because the first element of `self` does not change.
477db841866SAlice Ryhl             unsafe {
478db841866SAlice Ryhl                 (*self_first).prev = other_last;
479db841866SAlice Ryhl                 (*other_last).next = self_first;
480db841866SAlice Ryhl                 (*self_last).next = other_first;
481db841866SAlice Ryhl                 (*other_first).prev = self_last;
482db841866SAlice Ryhl             }
483db841866SAlice Ryhl         }
484db841866SAlice Ryhl 
485db841866SAlice Ryhl         // INVARIANT: The other list is now empty, so update its pointer.
486db841866SAlice Ryhl         other.first = ptr::null_mut();
487db841866SAlice Ryhl     }
488deeecc9cSAlice Ryhl 
48952ae96f5SAlice Ryhl     /// Returns a cursor that points before the first element of the list.
cursor_front(&mut self) -> Cursor<'_, T, ID>49052ae96f5SAlice Ryhl     pub fn cursor_front(&mut self) -> Cursor<'_, T, ID> {
49152ae96f5SAlice Ryhl         // INVARIANT: `self.first` is in this list.
49252ae96f5SAlice Ryhl         Cursor {
49352ae96f5SAlice Ryhl             next: self.first,
4949078a4f9SAlice Ryhl             list: self,
49552ae96f5SAlice Ryhl         }
49652ae96f5SAlice Ryhl     }
49752ae96f5SAlice Ryhl 
49852ae96f5SAlice Ryhl     /// Returns a cursor that points after the last element in the list.
cursor_back(&mut self) -> Cursor<'_, T, ID>49952ae96f5SAlice Ryhl     pub fn cursor_back(&mut self) -> Cursor<'_, T, ID> {
50052ae96f5SAlice Ryhl         // INVARIANT: `next` is allowed to be null.
50152ae96f5SAlice Ryhl         Cursor {
50252ae96f5SAlice Ryhl             next: core::ptr::null_mut(),
50352ae96f5SAlice Ryhl             list: self,
5049078a4f9SAlice Ryhl         }
5059078a4f9SAlice Ryhl     }
5069078a4f9SAlice Ryhl 
507deeecc9cSAlice Ryhl     /// Creates an iterator over the list.
iter(&self) -> Iter<'_, T, ID>508deeecc9cSAlice Ryhl     pub fn iter(&self) -> Iter<'_, T, ID> {
509deeecc9cSAlice Ryhl         // INVARIANT: If the list is empty, both pointers are null. Otherwise, both pointers point
510deeecc9cSAlice Ryhl         // at the first element of the same list.
511deeecc9cSAlice Ryhl         Iter {
512deeecc9cSAlice Ryhl             current: self.first,
513deeecc9cSAlice Ryhl             stop: self.first,
514deeecc9cSAlice Ryhl             _ty: PhantomData,
515deeecc9cSAlice Ryhl         }
516deeecc9cSAlice Ryhl     }
517db841866SAlice Ryhl }
518db841866SAlice Ryhl 
519db841866SAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> Default for List<T, ID> {
default() -> Self520db841866SAlice Ryhl     fn default() -> Self {
521db841866SAlice Ryhl         List::new()
522db841866SAlice Ryhl     }
523db841866SAlice Ryhl }
524db841866SAlice Ryhl 
525db841866SAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> Drop for List<T, ID> {
drop(&mut self)526db841866SAlice Ryhl     fn drop(&mut self) {
527db841866SAlice Ryhl         while let Some(item) = self.pop_front() {
528db841866SAlice Ryhl             drop(item);
529db841866SAlice Ryhl         }
530db841866SAlice Ryhl     }
53114176295SAlice Ryhl }
532deeecc9cSAlice Ryhl 
533deeecc9cSAlice Ryhl /// An iterator over a [`List`].
534deeecc9cSAlice Ryhl ///
535deeecc9cSAlice Ryhl /// # Invariants
536deeecc9cSAlice Ryhl ///
537deeecc9cSAlice Ryhl /// * There must be a [`List`] that is immutably borrowed for the duration of `'a`.
538deeecc9cSAlice Ryhl /// * The `current` pointer is null or points at a value in that [`List`].
539deeecc9cSAlice Ryhl /// * The `stop` pointer is equal to the `first` field of that [`List`].
540deeecc9cSAlice Ryhl #[derive(Clone)]
541deeecc9cSAlice Ryhl pub struct Iter<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
542deeecc9cSAlice Ryhl     current: *mut ListLinksFields,
543deeecc9cSAlice Ryhl     stop: *mut ListLinksFields,
544deeecc9cSAlice Ryhl     _ty: PhantomData<&'a ListArc<T, ID>>,
545deeecc9cSAlice Ryhl }
546deeecc9cSAlice Ryhl 
547deeecc9cSAlice Ryhl impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Iterator for Iter<'a, T, ID> {
548deeecc9cSAlice Ryhl     type Item = ArcBorrow<'a, T>;
549deeecc9cSAlice Ryhl 
next(&mut self) -> Option<ArcBorrow<'a, T>>550deeecc9cSAlice Ryhl     fn next(&mut self) -> Option<ArcBorrow<'a, T>> {
551deeecc9cSAlice Ryhl         if self.current.is_null() {
552deeecc9cSAlice Ryhl             return None;
553deeecc9cSAlice Ryhl         }
554deeecc9cSAlice Ryhl 
555deeecc9cSAlice Ryhl         let current = self.current;
556deeecc9cSAlice Ryhl 
557deeecc9cSAlice Ryhl         // SAFETY: We just checked that `current` is not null, so it is in a list, and hence not
558deeecc9cSAlice Ryhl         // dangling. There's no race because the iterator holds an immutable borrow to the list.
559deeecc9cSAlice Ryhl         let next = unsafe { (*current).next };
560deeecc9cSAlice Ryhl         // INVARIANT: If `current` was the last element of the list, then this updates it to null.
561deeecc9cSAlice Ryhl         // Otherwise, we update it to the next element.
562deeecc9cSAlice Ryhl         self.current = if next != self.stop {
563deeecc9cSAlice Ryhl             next
564deeecc9cSAlice Ryhl         } else {
565deeecc9cSAlice Ryhl             ptr::null_mut()
566deeecc9cSAlice Ryhl         };
567deeecc9cSAlice Ryhl 
568deeecc9cSAlice Ryhl         // SAFETY: The `current` pointer points at a value in the list.
569deeecc9cSAlice Ryhl         let item = unsafe { T::view_value(ListLinks::from_fields(current)) };
570deeecc9cSAlice Ryhl         // SAFETY:
571deeecc9cSAlice Ryhl         // * All values in a list are stored in an `Arc`.
572deeecc9cSAlice Ryhl         // * The value cannot be removed from the list for the duration of the lifetime annotated
573deeecc9cSAlice Ryhl         //   on the returned `ArcBorrow`, because removing it from the list would require mutable
574deeecc9cSAlice Ryhl         //   access to the list. However, the `ArcBorrow` is annotated with the iterator's
575deeecc9cSAlice Ryhl         //   lifetime, and the list is immutably borrowed for that lifetime.
576deeecc9cSAlice Ryhl         // * Values in a list never have a `UniqueArc` reference.
577deeecc9cSAlice Ryhl         Some(unsafe { ArcBorrow::from_raw(item) })
578deeecc9cSAlice Ryhl     }
579deeecc9cSAlice Ryhl }
580deeecc9cSAlice Ryhl 
5819078a4f9SAlice Ryhl /// A cursor into a [`List`].
5829078a4f9SAlice Ryhl ///
58352ae96f5SAlice Ryhl /// A cursor always rests between two elements in the list. This means that a cursor has a previous
58452ae96f5SAlice Ryhl /// and next element, but no current element. It also means that it's possible to have a cursor
58552ae96f5SAlice Ryhl /// into an empty list.
58652ae96f5SAlice Ryhl ///
58752ae96f5SAlice Ryhl /// # Examples
58852ae96f5SAlice Ryhl ///
58952ae96f5SAlice Ryhl /// ```
59052ae96f5SAlice Ryhl /// use kernel::prelude::*;
59152ae96f5SAlice Ryhl /// use kernel::list::{List, ListArc, ListLinks};
59252ae96f5SAlice Ryhl ///
59352ae96f5SAlice Ryhl /// #[pin_data]
59452ae96f5SAlice Ryhl /// struct ListItem {
59552ae96f5SAlice Ryhl ///     value: u32,
59652ae96f5SAlice Ryhl ///     #[pin]
59752ae96f5SAlice Ryhl ///     links: ListLinks,
59852ae96f5SAlice Ryhl /// }
59952ae96f5SAlice Ryhl ///
60052ae96f5SAlice Ryhl /// impl ListItem {
60152ae96f5SAlice Ryhl ///     fn new(value: u32) -> Result<ListArc<Self>> {
60252ae96f5SAlice Ryhl ///         ListArc::pin_init(try_pin_init!(Self {
60352ae96f5SAlice Ryhl ///             value,
60452ae96f5SAlice Ryhl ///             links <- ListLinks::new(),
60552ae96f5SAlice Ryhl ///         }), GFP_KERNEL)
60652ae96f5SAlice Ryhl ///     }
60752ae96f5SAlice Ryhl /// }
60852ae96f5SAlice Ryhl ///
60952ae96f5SAlice Ryhl /// kernel::list::impl_has_list_links! {
61052ae96f5SAlice Ryhl ///     impl HasListLinks<0> for ListItem { self.links }
61152ae96f5SAlice Ryhl /// }
61252ae96f5SAlice Ryhl /// kernel::list::impl_list_arc_safe! {
61352ae96f5SAlice Ryhl ///     impl ListArcSafe<0> for ListItem { untracked; }
61452ae96f5SAlice Ryhl /// }
61552ae96f5SAlice Ryhl /// kernel::list::impl_list_item! {
61652ae96f5SAlice Ryhl ///     impl ListItem<0> for ListItem { using ListLinks; }
61752ae96f5SAlice Ryhl /// }
61852ae96f5SAlice Ryhl ///
61952ae96f5SAlice Ryhl /// // Use a cursor to remove the first element with the given value.
62052ae96f5SAlice Ryhl /// fn remove_first(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {
62152ae96f5SAlice Ryhl ///     let mut cursor = list.cursor_front();
62252ae96f5SAlice Ryhl ///     while let Some(next) = cursor.peek_next() {
62352ae96f5SAlice Ryhl ///         if next.value == value {
62452ae96f5SAlice Ryhl ///             return Some(next.remove());
62552ae96f5SAlice Ryhl ///         }
62652ae96f5SAlice Ryhl ///         cursor.move_next();
62752ae96f5SAlice Ryhl ///     }
62852ae96f5SAlice Ryhl ///     None
62952ae96f5SAlice Ryhl /// }
63052ae96f5SAlice Ryhl ///
63152ae96f5SAlice Ryhl /// // Use a cursor to remove the last element with the given value.
63252ae96f5SAlice Ryhl /// fn remove_last(list: &mut List<ListItem>, value: u32) -> Option<ListArc<ListItem>> {
63352ae96f5SAlice Ryhl ///     let mut cursor = list.cursor_back();
63452ae96f5SAlice Ryhl ///     while let Some(prev) = cursor.peek_prev() {
63552ae96f5SAlice Ryhl ///         if prev.value == value {
63652ae96f5SAlice Ryhl ///             return Some(prev.remove());
63752ae96f5SAlice Ryhl ///         }
63852ae96f5SAlice Ryhl ///         cursor.move_prev();
63952ae96f5SAlice Ryhl ///     }
64052ae96f5SAlice Ryhl ///     None
64152ae96f5SAlice Ryhl /// }
64252ae96f5SAlice Ryhl ///
64352ae96f5SAlice Ryhl /// // Use a cursor to remove all elements with the given value. The removed elements are moved to
64452ae96f5SAlice Ryhl /// // a new list.
64552ae96f5SAlice Ryhl /// fn remove_all(list: &mut List<ListItem>, value: u32) -> List<ListItem> {
64652ae96f5SAlice Ryhl ///     let mut out = List::new();
64752ae96f5SAlice Ryhl ///     let mut cursor = list.cursor_front();
64852ae96f5SAlice Ryhl ///     while let Some(next) = cursor.peek_next() {
64952ae96f5SAlice Ryhl ///         if next.value == value {
65052ae96f5SAlice Ryhl ///             out.push_back(next.remove());
65152ae96f5SAlice Ryhl ///         } else {
65252ae96f5SAlice Ryhl ///             cursor.move_next();
65352ae96f5SAlice Ryhl ///         }
65452ae96f5SAlice Ryhl ///     }
65552ae96f5SAlice Ryhl ///     out
65652ae96f5SAlice Ryhl /// }
65752ae96f5SAlice Ryhl ///
65852ae96f5SAlice Ryhl /// // Use a cursor to insert a value at a specific index. Returns an error if the index is out of
65952ae96f5SAlice Ryhl /// // bounds.
66052ae96f5SAlice Ryhl /// fn insert_at(list: &mut List<ListItem>, new: ListArc<ListItem>, idx: usize) -> Result {
66152ae96f5SAlice Ryhl ///     let mut cursor = list.cursor_front();
66252ae96f5SAlice Ryhl ///     for _ in 0..idx {
66352ae96f5SAlice Ryhl ///         if !cursor.move_next() {
66452ae96f5SAlice Ryhl ///             return Err(EINVAL);
66552ae96f5SAlice Ryhl ///         }
66652ae96f5SAlice Ryhl ///     }
66752ae96f5SAlice Ryhl ///     cursor.insert_next(new);
66852ae96f5SAlice Ryhl ///     Ok(())
66952ae96f5SAlice Ryhl /// }
67052ae96f5SAlice Ryhl ///
67152ae96f5SAlice Ryhl /// // Merge two sorted lists into a single sorted list.
67252ae96f5SAlice Ryhl /// fn merge_sorted(list: &mut List<ListItem>, merge: List<ListItem>) {
67352ae96f5SAlice Ryhl ///     let mut cursor = list.cursor_front();
67452ae96f5SAlice Ryhl ///     for to_insert in merge {
67552ae96f5SAlice Ryhl ///         while let Some(next) = cursor.peek_next() {
67652ae96f5SAlice Ryhl ///             if to_insert.value < next.value {
67752ae96f5SAlice Ryhl ///                 break;
67852ae96f5SAlice Ryhl ///             }
67952ae96f5SAlice Ryhl ///             cursor.move_next();
68052ae96f5SAlice Ryhl ///         }
68152ae96f5SAlice Ryhl ///         cursor.insert_prev(to_insert);
68252ae96f5SAlice Ryhl ///     }
68352ae96f5SAlice Ryhl /// }
68452ae96f5SAlice Ryhl ///
68552ae96f5SAlice Ryhl /// let mut list = List::new();
68652ae96f5SAlice Ryhl /// list.push_back(ListItem::new(14)?);
68752ae96f5SAlice Ryhl /// list.push_back(ListItem::new(12)?);
68852ae96f5SAlice Ryhl /// list.push_back(ListItem::new(10)?);
68952ae96f5SAlice Ryhl /// list.push_back(ListItem::new(12)?);
69052ae96f5SAlice Ryhl /// list.push_back(ListItem::new(15)?);
69152ae96f5SAlice Ryhl /// list.push_back(ListItem::new(14)?);
69252ae96f5SAlice Ryhl /// assert_eq!(remove_all(&mut list, 12).iter().count(), 2);
69352ae96f5SAlice Ryhl /// // [14, 10, 15, 14]
69452ae96f5SAlice Ryhl /// assert!(remove_first(&mut list, 14).is_some());
69552ae96f5SAlice Ryhl /// // [10, 15, 14]
69652ae96f5SAlice Ryhl /// insert_at(&mut list, ListItem::new(12)?, 2)?;
69752ae96f5SAlice Ryhl /// // [10, 15, 12, 14]
69852ae96f5SAlice Ryhl /// assert!(remove_last(&mut list, 15).is_some());
69952ae96f5SAlice Ryhl /// // [10, 12, 14]
70052ae96f5SAlice Ryhl ///
70152ae96f5SAlice Ryhl /// let mut list2 = List::new();
70252ae96f5SAlice Ryhl /// list2.push_back(ListItem::new(11)?);
70352ae96f5SAlice Ryhl /// list2.push_back(ListItem::new(13)?);
70452ae96f5SAlice Ryhl /// merge_sorted(&mut list, list2);
70552ae96f5SAlice Ryhl ///
70652ae96f5SAlice Ryhl /// let mut items = list.into_iter();
70752ae96f5SAlice Ryhl /// assert_eq!(items.next().unwrap().value, 10);
70852ae96f5SAlice Ryhl /// assert_eq!(items.next().unwrap().value, 11);
70952ae96f5SAlice Ryhl /// assert_eq!(items.next().unwrap().value, 12);
71052ae96f5SAlice Ryhl /// assert_eq!(items.next().unwrap().value, 13);
71152ae96f5SAlice Ryhl /// assert_eq!(items.next().unwrap().value, 14);
71252ae96f5SAlice Ryhl /// assert!(items.next().is_none());
71352ae96f5SAlice Ryhl /// # Result::<(), Error>::Ok(())
71452ae96f5SAlice Ryhl /// ```
71552ae96f5SAlice Ryhl ///
7169078a4f9SAlice Ryhl /// # Invariants
7179078a4f9SAlice Ryhl ///
71852ae96f5SAlice Ryhl /// The `next` pointer is null or points a value in `list`.
7199078a4f9SAlice Ryhl pub struct Cursor<'a, T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
7209078a4f9SAlice Ryhl     list: &'a mut List<T, ID>,
72152ae96f5SAlice Ryhl     /// Points at the element after this cursor, or null if the cursor is after the last element.
72252ae96f5SAlice Ryhl     next: *mut ListLinksFields,
7239078a4f9SAlice Ryhl }
7249078a4f9SAlice Ryhl 
7259078a4f9SAlice Ryhl impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> Cursor<'a, T, ID> {
72652ae96f5SAlice Ryhl     /// Returns a pointer to the element before the cursor.
72752ae96f5SAlice Ryhl     ///
72852ae96f5SAlice Ryhl     /// Returns null if there is no element before the cursor.
prev_ptr(&self) -> *mut ListLinksFields72952ae96f5SAlice Ryhl     fn prev_ptr(&self) -> *mut ListLinksFields {
73052ae96f5SAlice Ryhl         let mut next = self.next;
73152ae96f5SAlice Ryhl         let first = self.list.first;
73252ae96f5SAlice Ryhl         if next == first {
73352ae96f5SAlice Ryhl             // We are before the first element.
73452ae96f5SAlice Ryhl             return core::ptr::null_mut();
73552ae96f5SAlice Ryhl         }
73652ae96f5SAlice Ryhl 
73752ae96f5SAlice Ryhl         if next.is_null() {
73852ae96f5SAlice Ryhl             // We are after the last element, so we need a pointer to the last element, which is
73952ae96f5SAlice Ryhl             // the same as `(*first).prev`.
74052ae96f5SAlice Ryhl             next = first;
74152ae96f5SAlice Ryhl         }
74252ae96f5SAlice Ryhl 
74352ae96f5SAlice Ryhl         // SAFETY: `next` can't be null, because then `first` must also be null, but in that case
74452ae96f5SAlice Ryhl         // we would have exited at the `next == first` check. Thus, `next` is an element in the
74552ae96f5SAlice Ryhl         // list, so we can access its `prev` pointer.
74652ae96f5SAlice Ryhl         unsafe { (*next).prev }
74752ae96f5SAlice Ryhl     }
74852ae96f5SAlice Ryhl 
74952ae96f5SAlice Ryhl     /// Access the element after this cursor.
peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>>75052ae96f5SAlice Ryhl     pub fn peek_next(&mut self) -> Option<CursorPeek<'_, 'a, T, true, ID>> {
75152ae96f5SAlice Ryhl         if self.next.is_null() {
75252ae96f5SAlice Ryhl             return None;
75352ae96f5SAlice Ryhl         }
75452ae96f5SAlice Ryhl 
75552ae96f5SAlice Ryhl         // INVARIANT:
75652ae96f5SAlice Ryhl         // * We just checked that `self.next` is non-null, so it must be in `self.list`.
75752ae96f5SAlice Ryhl         // * `ptr` is equal to `self.next`.
75852ae96f5SAlice Ryhl         Some(CursorPeek {
75952ae96f5SAlice Ryhl             ptr: self.next,
76052ae96f5SAlice Ryhl             cursor: self,
76152ae96f5SAlice Ryhl         })
76252ae96f5SAlice Ryhl     }
76352ae96f5SAlice Ryhl 
76452ae96f5SAlice Ryhl     /// Access the element before this cursor.
peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>>76552ae96f5SAlice Ryhl     pub fn peek_prev(&mut self) -> Option<CursorPeek<'_, 'a, T, false, ID>> {
76652ae96f5SAlice Ryhl         let prev = self.prev_ptr();
76752ae96f5SAlice Ryhl 
76852ae96f5SAlice Ryhl         if prev.is_null() {
76952ae96f5SAlice Ryhl             return None;
77052ae96f5SAlice Ryhl         }
77152ae96f5SAlice Ryhl 
77252ae96f5SAlice Ryhl         // INVARIANT:
77352ae96f5SAlice Ryhl         // * We just checked that `prev` is non-null, so it must be in `self.list`.
77452ae96f5SAlice Ryhl         // * `self.prev_ptr()` never returns `self.next`.
77552ae96f5SAlice Ryhl         Some(CursorPeek {
77652ae96f5SAlice Ryhl             ptr: prev,
77752ae96f5SAlice Ryhl             cursor: self,
77852ae96f5SAlice Ryhl         })
77952ae96f5SAlice Ryhl     }
78052ae96f5SAlice Ryhl 
78152ae96f5SAlice Ryhl     /// Move the cursor one element forward.
78252ae96f5SAlice Ryhl     ///
78352ae96f5SAlice Ryhl     /// If the cursor is after the last element, then this call does nothing. This call returns
78452ae96f5SAlice Ryhl     /// `true` if the cursor's position was changed.
move_next(&mut self) -> bool78552ae96f5SAlice Ryhl     pub fn move_next(&mut self) -> bool {
78652ae96f5SAlice Ryhl         if self.next.is_null() {
78752ae96f5SAlice Ryhl             return false;
78852ae96f5SAlice Ryhl         }
78952ae96f5SAlice Ryhl 
79052ae96f5SAlice Ryhl         // SAFETY: `self.next` is an element in the list and we borrow the list mutably, so we can
79152ae96f5SAlice Ryhl         // access the `next` field.
79252ae96f5SAlice Ryhl         let mut next = unsafe { (*self.next).next };
79352ae96f5SAlice Ryhl 
79452ae96f5SAlice Ryhl         if next == self.list.first {
79552ae96f5SAlice Ryhl             next = core::ptr::null_mut();
79652ae96f5SAlice Ryhl         }
79752ae96f5SAlice Ryhl 
79852ae96f5SAlice Ryhl         // INVARIANT: `next` is either null or the next element after an element in the list.
79952ae96f5SAlice Ryhl         self.next = next;
80052ae96f5SAlice Ryhl         true
80152ae96f5SAlice Ryhl     }
80252ae96f5SAlice Ryhl 
80352ae96f5SAlice Ryhl     /// Move the cursor one element backwards.
80452ae96f5SAlice Ryhl     ///
80552ae96f5SAlice Ryhl     /// If the cursor is before the first element, then this call does nothing. This call returns
80652ae96f5SAlice Ryhl     /// `true` if the cursor's position was changed.
move_prev(&mut self) -> bool80752ae96f5SAlice Ryhl     pub fn move_prev(&mut self) -> bool {
80852ae96f5SAlice Ryhl         if self.next == self.list.first {
80952ae96f5SAlice Ryhl             return false;
81052ae96f5SAlice Ryhl         }
81152ae96f5SAlice Ryhl 
81252ae96f5SAlice Ryhl         // INVARIANT: `prev_ptr()` always returns a pointer that is null or in the list.
81352ae96f5SAlice Ryhl         self.next = self.prev_ptr();
81452ae96f5SAlice Ryhl         true
81552ae96f5SAlice Ryhl     }
81652ae96f5SAlice Ryhl 
81752ae96f5SAlice Ryhl     /// Inserts an element where the cursor is pointing and get a pointer to the new element.
insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields81852ae96f5SAlice Ryhl     fn insert_inner(&mut self, item: ListArc<T, ID>) -> *mut ListLinksFields {
81952ae96f5SAlice Ryhl         let ptr = if self.next.is_null() {
82052ae96f5SAlice Ryhl             self.list.first
82152ae96f5SAlice Ryhl         } else {
82252ae96f5SAlice Ryhl             self.next
82352ae96f5SAlice Ryhl         };
82452ae96f5SAlice Ryhl         // SAFETY:
82552ae96f5SAlice Ryhl         // * `ptr` is an element in the list or null.
82652ae96f5SAlice Ryhl         // * if `ptr` is null, then `self.list.first` is null so the list is empty.
82752ae96f5SAlice Ryhl         let item = unsafe { self.list.insert_inner(item, ptr) };
82852ae96f5SAlice Ryhl         if self.next == self.list.first {
82952ae96f5SAlice Ryhl             // INVARIANT: We just inserted `item`, so it's a member of list.
83052ae96f5SAlice Ryhl             self.list.first = item;
83152ae96f5SAlice Ryhl         }
83252ae96f5SAlice Ryhl         item
83352ae96f5SAlice Ryhl     }
83452ae96f5SAlice Ryhl 
83552ae96f5SAlice Ryhl     /// Insert an element at this cursor's location.
insert(mut self, item: ListArc<T, ID>)83652ae96f5SAlice Ryhl     pub fn insert(mut self, item: ListArc<T, ID>) {
83752ae96f5SAlice Ryhl         // This is identical to `insert_prev`, but consumes the cursor. This is helpful because it
83852ae96f5SAlice Ryhl         // reduces confusion when the last operation on the cursor is an insertion; in that case,
83952ae96f5SAlice Ryhl         // you just want to insert the element at the cursor, and it is confusing that the call
84052ae96f5SAlice Ryhl         // involves the word prev or next.
84152ae96f5SAlice Ryhl         self.insert_inner(item);
84252ae96f5SAlice Ryhl     }
84352ae96f5SAlice Ryhl 
84452ae96f5SAlice Ryhl     /// Inserts an element after this cursor.
84552ae96f5SAlice Ryhl     ///
84652ae96f5SAlice Ryhl     /// After insertion, the new element will be after the cursor.
insert_next(&mut self, item: ListArc<T, ID>)84752ae96f5SAlice Ryhl     pub fn insert_next(&mut self, item: ListArc<T, ID>) {
84852ae96f5SAlice Ryhl         self.next = self.insert_inner(item);
84952ae96f5SAlice Ryhl     }
85052ae96f5SAlice Ryhl 
85152ae96f5SAlice Ryhl     /// Inserts an element before this cursor.
85252ae96f5SAlice Ryhl     ///
85352ae96f5SAlice Ryhl     /// After insertion, the new element will be before the cursor.
insert_prev(&mut self, item: ListArc<T, ID>)85452ae96f5SAlice Ryhl     pub fn insert_prev(&mut self, item: ListArc<T, ID>) {
85552ae96f5SAlice Ryhl         self.insert_inner(item);
85652ae96f5SAlice Ryhl     }
85752ae96f5SAlice Ryhl 
85852ae96f5SAlice Ryhl     /// Remove the next element from the list.
remove_next(&mut self) -> Option<ListArc<T, ID>>85952ae96f5SAlice Ryhl     pub fn remove_next(&mut self) -> Option<ListArc<T, ID>> {
86052ae96f5SAlice Ryhl         self.peek_next().map(|v| v.remove())
86152ae96f5SAlice Ryhl     }
86252ae96f5SAlice Ryhl 
86352ae96f5SAlice Ryhl     /// Remove the previous element from the list.
remove_prev(&mut self) -> Option<ListArc<T, ID>>86452ae96f5SAlice Ryhl     pub fn remove_prev(&mut self) -> Option<ListArc<T, ID>> {
86552ae96f5SAlice Ryhl         self.peek_prev().map(|v| v.remove())
86652ae96f5SAlice Ryhl     }
86752ae96f5SAlice Ryhl }
86852ae96f5SAlice Ryhl 
86952ae96f5SAlice Ryhl /// References the element in the list next to the cursor.
87052ae96f5SAlice Ryhl ///
87152ae96f5SAlice Ryhl /// # Invariants
87252ae96f5SAlice Ryhl ///
87352ae96f5SAlice Ryhl /// * `ptr` is an element in `self.cursor.list`.
87452ae96f5SAlice Ryhl /// * `ISNEXT == (self.ptr == self.cursor.next)`.
87552ae96f5SAlice Ryhl pub struct CursorPeek<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> {
87652ae96f5SAlice Ryhl     cursor: &'a mut Cursor<'b, T, ID>,
87752ae96f5SAlice Ryhl     ptr: *mut ListLinksFields,
87852ae96f5SAlice Ryhl }
87952ae96f5SAlice Ryhl 
88052ae96f5SAlice Ryhl impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64>
88152ae96f5SAlice Ryhl     CursorPeek<'a, 'b, T, ISNEXT, ID>
88252ae96f5SAlice Ryhl {
88352ae96f5SAlice Ryhl     /// Remove the element from the list.
remove(self) -> ListArc<T, ID>88452ae96f5SAlice Ryhl     pub fn remove(self) -> ListArc<T, ID> {
88552ae96f5SAlice Ryhl         if ISNEXT {
88652ae96f5SAlice Ryhl             self.cursor.move_next();
88752ae96f5SAlice Ryhl         }
88852ae96f5SAlice Ryhl 
88952ae96f5SAlice Ryhl         // INVARIANT: `self.ptr` is not equal to `self.cursor.next` due to the above `move_next`
89052ae96f5SAlice Ryhl         // call.
89152ae96f5SAlice Ryhl         // SAFETY: By the type invariants of `Self`, `next` is not null, so `next` is an element of
89252ae96f5SAlice Ryhl         // `self.cursor.list` by the type invariants of `Cursor`.
89352ae96f5SAlice Ryhl         unsafe { self.cursor.list.remove_internal(self.ptr) }
89452ae96f5SAlice Ryhl     }
89552ae96f5SAlice Ryhl 
89652ae96f5SAlice Ryhl     /// Access this value as an [`ArcBorrow`].
arc(&self) -> ArcBorrow<'_, T>89752ae96f5SAlice Ryhl     pub fn arc(&self) -> ArcBorrow<'_, T> {
89852ae96f5SAlice Ryhl         // SAFETY: `self.ptr` points at an element in `self.cursor.list`.
89952ae96f5SAlice Ryhl         let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };
9009078a4f9SAlice Ryhl         // SAFETY:
9019078a4f9SAlice Ryhl         // * All values in a list are stored in an `Arc`.
9029078a4f9SAlice Ryhl         // * The value cannot be removed from the list for the duration of the lifetime annotated
9039078a4f9SAlice Ryhl         //   on the returned `ArcBorrow`, because removing it from the list would require mutable
90452ae96f5SAlice Ryhl         //   access to the `CursorPeek`, the `Cursor` or the `List`. However, the `ArcBorrow` holds
90552ae96f5SAlice Ryhl         //   an immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the
90652ae96f5SAlice Ryhl         //   `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable
90752ae96f5SAlice Ryhl         //   access requires first releasing the immutable borrow on the `CursorPeek`.
9089078a4f9SAlice Ryhl         // * Values in a list never have a `UniqueArc` reference, because the list has a `ListArc`
9099078a4f9SAlice Ryhl         //   reference, and `UniqueArc` references must be unique.
9109078a4f9SAlice Ryhl         unsafe { ArcBorrow::from_raw(me) }
9119078a4f9SAlice Ryhl     }
9129078a4f9SAlice Ryhl }
9139078a4f9SAlice Ryhl 
91452ae96f5SAlice Ryhl impl<'a, 'b, T: ?Sized + ListItem<ID>, const ISNEXT: bool, const ID: u64> core::ops::Deref
91552ae96f5SAlice Ryhl     for CursorPeek<'a, 'b, T, ISNEXT, ID>
91652ae96f5SAlice Ryhl {
91752ae96f5SAlice Ryhl     // If you change the `ptr` field to have type `ArcBorrow<'a, T>`, it might seem like you could
91852ae96f5SAlice Ryhl     // get rid of the `CursorPeek::arc` method and change the deref target to `ArcBorrow<'a, T>`.
91952ae96f5SAlice Ryhl     // However, that doesn't work because 'a is too long. You could obtain an `ArcBorrow<'a, T>`
92052ae96f5SAlice Ryhl     // and then call `CursorPeek::remove` without giving up the `ArcBorrow<'a, T>`, which would be
92152ae96f5SAlice Ryhl     // unsound.
92252ae96f5SAlice Ryhl     type Target = T;
9239078a4f9SAlice Ryhl 
deref(&self) -> &T92452ae96f5SAlice Ryhl     fn deref(&self) -> &T {
92552ae96f5SAlice Ryhl         // SAFETY: `self.ptr` points at an element in `self.cursor.list`.
92652ae96f5SAlice Ryhl         let me = unsafe { T::view_value(ListLinks::from_fields(self.ptr)) };
9279078a4f9SAlice Ryhl 
92852ae96f5SAlice Ryhl         // SAFETY: The value cannot be removed from the list for the duration of the lifetime
92952ae96f5SAlice Ryhl         // annotated on the returned `&T`, because removing it from the list would require mutable
93052ae96f5SAlice Ryhl         // access to the `CursorPeek`, the `Cursor` or the `List`. However, the `&T` holds an
93152ae96f5SAlice Ryhl         // immutable borrow on the `CursorPeek`, which in turn holds a mutable borrow on the
93252ae96f5SAlice Ryhl         // `Cursor`, which in turn holds a mutable borrow on the `List`, so any such mutable access
93352ae96f5SAlice Ryhl         // requires first releasing the immutable borrow on the `CursorPeek`.
93452ae96f5SAlice Ryhl         unsafe { &*me }
9359078a4f9SAlice Ryhl     }
9369078a4f9SAlice Ryhl }
9379078a4f9SAlice Ryhl 
938deeecc9cSAlice Ryhl impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for Iter<'a, T, ID> {}
939deeecc9cSAlice Ryhl 
940deeecc9cSAlice Ryhl impl<'a, T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for &'a List<T, ID> {
941deeecc9cSAlice Ryhl     type IntoIter = Iter<'a, T, ID>;
942deeecc9cSAlice Ryhl     type Item = ArcBorrow<'a, T>;
943deeecc9cSAlice Ryhl 
into_iter(self) -> Iter<'a, T, ID>944deeecc9cSAlice Ryhl     fn into_iter(self) -> Iter<'a, T, ID> {
945deeecc9cSAlice Ryhl         self.iter()
946deeecc9cSAlice Ryhl     }
947deeecc9cSAlice Ryhl }
948deeecc9cSAlice Ryhl 
949deeecc9cSAlice Ryhl /// An owning iterator into a [`List`].
950deeecc9cSAlice Ryhl pub struct IntoIter<T: ?Sized + ListItem<ID>, const ID: u64 = 0> {
951deeecc9cSAlice Ryhl     list: List<T, ID>,
952deeecc9cSAlice Ryhl }
953deeecc9cSAlice Ryhl 
954deeecc9cSAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> Iterator for IntoIter<T, ID> {
955deeecc9cSAlice Ryhl     type Item = ListArc<T, ID>;
956deeecc9cSAlice Ryhl 
next(&mut self) -> Option<ListArc<T, ID>>957deeecc9cSAlice Ryhl     fn next(&mut self) -> Option<ListArc<T, ID>> {
958deeecc9cSAlice Ryhl         self.list.pop_front()
959deeecc9cSAlice Ryhl     }
960deeecc9cSAlice Ryhl }
961deeecc9cSAlice Ryhl 
962deeecc9cSAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> FusedIterator for IntoIter<T, ID> {}
963deeecc9cSAlice Ryhl 
964deeecc9cSAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> DoubleEndedIterator for IntoIter<T, ID> {
next_back(&mut self) -> Option<ListArc<T, ID>>965deeecc9cSAlice Ryhl     fn next_back(&mut self) -> Option<ListArc<T, ID>> {
966deeecc9cSAlice Ryhl         self.list.pop_back()
967deeecc9cSAlice Ryhl     }
968deeecc9cSAlice Ryhl }
969deeecc9cSAlice Ryhl 
970deeecc9cSAlice Ryhl impl<T: ?Sized + ListItem<ID>, const ID: u64> IntoIterator for List<T, ID> {
971deeecc9cSAlice Ryhl     type IntoIter = IntoIter<T, ID>;
972deeecc9cSAlice Ryhl     type Item = ListArc<T, ID>;
973deeecc9cSAlice Ryhl 
into_iter(self) -> IntoIter<T, ID>974deeecc9cSAlice Ryhl     fn into_iter(self) -> IntoIter<T, ID> {
975deeecc9cSAlice Ryhl         IntoIter { list: self }
976deeecc9cSAlice Ryhl     }
977deeecc9cSAlice Ryhl }
978