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
6extern 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
99pub unsafe trait SListItem<Tag>: Sized {
109 fn get_node(&self) -> &mut SListNode<Self, Tag>;
110}
111
112#[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#[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 #[inline(always)]
193 pub fn new() -> Self {
194 SLinkedList { length: 0, head: null(), tail: null(), _phan: Default::default() }
195 }
196
197 #[inline]
199 pub fn clear(&mut self) {
200 while self.pop_front().is_some() {}
204 }
205
206 #[inline(always)]
208 pub fn len(&self) -> usize {
209 self.length
210 }
211
212 #[inline(always)]
214 pub fn is_empty(&self) -> bool {
215 self.length == 0
216 }
217
218 #[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 self.head = ptr;
227 } else {
228 unsafe {
230 (*self.tail).get_node().next = ptr;
231 }
232 }
233 self.tail = ptr;
234 self.length += 1;
235 }
236
237 #[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 self.tail = ptr;
246 }
247 self.head = ptr;
248 self.length += 1;
249 }
250
251 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 self.head = next_ptr;
262
263 if self.head.is_null() {
265 self.tail = null();
266 }
267
268 node.next = null();
270 self.length -= 1;
271
272 Some(unsafe { P::from_raw(head_ptr) })
273 }
274 }
275
276 #[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 #[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 #[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 #[inline(always)]
306 pub fn iter<'a>(&'a self) -> SLinkedListIterator<'a, P, Tag> {
307 SLinkedListIterator { list: self, cur: null() }
308 }
309
310 #[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 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 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); let node2 = Box::new(new_node(2));
488 l.push_front(node2); let node3 = Box::new(new_node(3));
491 l.push_front(node3); assert_eq!(3, l.len());
494 assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
495
496 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 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 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}