Skip to main content

embed_slist/
lib.rs

1#![allow(rustdoc::redundant_explicit_links)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(docsrs, allow(unused_attributes))]
4#![cfg_attr(not(feature = "std"), no_std)]
5
6//! An intrusive singly linked list implementation.
7//!
8//! This module provides `SLinkedList`, a singly linked list optimized for FIFO (First-In, First-Out)
9//! queue-like behavior. Elements embed the list nodes themselves, offering memory efficiency
10//! and explicit control over allocation.
11//!
12//! # Features
13//! - O(1) push to back and pop from front.
14//! - Generic over pointer types (`Box`, `Arc`, `NonNull`, raw pointers).
15//!
16//! # Example
17//!
18//! ```rust
19//! use embed_slist::{SLinkedList, SListItem, SListNode};
20//! use core::cell::UnsafeCell;
21//! use std::sync::Arc;
22//! use core::ptr::NonNull;
23//!
24//! struct MyTask {
25//!     priority: u8,
26//!     description: String,
27//!     node: UnsafeCell<SListNode<MyTask, ()>>,
28//! }
29//!
30//! impl MyTask {
31//!     fn new(priority: u8, desc: &str) -> Self {
32//!         MyTask {
33//!             priority,
34//!             description: desc.to_string(),
35//!             node: UnsafeCell::new(SListNode::default()),
36//!         }
37//!     }
38//! }
39//!
40//! unsafe impl SListItem<()> for MyTask {
41//!     fn get_node(&self) -> &mut SListNode<Self, ()> {
42//!         unsafe { &mut *self.node.get() }
43//!     }
44//! }
45//!
46//! // Using Box<T> (owned pointers)
47//! {
48//!     let mut task_queue = SLinkedList::<Box<MyTask>, ()>::new();
49//!     task_queue.push_back(Box::new(MyTask::new(1, "Handle user login")));
50//!     task_queue.push_back(Box::new(MyTask::new(2, "Process analytics data")));
51//!     task_queue.push_back(Box::new(MyTask::new(1, "Send welcome email")));
52//!     assert_eq!(task_queue.len(), 3);
53//!     assert_eq!(task_queue.pop_front().unwrap().description, "Handle user login");
54//!     assert_eq!(task_queue.pop_front().unwrap().description, "Process analytics data");
55//!     assert_eq!(task_queue.pop_front().unwrap().description, "Send welcome email");
56//!     assert!(task_queue.is_empty());
57//! }
58//!
59//! // Using Arc<T> (shared ownership)
60//! {
61//!     let mut task_queue = SLinkedList::<Arc<MyTask>, ()>::new();
62//!     task_queue.push_back(Arc::new(MyTask::new(1, "Handle user login")));
63//!     task_queue.push_back(Arc::new(MyTask::new(2, "Process analytics data")));
64//!     task_queue.push_back(Arc::new(MyTask::new(1, "Send welcome email")));
65//!     assert_eq!(task_queue.len(), 3);
66//!     assert_eq!(task_queue.pop_front().unwrap().description, "Handle user login");
67//!     assert_eq!(task_queue.pop_front().unwrap().description, "Process analytics data");
68//!     assert_eq!(task_queue.pop_front().unwrap().description, "Send welcome email");
69//!     assert!(task_queue.is_empty());
70//! }
71//!
72//! // Using NonNull<T> (raw pointers without ownership)
73//! {
74//!     let mut task_queue = SLinkedList::<NonNull<MyTask>, ()>::new();
75//!     let task1 = Box::leak(Box::new(MyTask::new(1, "Handle user login")));
76//!     let task2 = Box::leak(Box::new(MyTask::new(2, "Process analytics data")));
77//!     let task3 = Box::leak(Box::new(MyTask::new(1, "Send welcome email")));
78//!     task_queue.push_back(NonNull::from(task1));
79//!     task_queue.push_back(NonNull::from(task2));
80//!     task_queue.push_back(NonNull::from(task3));
81//!     assert_eq!(task_queue.len(), 3);
82//!     assert_eq!(unsafe { &task_queue.pop_front().unwrap().as_ref().description }, "Handle user login");
83//!     assert_eq!(unsafe { &task_queue.pop_front().unwrap().as_ref().description }, "Process analytics data");
84//!     assert_eq!(unsafe { &task_queue.pop_front().unwrap().as_ref().description }, "Send welcome email");
85//!     assert!(task_queue.is_empty());
86//! }
87//! ```
88
89extern crate alloc;
90#[cfg(any(feature = "std", test))]
91extern crate std;
92
93use core::fmt;
94use core::marker::PhantomData;
95use core::mem;
96use core::ptr::{self, null};
97use pointers::Pointer;
98
99/// A trait to return internal mutable SListNode for specified list.
100///
101/// The tag is used to distinguish different SListNodes within the same item.
102/// For only one ownership, you can use `()`.
103///
104/// # Safety
105/// Implementors must ensure `get_node` returns a valid reference to the `SListNode`
106/// embedded within `Self`. Users must use `UnsafeCell` to hold `SListNode` to support
107/// interior mutability required by list operations.
108pub unsafe trait SListItem<Tag>: Sized {
109    fn get_node(&self) -> &mut SListNode<Self, Tag>;
110}
111
112/// The node structure that must be embedded in items to be stored in a `SLinkedList`.
113///
114#[repr(C)]
115pub struct SListNode<T: Sized, Tag> {
116    next: *const T,
117    _phan: PhantomData<fn(&Tag)>,
118}
119
120unsafe impl<T, Tag> Send for SListNode<T, Tag> {}
121
122impl<T: SListItem<Tag>, Tag> SListNode<T, Tag> {}
123
124impl<T, Tag> Default for SListNode<T, Tag> {
125    #[inline(always)]
126    fn default() -> Self {
127        Self { next: null(), _phan: Default::default() }
128    }
129}
130
131impl<T: SListItem<Tag> + fmt::Debug, Tag> fmt::Debug for SListNode<T, Tag> {
132    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133        write!(f, "(")?;
134        if !self.next.is_null() {
135            write!(f, "next: {:p} ", self.next)?;
136        } else {
137            write!(f, "next: none ")?;
138        }
139        write!(f, ")")
140    }
141}
142
143/// A singly linked list with head and tail pointers (FIFO queue).
144///
145/// Supports O(1) push to back and pop from front.
146#[repr(C)]
147pub struct SLinkedList<P, Tag>
148where
149    P: Pointer,
150    P::Target: SListItem<Tag>,
151{
152    length: usize,
153    head: *const P::Target,
154    tail: *const P::Target,
155    _phan: PhantomData<fn(&Tag)>,
156}
157
158unsafe impl<P, Tag> Send for SLinkedList<P, Tag>
159where
160    P: Pointer,
161    P::Target: SListItem<Tag>,
162{
163}
164
165impl<P: fmt::Debug, Tag> fmt::Debug for SLinkedList<P, Tag>
166where
167    P: Pointer,
168    P::Target: SListItem<Tag>,
169{
170    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171        write!(f, "{{ length: {} ", self.length)?;
172        if !self.head.is_null() {
173            write!(f, "head: {:?} ", self.head)?;
174        } else {
175            write!(f, "head: none ")?;
176        }
177        if !self.tail.is_null() {
178            write!(f, "tail: {:?} ", self.tail)?;
179        } else {
180            write!(f, "tail: none ")?;
181        }
182        write!(f, "}}")
183    }
184}
185
186impl<P, Tag> SLinkedList<P, Tag>
187where
188    P: Pointer,
189    P::Target: SListItem<Tag>,
190{
191    /// Creates a new, empty singly linked list.
192    #[inline(always)]
193    pub fn new() -> Self {
194        SLinkedList { length: 0, head: null(), tail: null(), _phan: Default::default() }
195    }
196
197    /// Clears the list, dropping all of its elements if the pointer type `P` owns them.
198    #[inline]
199    pub fn clear(&mut self) {
200        // By repeatedly popping from the front, we drop each element.
201        // If P is an owned pointer (like Box), the element is dropped.
202        // If P is a raw pointer, it's a no-op, but the list is still emptied.
203        while self.pop_front().is_some() {}
204    }
205
206    /// Returns the length of the list as `usize`.
207    #[inline(always)]
208    pub fn len(&self) -> usize {
209        self.length
210    }
211
212    /// Returns `true` if the list contains no elements.
213    #[inline(always)]
214    pub fn is_empty(&self) -> bool {
215        self.length == 0
216    }
217
218    /// Appends an element to the back of the list (FIFO: enqueue).
219    #[inline]
220    pub fn push_back(&mut self, item: P) {
221        let node = item.as_ref().get_node();
222        node.next = null();
223        let ptr = item.into_raw();
224        if self.tail.is_null() {
225            // List is empty
226            self.head = ptr;
227        } else {
228            // List is not empty, update current tail's next
229            unsafe {
230                (*self.tail).get_node().next = ptr;
231            }
232        }
233        self.tail = ptr;
234        self.length += 1;
235    }
236
237    /// Pushes an element to the front of the list.
238    #[inline]
239    pub fn push_front(&mut self, item: P) {
240        let ptr = item.into_raw();
241        let node = unsafe { (*ptr).get_node() };
242        node.next = self.head;
243        if self.head.is_null() {
244            // List was empty
245            self.tail = ptr;
246        }
247        self.head = ptr;
248        self.length += 1;
249    }
250
251    /// Removes the first element and returns it (FIFO: dequeue).
252    pub fn pop_front(&mut self) -> Option<P> {
253        if self.head.is_null() {
254            None
255        } else {
256            let head_ptr = self.head;
257            let node = unsafe { (*head_ptr).get_node() };
258            let next_ptr = node.next;
259
260            // Update head to next
261            self.head = next_ptr;
262
263            // If head became null (list empty), update tail to null too
264            if self.head.is_null() {
265                self.tail = null();
266            }
267
268            // Clean up the removed node's next pointer
269            node.next = null();
270            self.length -= 1;
271
272            Some(unsafe { P::from_raw(head_ptr) })
273        }
274    }
275
276    /// Returns a reference to the front element.
277    #[inline]
278    pub fn get_front(&self) -> Option<&P::Target> {
279        if self.head.is_null() { None } else { unsafe { Some(&(*self.head)) } }
280    }
281
282    /// Returns a reference to the back element.
283    #[inline]
284    pub fn get_back(&self) -> Option<&P::Target> {
285        if self.tail.is_null() { None } else { unsafe { Some(&(*self.tail)) } }
286    }
287
288    /// Checks if the given node is the head of the list.
289    #[inline(always)]
290    pub fn is_front(&self, node: &P::Target) -> bool {
291        if self.head.is_null() { false } else { ptr::eq(self.head, node) }
292    }
293
294    /// Returns an iterator over the list (borrowed).
295    ///
296    /// # NOTE
297    ///
298    /// If you plan on turn the raw pointer to owned, use drain instead
299    ///
300    /// # Safety
301    ///
302    /// The caller must ensure that the list is not modified in a way that can
303    /// invalidate internal pointers (such as removing elements or dropping
304    /// items) for the duration of the iterator's use.
305    #[inline(always)]
306    pub fn iter<'a>(&'a self) -> SLinkedListIterator<'a, P, Tag> {
307        SLinkedListIterator { list: self, cur: null() }
308    }
309
310    /// Returns a draining iterator that removes items from the list.
311    #[inline(always)]
312    pub fn drain<'a>(&'a mut self) -> SLinkedListDrainer<'a, P, Tag> {
313        SLinkedListDrainer { list: self }
314    }
315}
316
317impl<P, Tag> Drop for SLinkedList<P, Tag>
318where
319    P: Pointer,
320    P::Target: SListItem<Tag>,
321{
322    fn drop(&mut self) {
323        if mem::needs_drop::<P>() {
324            self.drain().for_each(drop);
325        }
326    }
327}
328
329pub struct SLinkedListIterator<'a, P, Tag>
330where
331    P: Pointer,
332    P::Target: SListItem<Tag>,
333{
334    list: &'a SLinkedList<P, Tag>,
335    cur: *const P::Target,
336}
337
338unsafe impl<'a, P, Tag> Send for SLinkedListIterator<'a, P, Tag>
339where
340    P: Pointer,
341    P::Target: SListItem<Tag>,
342{
343}
344
345impl<'a, P, Tag> Iterator for SLinkedListIterator<'a, P, Tag>
346where
347    P: Pointer,
348    P::Target: SListItem<Tag>,
349{
350    type Item = &'a P::Target;
351
352    fn next(&mut self) -> Option<Self::Item> {
353        if self.cur.is_null() {
354            if self.list.head.is_null() {
355                return None;
356            } else {
357                self.cur = self.list.head;
358            }
359        } else {
360            let next = unsafe { (*self.cur).get_node().next };
361            if next.is_null() {
362                return None;
363            } else {
364                self.cur = next;
365            }
366        }
367        unsafe { Some(&(*self.cur)) }
368    }
369}
370
371pub struct SLinkedListDrainer<'a, P, Tag>
372where
373    P: Pointer,
374    P::Target: SListItem<Tag>,
375{
376    list: &'a mut SLinkedList<P, Tag>,
377}
378
379unsafe impl<'a, P, Tag> Send for SLinkedListDrainer<'a, P, Tag>
380where
381    P: Pointer,
382    P::Target: SListItem<Tag>,
383{
384}
385
386impl<'a, P, Tag> Iterator for SLinkedListDrainer<'a, P, Tag>
387where
388    P: Pointer,
389    P::Target: SListItem<Tag>,
390{
391    type Item = P;
392
393    #[inline]
394    fn next(&mut self) -> Option<P> {
395        self.list.pop_front()
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use alloc::boxed::Box;
403    use std::cell::UnsafeCell;
404    use std::sync::atomic::{AtomicUsize, Ordering};
405
406    pub struct TestTag;
407
408    #[derive(Debug)]
409    pub struct TestNode {
410        pub value: i64,
411        pub node: UnsafeCell<SListNode<Self, TestTag>>,
412    }
413
414    static ACTIVE_NODE_COUNT: AtomicUsize = AtomicUsize::new(0);
415
416    impl Drop for TestNode {
417        fn drop(&mut self) {
418            ACTIVE_NODE_COUNT.fetch_sub(1, Ordering::SeqCst);
419        }
420    }
421
422    unsafe impl Send for TestNode {}
423
424    unsafe impl SListItem<TestTag> for TestNode {
425        fn get_node(&self) -> &mut SListNode<Self, TestTag> {
426            unsafe { &mut *self.node.get() }
427        }
428    }
429
430    fn new_node(v: i64) -> TestNode {
431        ACTIVE_NODE_COUNT.fetch_add(1, Ordering::SeqCst);
432        TestNode { value: v, node: UnsafeCell::new(SListNode::default()) }
433    }
434
435    #[test]
436    fn test_push_back_pop_front_box() {
437        ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
438        let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
439
440        let node1 = Box::new(new_node(1));
441        l.push_back(node1);
442
443        let node2 = Box::new(new_node(2));
444        l.push_back(node2);
445
446        let node3 = Box::new(new_node(3));
447        l.push_back(node3);
448
449        assert_eq!(3, l.len());
450        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
451
452        // Test iterator
453        let mut iter = l.iter();
454        assert_eq!(iter.next().unwrap().value, 1);
455        assert_eq!(iter.next().unwrap().value, 2);
456        assert_eq!(iter.next().unwrap().value, 3);
457        assert!(iter.next().is_none());
458
459        // Test pop_front (FIFO)
460        let n1 = l.pop_front();
461        assert!(n1.is_some());
462        assert_eq!(n1.unwrap().value, 1);
463        assert_eq!(l.len(), 2);
464
465        let n2 = l.pop_front();
466        assert!(n2.is_some());
467        assert_eq!(n2.unwrap().value, 2);
468        assert_eq!(l.len(), 1);
469
470        let n3 = l.pop_front();
471        assert!(n3.is_some());
472        assert_eq!(n3.unwrap().value, 3);
473        assert_eq!(l.len(), 0);
474
475        assert!(l.pop_front().is_none());
476        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
477    }
478
479    #[test]
480    fn test_push_front_box() {
481        ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
482        let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
483
484        let node1 = Box::new(new_node(1));
485        l.push_front(node1); // List: [1]
486
487        let node2 = Box::new(new_node(2));
488        l.push_front(node2); // List: [2, 1]
489
490        let node3 = Box::new(new_node(3));
491        l.push_front(node3); // List: [3, 2, 1]
492
493        assert_eq!(3, l.len());
494        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
495
496        // Test iterator (should be 3, 2, 1)
497        let mut iter = l.iter();
498        assert_eq!(iter.next().unwrap().value, 3);
499        assert_eq!(iter.next().unwrap().value, 2);
500        assert_eq!(iter.next().unwrap().value, 1);
501        assert!(iter.next().is_none());
502
503        // Test pop_front (FIFO)
504        let n1 = l.pop_front();
505        assert!(n1.is_some());
506        assert_eq!(n1.unwrap().value, 3);
507        assert_eq!(l.len(), 2);
508
509        let n2 = l.pop_front();
510        assert!(n2.is_some());
511        assert_eq!(n2.unwrap().value, 2);
512        assert_eq!(l.len(), 1);
513
514        let n3 = l.pop_front();
515        assert!(n3.is_some());
516        assert_eq!(n3.unwrap().value, 1);
517        assert_eq!(l.len(), 0);
518
519        assert!(l.pop_front().is_none());
520        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
521    }
522
523    #[test]
524    fn test_drain() {
525        ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
526        let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
527
528        l.push_back(Box::new(new_node(10)));
529        l.push_back(Box::new(new_node(20)));
530        l.push_back(Box::new(new_node(30)));
531
532        assert_eq!(l.len(), 3);
533        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
534
535        {
536            let mut drain = l.drain();
537            assert_eq!(drain.next().unwrap().value, 10);
538            assert_eq!(drain.next().unwrap().value, 20);
539            assert_eq!(drain.next().unwrap().value, 30);
540            assert!(drain.next().is_none());
541        }
542
543        assert_eq!(l.len(), 0);
544        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
545    }
546
547    #[test]
548    fn test_clear() {
549        ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
550        let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
551
552        l.push_back(Box::new(new_node(1)));
553        l.push_back(Box::new(new_node(2)));
554        assert_eq!(l.len(), 2);
555        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 2);
556
557        l.clear();
558
559        assert!(l.is_empty());
560        assert_eq!(l.len(), 0);
561        assert!(l.get_front().is_none());
562        assert!(l.get_back().is_none());
563        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
564
565        // Can still push to the list
566        l.push_back(Box::new(new_node(3)));
567        assert_eq!(l.len(), 1);
568        assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 1);
569    }
570}