Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. list/unsafe_list.rs

list/
unsafe_list.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#![allow(dead_code)]
15use core::cmp::Ordering;
16use core::marker::PhantomData;
17use core::ptr::NonNull;
18
19// Intrusive link structures are particularly tricky in Rust because mutable
20// references are expected to be globally unique.  Accessing the data through
21// other methods is UB.  There is a good writeup of Tokio's soundness challenges
22// at: https://gist.github.com/Darksonn/1567538f56af1a8038ecc3c664a42462.
23//
24// Here we adapt the strategy that Tokio uses:
25// * The link pointer structure is marked with `PhantomPinned`.  This does two
26//   things.  First it "poisons" the containing structure so that it's
27//   unpinnable (immovable).  Second it triggers the heuristic from
28//   https://github.com/rust-lang/rust/pull/82834 which will cause the compiler
29//   to omit emitting a `noalias` annotation on mutable references to disable
30//   compiler optimization that assume the mutable reference is unique.
31// * `next` and `prev` themselves are accessed by `Link` through direct pointer
32//   math on the `LinkInner` struct.  This avoids creating mutable references to
33//   those fields themselves which can not be annotated with `PhantomPinned`.
34//   `LinkInner` is `#[repr(C)]` to make the pointer math deterministic.
35//   `LinkInner` is declared in an `inner` module so that `next` and `prev` can
36//   not be accessed directly be the rest of the code.
37//
38// TODO: konkers - Understand if we need to annotate the alignment of LinkInner.
39mod link {
40    use core::cell::Cell;
41    use core::marker::PhantomPinned;
42    use core::ptr::NonNull;
43
44    #[repr(C)]
45    pub struct Link {
46        // TODO: The use of `Cell` here is *explicitly* unsound in combination
47        // with the `Send` and `Sync` impls below!
48        next: Cell<Option<NonNull<Link>>>,
49        prev: Cell<Option<NonNull<Link>>>,
50        _pin: PhantomPinned,
51    }
52
53    impl Link {
54        const UNLINKED_VALUE: Option<NonNull<Link>> =
55            Some(NonNull::new(usize::MAX as *mut Link).unwrap());
56
57        #[must_use]
58        pub const fn new() -> Self {
59            Self {
60                next: Cell::new(Self::UNLINKED_VALUE),
61                prev: Cell::new(Self::UNLINKED_VALUE),
62                _pin: PhantomPinned,
63            }
64        }
65
66        pub(super) const fn get_next(&self) -> Option<NonNull<Link>> {
67            self.next.get()
68        }
69
70        pub(super) const fn get_prev(&self) -> Option<NonNull<Link>> {
71            self.prev.get()
72        }
73
74        pub(super) fn set_next(&self, next: Option<NonNull<Link>>) {
75            self.next.set(next);
76        }
77
78        pub(super) fn set_prev(&self, prev: Option<NonNull<Link>>) {
79            self.prev.set(prev);
80        }
81
82        #[inline]
83        #[must_use]
84        pub fn is_unlinked(&self) -> bool {
85            self.get_next() == Link::UNLINKED_VALUE && self.get_prev() == Link::UNLINKED_VALUE
86        }
87
88        #[inline]
89        #[must_use]
90        pub fn is_linked(&self) -> bool {
91            !self.is_unlinked()
92        }
93
94        pub(super) fn set_unlinked(&self) {
95            self.set_next(Link::UNLINKED_VALUE);
96            self.set_prev(Link::UNLINKED_VALUE);
97        }
98    }
99}
100pub use link::Link;
101
102// SAFETY:
103//
104// When used with a ForeignList (or RandomAccessForeignList), a given node can
105// only be in a single list at a time.  This list logically owns the node for
106// the duration of its membership in the list.  All mutation of the node's
107// `Link` pointers are done while the node is in the list.  There is no API to
108// get a mutable reference to a node while it is in the list nor directly
109// manipulate its membership or position in the list.
110//
111// When used with an `UnsafeList` it is the users responsibility to ensure that
112// Rust's read-shared/write-exclusive semantics are upheld across all access
113// to a given node including when that node is also in a ForeignList
114// RandomAccessForeignList.
115unsafe impl Send for Link {}
116unsafe impl Sync for Link {}
117
118impl Default for Link {
119    fn default() -> Self {
120        Self::new()
121    }
122}
123
124// `UnsafeList` uses None to mark the beginning and end of lists as opposed to
125// pointers to the base list node.  This means that there are never pointers to
126// `UnsafeList` and the same care is not needed to avoid mutable references as
127// is taken with the `Link` structure.
128pub struct UnsafeList<T, A: Adapter<T>> {
129    inner: UnsafeListInner,
130    _phantom_type: PhantomData<T>,
131    _phantom_adapter: PhantomData<A>,
132}
133
134// Safety:
135// All operations on the UnsafeList are unsafe and it is up to the caller to
136// ensure it's safe to send or share the list and its members between threads.
137unsafe impl<T, A: Adapter<T>> Send for UnsafeList<T, A> {}
138unsafe impl<T, A: Adapter<T>> Sync for UnsafeList<T, A> {}
139
140// We separate this out so that most logic can be implemented as methods on this
141// type. These methods are concrete (with no generic type parameters), and
142// equivalent, generic methods on `UnsafeList` call into them. By keeping most
143// logic in concrete functions, we cut down on monomorphization size bloat.
144struct UnsafeListInner {
145    head: Option<NonNull<Link>>,
146    tail: Option<NonNull<Link>>,
147}
148
149pub trait Adapter<T> {
150    #[doc(hidden)]
151    const LINK_OFFSET: usize;
152
153    #[doc(hidden)]
154    #[must_use]
155    unsafe fn get_link(element: NonNull<T>) -> NonNull<Link>;
156    #[doc(hidden)]
157    #[must_use]
158    #[inline(always)]
159    unsafe fn get_element(link: NonNull<Link>) -> NonNull<T> {
160        unsafe { link.byte_sub(Self::LINK_OFFSET).cast::<T>() }
161    }
162}
163
164/// Defines an adapter type and implements [`Adapter`] for it.
165///
166/// # Usage
167///
168/// `define_adapter!` accepts a syntax like the following (where type arguments
169/// are optional):
170///
171/// ```
172/// use list::{Link, define_adapter};
173///
174/// struct Node<T: Copy> {
175///     data: T,
176///     link: Link,
177/// }
178/// define_adapter!(pub Adapter<T: Copy> => Node<T>::link);
179/// ```
180#[macro_export]
181macro_rules! define_adapter {
182    ($vis:vis $name:ident $(<$($tyvar:ident $(: $bound:path)?),*>)? => $node:ident $(<$($node_tyvar:ident),*>)? :: $link:ident) => {
183        $vis struct $name $(<$($tyvar $(: $bound)?),*>)? {
184            $(
185                _marker: core::marker::PhantomData<$($tyvar),*>,
186            )?
187        }
188
189        const _: () = {
190            use core::ptr::NonNull;
191            use core::mem::offset_of;
192
193            impl $(<$($tyvar $(: $bound)?),*>)? $crate::Adapter<$node $(<$($node_tyvar),*>)?> for $name $(<$($tyvar),*>)? {
194                const LINK_OFFSET: usize = offset_of!($node $(<$($node_tyvar),*>)?, $link);
195
196                #[inline(always)]
197                unsafe fn get_link(element: NonNull<$node $(<$($node_tyvar),*>)?>) -> NonNull<$crate::Link> {
198                    // NOTE: There is nothing stopping a caller from providing a
199                    // `$link` field which is not of type `Link`. However, if
200                    // they do this, then this method will fail to compile since
201                    // we annotate `link: *mut Link`. That ensures that `$link:
202                    // Link`.
203                    //
204                    // Note that a previous version of this code didn't have an
205                    // `Adapter::get_link` function, and relied on `LINK_OFFSET`
206                    // for both element -> link and link -> element pointer
207                    // operations. That code was vulnerable to this bug.
208                    let link: *mut $crate::Link = unsafe { core::ptr::addr_of_mut!((*element.as_ptr()).$link) };
209                    unsafe { NonNull::new_unchecked(link) }
210                }
211            }
212        };
213    };
214}
215
216impl<T, A: Adapter<T>> UnsafeList<T, A> {
217    #[must_use]
218    pub const fn new() -> Self {
219        Self {
220            inner: UnsafeListInner::new(),
221            _phantom_type: PhantomData,
222            _phantom_adapter: PhantomData,
223        }
224    }
225
226    /// # Safety
227    /// It is up to the caller to ensure exclusive access to the list and its
228    /// members.
229    #[must_use]
230    pub unsafe fn is_empty(&self) -> bool {
231        self.inner.is_empty()
232    }
233
234    /// Returns true if element is in **ANY** list that uses this list's adapter.
235    ///
236    /// # Safety
237    /// `element` must be a valid, non-null pointer.
238    #[must_use]
239    pub unsafe fn is_element_linked(&self, element: NonNull<T>) -> bool {
240        unsafe { A::get_link(element).as_ref().is_linked() }
241    }
242
243    /// Unchecked means:
244    /// * We don't `assert!((*element_ptr.as_ptr()).is_unlinked());`
245    /// * We don't check that `element` is non-null.
246    ///
247    /// # Safety
248    ///
249    /// It is up to the caller to ensure exclusive access to the list and its
250    /// members.
251    ///
252    /// It is up to the caller to ensure the element is not in a list.
253    pub unsafe fn push_front_unchecked(&mut self, element: NonNull<T>) {
254        let link_ptr = unsafe { A::get_link(element) };
255        unsafe { self.inner.push_front_unchecked(link_ptr) };
256    }
257
258    /// Unchecked means:
259    /// * We don't `assert!((*element_ptr.as_ptr()).is_unlinked());`
260    /// * We don't check that `element` is non-null.
261    ///
262    /// # Safety
263    ///
264    /// It is up to the caller to ensure exclusive access to the list and its
265    /// members.
266    ///
267    /// It is up to the caller to ensure the element is not in a list.
268    pub unsafe fn push_back_unchecked(&mut self, element: NonNull<T>) {
269        let link_ptr = unsafe { A::get_link(element) };
270        unsafe { self.inner.push_back_unchecked(link_ptr) };
271    }
272
273    /// Insert element_a into the list immediately before `element_b`
274    ///
275    /// # Safety
276    /// It is up to the caller to ensure exclusive access to the list and its
277    /// members.
278    /// It is up to the caller to ensure that element_a is not in a list.
279    /// It is up to the caller to ensure that element_b is in a list.
280    /// It is up to the caller to ensure the element_a and element_b are non-null.
281    unsafe fn insert_before(&mut self, element_a: NonNull<Link>, element_b: NonNull<Link>) {
282        unsafe { self.inner.insert_before(element_a, element_b) };
283    }
284
285    /// Unlinks element from the linked list.
286    ///
287    /// # Safety
288    ///
289    /// It is up to the caller to ensure exclusive access to the list and its
290    /// members.
291    ///
292    /// It is up to the caller to ensure the element is in the list.
293    pub unsafe fn unlink_element_unchecked(&mut self, element: NonNull<T>) {
294        let link_ptr = unsafe { A::get_link(element) };
295        unsafe { self.inner.unlink_element_unchecked(link_ptr) };
296    }
297
298    /// # Safety
299    ///
300    /// The caller must ensure that the element points to a valid `T`.
301    pub unsafe fn unlink_element(&mut self, element: NonNull<T>) -> Option<NonNull<T>> {
302        let link_ptr = unsafe { A::get_link(element) };
303        unsafe { self.inner.unlink_element(link_ptr).map(|()| element) }
304    }
305
306    /// # Safety
307    ///
308    /// It is up to the caller to ensure exclusive access to the list and its
309    /// members.
310    pub unsafe fn for_each<E, F: FnMut(&T) -> Result<(), E>>(
311        &self,
312        mut callback: F,
313    ) -> Result<(), E> {
314        let mut res = Ok(());
315        unsafe {
316            self.inner.for_each(&mut |link_ptr| {
317                let element = A::get_element(link_ptr);
318                callback(element.as_ref()).map_err(|e| res = Err(e))
319            })
320        };
321        res
322    }
323
324    #[must_use]
325    pub fn iter(&self) -> Iter<'_, T, A> {
326        Iter {
327            front: self.inner.head,
328            back: self.inner.tail,
329            _phantom: PhantomData,
330            _phantom_adapter: PhantomData,
331        }
332    }
333
334    // Note: `iter_mut()` is intentionally not provided. Providing `&mut T` would
335    // expose the internal `Link` field, allowing callers to corrupt the list's
336    // structure or violate Rust's sharing rules (since intrusive elements are
337    // often shared via raw pointers). Use `for_each` or manual pointers if you
338    // must modify elements.
339
340    /// Filter iterates over every element in the list calling `callback` on
341    /// each one.  If `callback` returns false, the element will be removed
342    /// from the list without modifying the element itself.  It is safe to
343    /// add the element to the another linked list within `callback` if it
344    /// returns false.
345    ///
346    /// # Safety
347    ///
348    /// It is up to the caller to ensure exclusive access to the list and its
349    /// members.
350    pub unsafe fn filter<F: FnMut(&mut T) -> bool>(&mut self, mut callback: F) {
351        unsafe {
352            self.inner.filter(&mut |link_ptr| {
353                let mut element = A::get_element(link_ptr);
354                callback(element.as_mut())
355            })
356        }
357    }
358
359    /// Return a reference to the first element in the list without removing it.
360    ///
361    /// # Safety
362    /// It is up to the caller to ensure exclusive access to the list and its
363    /// members.
364    #[must_use]
365    pub unsafe fn peek_head(&self) -> Option<NonNull<T>> {
366        self.inner
367            .peek_head()
368            .map(|link_ptr| unsafe { A::get_element(link_ptr) })
369    }
370
371    /// Return a reference to the first element in the list, clearing the
372    /// prev/next fields in the element.
373    ///
374    /// # Safety
375    /// It is up to the caller to ensure exclusive access to the list and its
376    /// members.
377    pub unsafe fn pop_head(&mut self) -> Option<NonNull<T>> {
378        self.inner
379            .pop_head()
380            .map(|link_ptr| unsafe { A::get_element(link_ptr) })
381    }
382}
383
384impl<T, A: Adapter<T>> UnsafeList<T, A> {
385    /// Unchecked means:
386    /// * We don't `assert!((*element_ptr.as_ptr()).is_unlinked());`
387    /// * We don't check that `element` is non-null.
388    ///
389    /// # Safety
390    ///
391    /// It is up to the caller to ensure exclusive access to the list and its
392    /// members.
393    ///
394    /// It is up to the caller to ensure the element is not in a list.
395    pub unsafe fn sorted_insert_by_unchecked<F: FnMut(&T, &T) -> Ordering>(
396        &mut self,
397        element: NonNull<T>,
398        mut compare: F,
399    ) {
400        let link_ptr = unsafe { A::get_link(element) };
401
402        let mut cmp = move |lhs, rhs| {
403            let lhs = unsafe { A::get_element(lhs) };
404            let rhs = unsafe { A::get_element(rhs) };
405            unsafe { compare(lhs.as_ref(), rhs.as_ref()) }
406        };
407        unsafe { self.inner.sorted_insert_by_unchecked(link_ptr, &mut cmp) };
408    }
409}
410
411impl UnsafeListInner {
412    #[must_use]
413    pub const fn new() -> Self {
414        Self {
415            head: None,
416            tail: None,
417        }
418    }
419
420    const fn is_empty(&self) -> bool {
421        self.head.is_none()
422    }
423
424    /// Unchecked means:
425    /// * We don't `assert!((*element_ptr.as_ptr()).is_unlinked());`
426    /// * We don't check that `element` is non-null.
427    ///
428    /// # Safety
429    ///
430    /// It is up to the caller to ensure exclusive access to the list and its
431    /// members.
432    ///
433    /// It is up to the caller to ensure the element is not in a list.
434    pub unsafe fn push_front_unchecked(&mut self, link_ptr: NonNull<Link>) {
435        // Link up the added element.
436        let link = unsafe { link_ptr.as_ref() };
437        link.set_next(self.head);
438        link.set_prev(None);
439
440        match self.head {
441            // If `head` was `None`, the list is empty and `tail` should point
442            // to the added element.
443            None => self.tail = Some(link_ptr),
444
445            // If `head` is not `None`, point the previous `head` to the added
446            // element.
447            Some(head) => unsafe { head.as_ref() }.set_prev(Some(link_ptr)),
448        }
449
450        // Finally point `head` to the added element.
451        self.head = Some(link_ptr);
452    }
453
454    /// Unchecked means:
455    /// * We don't `assert!((*element_ptr.as_ptr()).is_unlinked());`
456    /// * We don't check that `element` is non-null.
457    ///
458    /// # Safety
459    ///
460    /// It is up to the caller to ensure exclusive access to the list and its
461    /// members.
462    ///
463    /// It is up to the caller to ensure the element is not in a list.
464    pub unsafe fn push_back_unchecked(&mut self, link_ptr: NonNull<Link>) {
465        // Link up the added element.
466        let link = unsafe { link_ptr.as_ref() };
467        link.set_next(None);
468        link.set_prev(self.tail);
469
470        match self.tail {
471            // If `tail` was `None`, the list is empty and `head` should point
472            // to the added element.
473            None => self.head = Some(link_ptr),
474
475            // If `tail` is not `None`, point the previous `tail` to the added
476            // element.
477            Some(tail) => unsafe { tail.as_ref() }.set_next(Some(link_ptr)),
478        }
479
480        self.tail = Some(link_ptr);
481    }
482
483    /// Insert element_a into the list immediately before `element_b`
484    ///
485    /// # Safety
486    /// It is up to the caller to ensure exclusive access to the list and its
487    /// members.
488    /// It is up to the caller to ensure that element_a is not in a list.
489    /// It is up to the caller to ensure that element_b is in a list.
490    /// It is up to the caller to ensure the element_a and element_b are non-null.
491    unsafe fn insert_before(&mut self, element_a: NonNull<Link>, element_b: NonNull<Link>) {
492        let a = unsafe { element_a.as_ref() };
493        let b = unsafe { element_b.as_ref() };
494
495        let prev = b.get_prev();
496
497        a.set_next(Some(element_b));
498        a.set_prev(prev);
499
500        b.set_prev(Some(element_a));
501
502        match prev {
503            // Element is at the head of the list
504            None => self.head = Some(element_a),
505
506            // Element has elements before it in the list.
507            Some(prev_ptr) => unsafe { prev_ptr.as_ref() }.set_next(Some(element_a)),
508        }
509    }
510
511    /// Unlinks element from the linked list.
512    ///
513    /// # Safety
514    ///
515    /// It is up to the caller to ensure exclusive access to the list and its
516    /// members.
517    ///
518    /// It is up to the caller to ensure the element is in the list.
519    pub unsafe fn unlink_element_unchecked(&mut self, link_ptr: NonNull<Link>) {
520        // Wrap in a block to ensure `link`, which is a `&mut`, doesn't live
521        // long enough to possibly overlap with other `&mut` references to the
522        // same memory.
523        let (prev, next) = {
524            let link = unsafe { link_ptr.as_ref() };
525            let prev = link.get_prev();
526            let next = link.get_next();
527            link.set_unlinked();
528            (prev, next)
529        };
530
531        match prev {
532            // Element is at the head of the list
533            None => self.head = next,
534
535            // Element has elements before it in the list.
536            Some(prev_ptr) => unsafe { prev_ptr.as_ref() }.set_next(next),
537        }
538
539        match next {
540            // Element is at the tail of the list
541            None => self.tail = prev,
542
543            // Element has elements after it in the list.
544            Some(next_ptr) => unsafe { next_ptr.as_ref() }.set_prev(prev),
545        }
546    }
547
548    /// # Safety
549    ///
550    /// The caller must ensure that the element points to a valid `T`.
551    pub unsafe fn unlink_element(&mut self, link_ptr: NonNull<Link>) -> Option<()> {
552        if unsafe { link_ptr.as_ref() }.is_linked() {
553            unsafe { self.unlink_element_unchecked(link_ptr) };
554            Some(())
555        } else {
556            None
557        }
558    }
559
560    /// # Safety
561    ///
562    /// It is up to the caller to ensure exclusive access to the list and its
563    /// members.
564    pub unsafe fn for_each(&self, callback: &mut dyn FnMut(NonNull<Link>) -> Result<(), ()>) {
565        let mut cur = self.head;
566
567        while let Some(cur_ptr) = cur {
568            unsafe {
569                if callback(cur_ptr).is_err() {
570                    return;
571                }
572                cur = cur_ptr.as_ref().get_next();
573            }
574        }
575    }
576
577    /// Filter iterates over every element in the list calling `callback` on
578    /// each one.  If `callback` returns false, the element will be removed
579    /// from the list without modifying the element itself.  It is safe to
580    /// add the element to the another linked list within `callback` if it
581    /// returns false.
582    ///
583    /// # Safety
584    ///
585    /// It is up to the caller to ensure exclusive access to the list and its
586    /// members.
587    pub unsafe fn filter(&mut self, callback: &mut dyn FnMut(NonNull<Link>) -> bool) {
588        let mut cur = self.head;
589
590        while let Some(cur_ptr) = cur {
591            let next = unsafe {
592                // Cache the next element so that we don't rely on `cur_ptr`
593                // staying coherent across calls to `callback`.
594                let next = cur_ptr.as_ref().get_next();
595
596                if !callback(cur_ptr) {
597                    self.unlink_element_unchecked(cur_ptr);
598                }
599                next
600            };
601
602            cur = next;
603        }
604    }
605
606    /// Return a reference to the first element in the list without removing it.
607    pub fn peek_head(&self) -> Option<NonNull<Link>> {
608        self.head
609    }
610
611    /// Return a reference to the first element in the list, clearing the
612    /// prev/next fields in the element.
613    pub fn pop_head(&mut self) -> Option<NonNull<Link>> {
614        let head = self.head?;
615        unsafe { self.unlink_element_unchecked(head) };
616        Some(head)
617    }
618}
619
620impl UnsafeListInner {
621    /// Unchecked means:
622    /// * We don't `assert!((*element_ptr.as_ptr()).is_unlinked());`
623    /// * We don't check that `element` is non-null.
624    ///
625    /// # Safety
626    ///
627    /// It is up to the caller to ensure exclusive access to the list and its
628    /// members.
629    ///
630    /// It is up to the caller to ensure the element is not in a list.
631    pub unsafe fn sorted_insert_by_unchecked(
632        &mut self,
633        link_ptr: NonNull<Link>,
634        cmp: &mut dyn FnMut(NonNull<Link>, NonNull<Link>) -> Ordering,
635    ) {
636        let mut cur = self.head;
637
638        while let Some(cur_link_ptr) = cur {
639            unsafe {
640                if let Ordering::Less | Ordering::Equal = cmp(link_ptr, cur_link_ptr) {
641                    self.insert_before(link_ptr, cur_link_ptr);
642                    return;
643                }
644            }
645
646            cur = unsafe { cur_link_ptr.as_ref().get_next() };
647        }
648
649        // Either the list is empty or all elements are less than `link_ptr`. In
650        // both cases pushing the element to the back is appropriate.
651        unsafe {
652            self.push_back_unchecked(link_ptr);
653        }
654    }
655}
656
657impl<T, A: Adapter<T>> Default for UnsafeList<T, A> {
658    fn default() -> Self {
659        Self::new()
660    }
661}
662
663pub struct Iter<'a, T, A: Adapter<T>> {
664    front: Option<NonNull<Link>>,
665    back: Option<NonNull<Link>>,
666    _phantom: PhantomData<&'a T>,
667    _phantom_adapter: PhantomData<A>,
668}
669
670impl<'a, T, A: Adapter<T>> Iterator for Iter<'a, T, A> {
671    type Item = &'a T;
672
673    fn next(&mut self) -> Option<Self::Item> {
674        let current = self.front?;
675
676        if Some(current) == self.back {
677            self.front = None;
678            self.back = None;
679        } else {
680            // SAFETY: `current` is non-null (verified by `?`). It is a valid pointer
681            // to a `Link` inside a valid element in the list.
682            self.front = unsafe { current.as_ref().get_next() };
683        }
684
685        // SAFETY: The iterator borrows the list for lifetime `'a`. This prevents
686        // any mutations to the list (e.g., removing or reordering elements) while
687        // the iterator is alive. `current` was read from the list structure and
688        // is a valid pointer to a `Link` embedded in an instance of `T`.
689        let element = unsafe { A::get_element(current) };
690
691        // SAFETY: `element` points to a valid instance of `T` computed by the
692        // adapter. Lifetime `'a` ensures the reference remains valid for the
693        // duration of the borrow.
694        Some(unsafe { element.as_ref() })
695    }
696}
697
698impl<'a, T, A: Adapter<T>> DoubleEndedIterator for Iter<'a, T, A> {
699    fn next_back(&mut self) -> Option<Self::Item> {
700        let current = self.back?;
701
702        if Some(current) == self.front {
703            self.front = None;
704            self.back = None;
705        } else {
706            // SAFETY: `current` is non-null (verified by `?`). It is a valid pointer
707            // to a `Link` inside a valid element in the list.
708            self.back = unsafe { current.as_ref().get_prev() };
709        }
710
711        // SAFETY: The iterator borrows the list for lifetime `'a`. This prevents
712        // any mutations to the list (e.g., removing or reordering elements) while
713        // the iterator is alive. `current` was read from the list structure and
714        // is a valid pointer to a `Link` embedded in an instance of `T`.
715        let element = unsafe { A::get_element(current) };
716
717        // SAFETY: `element` points to a valid instance of `T` computed by the
718        // adapter. Lifetime `'a` ensures the reference remains valid for the
719        // duration of the borrow.
720        Some(unsafe { element.as_ref() })
721    }
722}
723
724#[cfg(test)]
725mod tests {
726    use core::ptr::NonNull;
727
728    use unittest::test;
729
730    use super::*;
731
732    // `#[repr(C)]` is used to ensure that `link` is at a non-zero offset.
733    // Previously, without this, the compiler was putting link at the beginning of
734    // the struct causing `LINK_OFFSET` in the adapter to be zero which obfuscated
735    // some pointer math bugs.
736    #[repr(C)]
737    struct TestMember {
738        value: u32,
739        link: Link,
740    }
741
742    impl PartialEq for TestMember {
743        fn eq(&self, other: &Self) -> bool {
744            self.value == other.value
745        }
746    }
747
748    impl Eq for TestMember {}
749
750    impl PartialOrd for TestMember {
751        fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
752            Some(self.cmp(other))
753        }
754    }
755
756    impl Ord for TestMember {
757        fn cmp(&self, other: &Self) -> core::cmp::Ordering {
758            self.value.cmp(&other.value)
759        }
760    }
761
762    define_adapter!(TestAdapter => TestMember::link);
763
764    unsafe fn validate_list(
765        list: &UnsafeList<TestMember, TestAdapter>,
766        expected_values: &[u32],
767    ) -> unittest::Result<()> {
768        let mut index = 0;
769        unsafe {
770            list.for_each(|element| {
771                unittest::assert_eq!(element.value, expected_values[index]);
772                index += 1;
773                Ok(())
774            })
775        }?;
776
777        unittest::assert_eq!(index, expected_values.len());
778        Ok(())
779    }
780
781    #[test]
782    fn new_link_is_not_linked() -> unittest::Result<()> {
783        let link = Link::new();
784        unittest::assert_false!(link.is_linked());
785        unittest::assert_true!(link.is_unlinked());
786        Ok(())
787    }
788
789    #[test]
790    fn new_list_is_empty() -> unittest::Result<()> {
791        let list = UnsafeList::<TestMember, TestAdapter>::new();
792        unittest::assert_true!(unsafe { list.is_empty() });
793        Ok(())
794    }
795
796    #[test]
797    fn single_element_list_is_non_empty_and_linked() -> unittest::Result<()> {
798        let mut element1 = TestMember {
799            value: 1,
800            link: Link::new(),
801        };
802
803        let element1 = NonNull::from(&mut element1);
804
805        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
806
807        unittest::assert_true!(unsafe { list.is_empty() });
808        unittest::assert_false!(unsafe { list.is_element_linked(element1) });
809
810        unsafe { list.push_front_unchecked(element1) };
811
812        unittest::assert_false!(unsafe { list.is_empty() });
813        unittest::assert_true!(unsafe { list.is_element_linked(element1) });
814
815        Ok(())
816    }
817
818    #[test]
819    fn push_front_adds_in_correct_order() -> unittest::Result<()> {
820        let mut element1 = TestMember {
821            value: 1,
822            link: Link::new(),
823        };
824        let mut element2 = TestMember {
825            value: 2,
826            link: Link::new(),
827        };
828
829        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
830        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
831        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
832
833        unittest::assert_false!(unsafe { list.is_empty() });
834
835        unsafe { validate_list(&list, &[1, 2]) }
836    }
837
838    #[test]
839    fn push_back_adds_in_correct_order() -> unittest::Result<()> {
840        let mut element1 = TestMember {
841            value: 1,
842            link: Link::new(),
843        };
844        let mut element2 = TestMember {
845            value: 2,
846            link: Link::new(),
847        };
848
849        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
850        unsafe { list.push_back_unchecked(NonNull::from(&mut element2)) };
851        unsafe { list.push_back_unchecked(NonNull::from(&mut element1)) };
852
853        unittest::assert_false!(unsafe { list.is_empty() });
854
855        unsafe { validate_list(&list, &[2, 1]) }
856    }
857
858    #[test]
859    fn unlink_removes_head_correctly() -> unittest::Result<()> {
860        let mut element1 = TestMember {
861            value: 1,
862            link: Link::new(),
863        };
864        let mut element2 = TestMember {
865            value: 2,
866            link: Link::new(),
867        };
868        let mut element3 = TestMember {
869            value: 3,
870            link: Link::new(),
871        };
872
873        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
874        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
875        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
876
877        let element1 = NonNull::from(&mut element1);
878        unsafe { list.push_front_unchecked(element1) };
879
880        unsafe { list.unlink_element_unchecked(element1) };
881
882        unsafe { validate_list(&list, &[2, 3]) }
883    }
884
885    #[test]
886    fn peek_head_returns_head_without_removing() -> unittest::Result<()> {
887        let mut element1 = TestMember {
888            value: 1,
889            link: Link::new(),
890        };
891        let mut element2 = TestMember {
892            value: 2,
893            link: Link::new(),
894        };
895
896        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
897        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
898        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
899
900        let head = unsafe { list.peek_head() };
901        unittest::assert_true!(head.is_some());
902        unittest::assert_eq!(unsafe { head.unwrap().as_ref() }.value, 1);
903        unittest::assert_false!(unsafe { list.is_empty() });
904
905        unsafe { validate_list(&list, &[1, 2]) }
906    }
907
908    #[test]
909    fn unlink_removes_tail_correctly() -> unittest::Result<()> {
910        let mut element1 = TestMember {
911            value: 1,
912            link: Link::new(),
913        };
914        let mut element2 = TestMember {
915            value: 2,
916            link: Link::new(),
917        };
918        let mut element3 = TestMember {
919            value: 3,
920            link: Link::new(),
921        };
922
923        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
924        let element3 = NonNull::from(&mut element3);
925        unsafe { list.push_front_unchecked(element3) };
926        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
927        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
928
929        unsafe { list.unlink_element_unchecked(element3) };
930
931        unsafe { validate_list(&list, &[1, 2]) }
932    }
933
934    #[test]
935    fn unlink_removes_middle_correctly() -> unittest::Result<()> {
936        let mut element1 = TestMember {
937            value: 1,
938            link: Link::new(),
939        };
940        let mut element2 = TestMember {
941            value: 2,
942            link: Link::new(),
943        };
944        let mut element3 = TestMember {
945            value: 3,
946            link: Link::new(),
947        };
948
949        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
950        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
951        let element2 = NonNull::from(&mut element2);
952        unsafe { list.push_front_unchecked(element2) };
953        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
954
955        unsafe { list.unlink_element_unchecked(element2) };
956
957        unsafe { validate_list(&list, &[1, 3]) }
958    }
959
960    #[test]
961    fn unlink_fails_non_inserted_element() -> unittest::Result<()> {
962        let mut element1 = TestMember {
963            value: 1,
964            link: Link::new(),
965        };
966
967        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
968
969        unittest::assert_eq!(
970            unsafe { list.unlink_element(NonNull::from(&mut element1)) },
971            None
972        );
973        Ok(())
974    }
975
976    #[test]
977    fn pop_head_removes_correctly() -> unittest::Result<()> {
978        let mut element1 = TestMember {
979            value: 1,
980            link: Link::new(),
981        };
982        let mut element2 = TestMember {
983            value: 2,
984            link: Link::new(),
985        };
986        let mut element3 = TestMember {
987            value: 3,
988            link: Link::new(),
989        };
990
991        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
992        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
993        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
994        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
995
996        unsafe {
997            let e = list.pop_head();
998            unittest::assert_true!(e.is_some());
999            let e = e.unwrap().as_ref();
1000            unittest::assert_eq!(e.value, 3);
1001            unittest::assert_true!(e.link.is_unlinked());
1002        }
1003
1004        unsafe {
1005            let e = list.pop_head();
1006            unittest::assert_true!(e.is_some());
1007            let e = e.unwrap().as_ref();
1008            unittest::assert_eq!(e.value, 2);
1009            unittest::assert_true!(e.link.is_unlinked());
1010        }
1011
1012        unsafe {
1013            let e = list.pop_head();
1014            unittest::assert_true!(e.is_some());
1015            let e = e.unwrap().as_ref();
1016            unittest::assert_eq!(e.value, 1);
1017            unittest::assert_true!(e.link.is_unlinked());
1018        }
1019
1020        unsafe { validate_list(&list, &[]) }
1021    }
1022
1023    #[test]
1024    fn filter_removes_nothing_correctly() -> unittest::Result<()> {
1025        let mut element1 = TestMember {
1026            value: 1,
1027            link: Link::new(),
1028        };
1029        let mut element2 = TestMember {
1030            value: 2,
1031            link: Link::new(),
1032        };
1033        let mut element3 = TestMember {
1034            value: 3,
1035            link: Link::new(),
1036        };
1037
1038        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1039        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
1040        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
1041        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
1042
1043        unsafe { list.filter(|_| true) };
1044
1045        unsafe { validate_list(&list, &[1, 2, 3]) }
1046    }
1047
1048    #[test]
1049    fn filter_removes_everything_correctly() -> unittest::Result<()> {
1050        let mut element1 = TestMember {
1051            value: 1,
1052            link: Link::new(),
1053        };
1054        let mut element2 = TestMember {
1055            value: 2,
1056            link: Link::new(),
1057        };
1058        let mut element3 = TestMember {
1059            value: 3,
1060            link: Link::new(),
1061        };
1062
1063        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1064        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
1065        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
1066        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
1067
1068        unsafe { list.filter(|_| false) };
1069
1070        unsafe { validate_list(&list, &[]) }
1071    }
1072
1073    #[test]
1074    fn filter_removes_head_correctly() -> unittest::Result<()> {
1075        let mut element1 = TestMember {
1076            value: 1,
1077            link: Link::new(),
1078        };
1079        let mut element2 = TestMember {
1080            value: 2,
1081            link: Link::new(),
1082        };
1083        let mut element3 = TestMember {
1084            value: 3,
1085            link: Link::new(),
1086        };
1087
1088        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1089        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
1090        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
1091        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
1092
1093        unsafe { list.filter(|element| element.value != 1) };
1094
1095        unsafe { validate_list(&list, &[2, 3]) }
1096    }
1097
1098    #[test]
1099    fn filter_removes_middle_correctly() -> unittest::Result<()> {
1100        let mut element1 = TestMember {
1101            value: 1,
1102            link: Link::new(),
1103        };
1104        let mut element2 = TestMember {
1105            value: 2,
1106            link: Link::new(),
1107        };
1108        let mut element3 = TestMember {
1109            value: 3,
1110            link: Link::new(),
1111        };
1112
1113        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1114        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
1115        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
1116        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
1117
1118        unsafe { list.filter(|element| element.value != 2) };
1119
1120        unsafe { validate_list(&list, &[1, 3]) }
1121    }
1122
1123    #[test]
1124    fn filter_removes_tail_correctly() -> unittest::Result<()> {
1125        let mut element1 = TestMember {
1126            value: 1,
1127            link: Link::new(),
1128        };
1129        let mut element2 = TestMember {
1130            value: 2,
1131            link: Link::new(),
1132        };
1133        let mut element3 = TestMember {
1134            value: 3,
1135            link: Link::new(),
1136        };
1137
1138        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1139        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
1140        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
1141        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
1142
1143        unsafe { list.filter(|element| element.value != 3) };
1144
1145        unsafe { validate_list(&list, &[1, 2]) }
1146    }
1147
1148    #[test]
1149    fn sorted_insert_inserts_sorted_items_in_correct_order() -> unittest::Result<()> {
1150        let mut element1 = TestMember {
1151            value: 1,
1152            link: Link::new(),
1153        };
1154        let mut element2 = TestMember {
1155            value: 2,
1156            link: Link::new(),
1157        };
1158        let mut element3 = TestMember {
1159            value: 3,
1160            link: Link::new(),
1161        };
1162
1163        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1164        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element3), TestMember::cmp) };
1165        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element2), TestMember::cmp) };
1166        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element1), TestMember::cmp) };
1167        unsafe { validate_list(&list, &[1, 2, 3]) }
1168    }
1169
1170    #[test]
1171    fn sorted_insert_inserts_reverse_sorted_items_in_correct_order() -> unittest::Result<()> {
1172        let mut element1 = TestMember {
1173            value: 1,
1174            link: Link::new(),
1175        };
1176        let mut element2 = TestMember {
1177            value: 2,
1178            link: Link::new(),
1179        };
1180        let mut element3 = TestMember {
1181            value: 3,
1182            link: Link::new(),
1183        };
1184
1185        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1186        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element1), TestMember::cmp) };
1187        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element2), TestMember::cmp) };
1188        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element3), TestMember::cmp) };
1189        unsafe { validate_list(&list, &[1, 2, 3]) }
1190    }
1191
1192    #[test]
1193    fn sorted_insert_inserts_unsorted_items_in_correct_order() -> unittest::Result<()> {
1194        let mut element1 = TestMember {
1195            value: 1,
1196            link: Link::new(),
1197        };
1198        let mut element2 = TestMember {
1199            value: 2,
1200            link: Link::new(),
1201        };
1202        let mut element2_2 = TestMember {
1203            value: 2,
1204            link: Link::new(),
1205        };
1206        let mut element3 = TestMember {
1207            value: 3,
1208            link: Link::new(),
1209        };
1210
1211        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1212        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element2), TestMember::cmp) };
1213        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element1), TestMember::cmp) };
1214        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element3), TestMember::cmp) };
1215        unsafe { list.sorted_insert_by_unchecked(NonNull::from(&mut element2_2), TestMember::cmp) };
1216        unsafe { validate_list(&list, &[1, 2, 2, 3]) }
1217    }
1218
1219    #[test]
1220    fn double_ended_iterator_works() -> unittest::Result<()> {
1221        let mut element1 = TestMember {
1222            value: 1,
1223            link: Link::new(),
1224        };
1225        let mut element2 = TestMember {
1226            value: 2,
1227            link: Link::new(),
1228        };
1229        let mut element3 = TestMember {
1230            value: 3,
1231            link: Link::new(),
1232        };
1233
1234        let mut list = UnsafeList::<TestMember, TestAdapter>::new();
1235        unsafe { list.push_front_unchecked(NonNull::from(&mut element3)) };
1236        unsafe { list.push_front_unchecked(NonNull::from(&mut element2)) };
1237        unsafe { list.push_front_unchecked(NonNull::from(&mut element1)) };
1238
1239        let mut iter = list.iter();
1240
1241        // [1, 2, 3]
1242        unittest::assert_eq!(iter.next().unwrap().value, 1);
1243        // [2, 3]
1244        unittest::assert_eq!(iter.next_back().unwrap().value, 3);
1245        // [2]
1246        unittest::assert_eq!(iter.next().unwrap().value, 2);
1247        // []
1248        unittest::assert_true!(iter.next().is_none());
1249        unittest::assert_true!(iter.next_back().is_none());
1250
1251        Ok(())
1252    }
1253}