#![allow(rustdoc::redundant_explicit_links)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(any(feature = "std", test))]
extern crate std;
use core::borrow::BorrowMut;
use core::fmt;
use core::marker::PhantomData;
use core::mem::{self, MaybeUninit};
use core::ptr::{self, null_mut};
use pointers::Pointer;
pub unsafe trait SListItem<Tag>: Sized {
fn get_node(&self) -> &mut SListNode<Tag>;
#[allow(unsafe_op_in_unsafe_fn)]
#[inline(always)]
unsafe fn get_node_from_ptr<'a>(p: *mut u8) -> &'a mut SListNode<Tag>
where
Self: 'a,
{
debug_assert!(!p.is_null());
(*(p as *const Self)).get_node()
}
}
#[repr(C)]
pub struct SListNode<Tag> {
next: *mut u8,
_phan: PhantomData<fn(&Tag)>,
}
unsafe impl<Tag> Send for SListNode<Tag> {}
impl<Tag> Default for SListNode<Tag> {
#[inline(always)]
fn default() -> Self {
Self { next: null_mut(), _phan: Default::default() }
}
}
impl<Tag> fmt::Debug for SListNode<Tag> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(")?;
if !self.next.is_null() {
write!(f, "next: {:p} ", self.next)?;
} else {
write!(f, "next: none ")?;
}
write!(f, ")")
}
}
#[repr(C)]
pub struct SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
length: usize,
head: *mut u8,
tail: *mut u8,
_phan: PhantomData<fn(&P, &Tag)>,
}
unsafe impl<P, Tag> Send for SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
}
impl<P: fmt::Debug, Tag> fmt::Debug for SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{ length: {} ", self.length)?;
if !self.head.is_null() {
write!(f, "head: {:?} ", self.head)?;
} else {
write!(f, "head: none ")?;
}
if !self.tail.is_null() {
write!(f, "tail: {:?} ", self.tail)?;
} else {
write!(f, "tail: none ")?;
}
write!(f, "}}")
}
}
impl<P, Tag> SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
#[inline(always)]
pub fn new() -> Self {
SLinkedList { length: 0, head: null_mut(), tail: null_mut(), _phan: Default::default() }
}
#[inline]
pub fn clear(&mut self) {
while self.pop_front().is_some() {}
}
#[inline(always)]
pub fn len(&self) -> usize {
self.length
}
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.length == 0
}
#[inline]
pub fn push_back(&mut self, item: P) {
let ptr = item.into_raw() as *mut u8;
unsafe {
let node = <P::Target as SListItem<Tag>>::get_node_from_ptr(ptr);
node.next = null_mut();
if !self.tail.is_null() {
<P::Target as SListItem<Tag>>::get_node_from_ptr(self.tail).next = ptr;
} else {
self.head = ptr;
}
}
self.tail = ptr;
self.length += 1;
}
#[inline]
pub fn push_front(&mut self, item: P) {
let ptr = item.into_raw() as *mut u8;
let node = unsafe { <P::Target as SListItem<Tag>>::get_node_from_ptr(ptr) };
node.next = self.head;
if !self.head.is_null() {
} else {
self.tail = ptr;
}
self.head = ptr;
self.length += 1;
}
pub fn pop_front(&mut self) -> Option<P> {
if !self.head.is_null() {
let head_ptr = self.head;
let node = unsafe { <P::Target as SListItem<Tag>>::get_node_from_ptr(head_ptr) };
let next_ptr = node.next;
node.next = null_mut();
self.head = next_ptr;
self.length -= 1;
if !self.head.is_null() {
} else {
self.tail = null_mut();
}
Some(unsafe { P::from_raw(head_ptr as *const P::Target) })
} else {
None
}
}
#[inline]
pub fn get_front_ptr(&self) -> *const P::Target {
self.head as *const P::Target
}
#[inline]
pub fn get_back_ptr(&self) -> *const P::Target {
self.tail as *const P::Target
}
#[inline]
pub fn get_front(&self) -> Option<&P::Target> {
if !self.head.is_null() {
unsafe { Some(&(*(self.head as *const P::Target))) }
} else {
None
}
}
#[inline]
pub fn get_back(&self) -> Option<&P::Target> {
if !self.tail.is_null() {
unsafe { Some(&(*(self.tail as *const P::Target))) }
} else {
None
}
}
#[inline(always)]
pub fn is_front(&self, node: &P::Target) -> bool {
if !self.head.is_null() {
ptr::eq(self.head, node as *const P::Target as *const u8)
} else {
false
}
}
#[inline(always)]
pub fn iter<'a>(&'a self) -> SLinkedListIter<'a, P, Tag> {
SLinkedListIter {
len: self.length,
next_p: self.head,
cur: MaybeUninit::uninit(),
_phan: Default::default(),
}
}
#[inline(always)]
pub fn drain<'a>(&'a mut self) -> SLinkedListDrainer<'a, P, Tag> {
SLinkedListDrainer { list: self, _phan: Default::default() }
}
}
impl<P, Tag> Drop for SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
fn drop(&mut self) {
if mem::needs_drop::<P>() {
self.drain().for_each(drop);
}
}
}
pub struct SLinkedListIter<'a, P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
next_p: *mut u8,
cur: MaybeUninit<P>,
len: usize,
_phan: PhantomData<&'a SLinkedList<P, Tag>>,
}
unsafe impl<'a, P, Tag> Send for SLinkedListIter<'a, P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
}
impl<'a, P, Tag> Iterator for SLinkedListIter<'a, P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
type Item = &'a P;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if !self.next_p.is_null() {
let cur = self.next_p;
unsafe {
self.next_p = <P::Target as SListItem<Tag>>::get_node_from_ptr(cur).next;
self.cur.write(P::from_raw(cur as *const P::Target));
return Some(mem::transmute::<&P, &P>(self.cur.assume_init_ref()));
}
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
impl<'a, P, Tag> ExactSizeIterator for SLinkedListIter<'a, P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
}
pub type SLinkedListDrainer<'a, P, Tag> = Drainer<&'a mut SLinkedList<P, Tag>, P, Tag>;
pub type SLinkedListIntoIter<P, Tag> = Drainer<SLinkedList<P, Tag>, P, Tag>;
pub struct Drainer<L, P, Tag>
where
L: BorrowMut<SLinkedList<P, Tag>>,
P: Pointer,
P::Target: SListItem<Tag>,
{
list: L,
_phan: PhantomData<(P, Tag)>,
}
impl<L, P, Tag> Iterator for Drainer<L, P, Tag>
where
L: BorrowMut<SLinkedList<P, Tag>>,
P: Pointer,
P::Target: SListItem<Tag>,
{
type Item = P;
#[inline]
fn next(&mut self) -> Option<P> {
self.list.borrow_mut().pop_front()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let l = self.list.borrow().len();
(l, Some(l))
}
}
impl<L, P, Tag> ExactSizeIterator for Drainer<L, P, Tag>
where
L: BorrowMut<SLinkedList<P, Tag>>,
P: Pointer,
P::Target: SListItem<Tag>,
{
}
impl<'a, P, Tag> IntoIterator for &'a SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
type Item = &'a P;
type IntoIter = SLinkedListIter<'a, P, Tag>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<P, Tag> IntoIterator for SLinkedList<P, Tag>
where
P: Pointer,
P::Target: SListItem<Tag>,
{
type Item = P;
type IntoIter = SLinkedListIntoIter<P, Tag>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
Drainer { list: self, _phan: Default::default() }
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::boxed::Box;
use std::cell::UnsafeCell;
use std::sync::atomic::{AtomicUsize, Ordering};
pub struct TestTag;
#[derive(Debug)]
pub struct TestNode {
pub value: i64,
pub node: UnsafeCell<SListNode<TestTag>>,
}
static ACTIVE_NODE_COUNT: AtomicUsize = AtomicUsize::new(0);
impl Drop for TestNode {
fn drop(&mut self) {
ACTIVE_NODE_COUNT.fetch_sub(1, Ordering::SeqCst);
}
}
unsafe impl Send for TestNode {}
unsafe impl SListItem<TestTag> for TestNode {
fn get_node(&self) -> &mut SListNode<TestTag> {
unsafe { &mut *self.node.get() }
}
}
fn new_node(v: i64) -> TestNode {
ACTIVE_NODE_COUNT.fetch_add(1, Ordering::SeqCst);
TestNode { value: v, node: UnsafeCell::new(SListNode::default()) }
}
#[test]
fn test_push_back_pop_front_box() {
ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
let node1 = Box::new(new_node(1));
l.push_back(node1);
let node2 = Box::new(new_node(2));
l.push_back(node2);
let node3 = Box::new(new_node(3));
l.push_back(node3);
assert_eq!(3, l.len());
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
let mut iter = l.iter();
assert_eq!(iter.next().unwrap().value, 1);
assert_eq!(iter.next().unwrap().value, 2);
assert_eq!(iter.next().unwrap().value, 3);
assert!(iter.next().is_none());
let n1 = l.pop_front();
assert!(n1.is_some());
assert_eq!(n1.unwrap().value, 1);
assert_eq!(l.len(), 2);
let n2 = l.pop_front();
assert!(n2.is_some());
assert_eq!(n2.unwrap().value, 2);
assert_eq!(l.len(), 1);
let n3 = l.pop_front();
assert!(n3.is_some());
assert_eq!(n3.unwrap().value, 3);
assert_eq!(l.len(), 0);
assert!(l.pop_front().is_none());
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
}
#[test]
fn test_push_front_box() {
ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
let node1 = Box::new(new_node(1));
l.push_front(node1);
let node2 = Box::new(new_node(2));
l.push_front(node2);
let node3 = Box::new(new_node(3));
l.push_front(node3);
assert_eq!(3, l.len());
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
let mut iter = l.iter();
assert_eq!(iter.next().unwrap().value, 3);
assert_eq!(iter.next().unwrap().value, 2);
assert_eq!(iter.next().unwrap().value, 1);
assert!(iter.next().is_none());
let n1 = l.pop_front();
assert!(n1.is_some());
assert_eq!(n1.unwrap().value, 3);
assert_eq!(l.len(), 2);
let n2 = l.pop_front();
assert!(n2.is_some());
assert_eq!(n2.unwrap().value, 2);
assert_eq!(l.len(), 1);
let n3 = l.pop_front();
assert!(n3.is_some());
assert_eq!(n3.unwrap().value, 1);
assert_eq!(l.len(), 0);
assert!(l.pop_front().is_none());
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
}
#[test]
fn test_drain() {
ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
l.push_back(Box::new(new_node(10)));
l.push_back(Box::new(new_node(20)));
l.push_back(Box::new(new_node(30)));
assert_eq!(l.len(), 3);
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
{
let mut drain = l.drain();
assert_eq!(drain.next().unwrap().value, 10);
assert_eq!(drain.next().unwrap().value, 20);
assert_eq!(drain.next().unwrap().value, 30);
assert!(drain.next().is_none());
}
assert_eq!(l.len(), 0);
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
}
#[test]
fn test_clear() {
ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
l.push_back(Box::new(new_node(1)));
l.push_back(Box::new(new_node(2)));
assert_eq!(l.len(), 2);
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 2);
l.clear();
assert!(l.is_empty());
assert_eq!(l.len(), 0);
assert!(l.get_front().is_none());
assert!(l.get_back().is_none());
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
l.push_back(Box::new(new_node(3)));
assert_eq!(l.len(), 1);
assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 1);
}
}