1use crate::Pointer;
56use core::fmt;
57use core::marker::PhantomData;
58use core::mem;
59use core::ptr::null;
60
61pub unsafe trait SListItem<Tag>: Sized {
70 fn get_node(&self) -> &mut SListNode<Self, Tag>;
71}
72
73#[repr(C)]
75pub struct SListNode<T: Sized, Tag> {
76 next: *const T,
77 _phan: PhantomData<fn(&Tag)>,
78}
79
80unsafe impl<T, Tag> Send for SListNode<T, Tag> {}
81
82impl<T: SListItem<Tag>, Tag> SListNode<T, Tag> {}
83
84impl<T, Tag> Default for SListNode<T, Tag> {
85 #[inline(always)]
86 fn default() -> Self {
87 Self { next: null(), _phan: Default::default() }
88 }
89}
90
91impl<T: SListItem<Tag> + fmt::Debug, Tag> fmt::Debug for SListNode<T, Tag> {
92 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 write!(f, "(")?;
94 if !self.next.is_null() {
95 write!(f, "next: {:p} ", self.next)?;
96 } else {
97 write!(f, "next: none ")?;
98 }
99 write!(f, ")")
100 }
101}
102
103#[repr(C)]
107pub struct SLinkedList<P, Tag>
108where
109 P: Pointer,
110 P::Target: SListItem<Tag>,
111{
112 length: u64,
113 head: *const P::Target,
114 tail: *const P::Target,
115 _phan: PhantomData<fn(&Tag)>,
116}
117
118unsafe impl<P, Tag> Send for SLinkedList<P, Tag>
119where
120 P: Pointer,
121 P::Target: SListItem<Tag>,
122{
123}
124
125impl<P: fmt::Debug, Tag> fmt::Debug for SLinkedList<P, Tag>
126where
127 P: Pointer,
128 P::Target: SListItem<Tag>,
129{
130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
131 write!(f, "{{ length: {} ", self.length)?;
132 if !self.head.is_null() {
133 write!(f, "head: {:?} ", self.head)?;
134 } else {
135 write!(f, "head: none ")?;
136 }
137 if !self.tail.is_null() {
138 write!(f, "tail: {:?} ", self.tail)?;
139 } else {
140 write!(f, "tail: none ")?;
141 }
142 write!(f, "}}")
143 }
144}
145
146impl<P, Tag> SLinkedList<P, Tag>
147where
148 P: Pointer,
149 P::Target: SListItem<Tag>,
150{
151 #[inline(always)]
153 pub fn new() -> Self {
154 SLinkedList { length: 0, head: null(), tail: null(), _phan: Default::default() }
155 }
156
157 #[inline]
160 pub fn clear(&mut self) {
161 self.length = 0;
162 self.head = null();
163 self.tail = null();
164 }
165
166 #[inline(always)]
168 pub fn get_length(&self) -> u64 {
169 return self.length;
170 }
171
172 #[inline(always)]
174 pub fn len(&self) -> usize {
175 return self.length as usize;
176 }
177
178 #[inline(always)]
180 pub fn is_empty(&self) -> bool {
181 self.length == 0
182 }
183
184 #[inline]
186 pub fn push_back(&mut self, item: P) {
187 let node = item.as_ref().get_node();
188 node.next = null();
189
190 let ptr = item.into_raw();
191
192 if self.tail.is_null() {
193 self.head = ptr;
195 } else {
196 unsafe {
198 (*self.tail).get_node().next = ptr;
199 }
200 }
201 self.tail = ptr;
202 self.length += 1;
203 }
204
205 pub fn pop_front(&mut self) -> Option<P> {
207 if self.head.is_null() {
208 None
209 } else {
210 let head_ptr = self.head;
211 let node = unsafe { (*head_ptr).get_node() };
212 let next_ptr = node.next;
213
214 self.head = next_ptr;
216
217 if self.head.is_null() {
219 self.tail = null();
220 }
221
222 node.next = null();
224 self.length -= 1;
225
226 Some(unsafe { P::from_raw(head_ptr) })
227 }
228 }
229
230 #[inline]
232 pub fn get_front(&self) -> Option<&P::Target> {
233 if self.head.is_null() { None } else { unsafe { Some(&(*self.head)) } }
234 }
235
236 #[inline]
238 pub fn get_back(&self) -> Option<&P::Target> {
239 if self.tail.is_null() { None } else { unsafe { Some(&(*self.tail)) } }
240 }
241
242 #[inline(always)]
244 pub fn is_front(&self, node: &P::Target) -> bool {
245 if self.head.is_null() { false } else { self.head == node as *const P::Target }
246 }
247
248 #[inline(always)]
260 pub fn iter<'a>(&'a self) -> SLinkedListIterator<'a, P, Tag> {
261 SLinkedListIterator { list: self, cur: null() }
262 }
263
264 #[inline(always)]
266 pub fn drain<'a>(&'a mut self) -> SLinkedListDrainer<'a, P, Tag> {
267 SLinkedListDrainer { list: self }
268 }
269}
270
271impl<P, Tag> Drop for SLinkedList<P, Tag>
272where
273 P: Pointer,
274 P::Target: SListItem<Tag>,
275{
276 fn drop(&mut self) {
277 if mem::needs_drop::<P>() {
278 self.drain().for_each(drop);
279 }
280 }
281}
282
283pub struct SLinkedListIterator<'a, P, Tag>
284where
285 P: Pointer,
286 P::Target: SListItem<Tag>,
287{
288 list: &'a SLinkedList<P, Tag>,
289 cur: *const P::Target,
290}
291
292unsafe impl<'a, P, Tag> Send for SLinkedListIterator<'a, P, Tag>
293where
294 P: Pointer,
295 P::Target: SListItem<Tag>,
296{
297}
298
299impl<'a, P, Tag> Iterator for SLinkedListIterator<'a, P, Tag>
300where
301 P: Pointer,
302 P::Target: SListItem<Tag>,
303{
304 type Item = &'a P::Target;
305
306 fn next(&mut self) -> Option<Self::Item> {
307 if self.cur.is_null() {
308 if self.list.head.is_null() {
309 return None;
310 } else {
311 self.cur = self.list.head;
312 }
313 } else {
314 let next = unsafe { (*self.cur).get_node().next };
315 if next.is_null() {
316 return None;
317 } else {
318 self.cur = next;
319 }
320 }
321 unsafe { Some(&(*self.cur)) }
322 }
323}
324
325pub struct SLinkedListDrainer<'a, P, Tag>
326where
327 P: Pointer,
328 P::Target: SListItem<Tag>,
329{
330 list: &'a mut SLinkedList<P, Tag>,
331}
332
333unsafe impl<'a, P, Tag> Send for SLinkedListDrainer<'a, P, Tag>
334where
335 P: Pointer,
336 P::Target: SListItem<Tag>,
337{
338}
339
340impl<'a, P, Tag> Iterator for SLinkedListDrainer<'a, P, Tag>
341where
342 P: Pointer,
343 P::Target: SListItem<Tag>,
344{
345 type Item = P;
346
347 #[inline]
348 fn next(&mut self) -> Option<P> {
349 self.list.pop_front()
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356 use std::cell::UnsafeCell;
357 use std::sync::atomic::{AtomicUsize, Ordering};
358
359 pub struct TestTag;
360
361 #[derive(Debug)]
362 pub struct TestNode {
363 pub value: i64,
364 pub node: UnsafeCell<SListNode<Self, TestTag>>,
365 }
366
367 static ACTIVE_NODE_COUNT: AtomicUsize = AtomicUsize::new(0);
368
369 impl Drop for TestNode {
370 fn drop(&mut self) {
371 ACTIVE_NODE_COUNT.fetch_sub(1, Ordering::SeqCst);
372 }
373 }
374
375 unsafe impl Send for TestNode {}
376
377 unsafe impl SListItem<TestTag> for TestNode {
378 fn get_node(&self) -> &mut SListNode<Self, TestTag> {
379 unsafe { &mut *self.node.get() }
380 }
381 }
382
383 fn new_node(v: i64) -> TestNode {
384 ACTIVE_NODE_COUNT.fetch_add(1, Ordering::SeqCst);
385 TestNode { value: v, node: UnsafeCell::new(SListNode::default()) }
386 }
387
388 #[test]
389 fn test_push_back_pop_front_box() {
390 ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
391 let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
392
393 let node1 = Box::new(new_node(1));
394 l.push_back(node1);
395
396 let node2 = Box::new(new_node(2));
397 l.push_back(node2);
398
399 let node3 = Box::new(new_node(3));
400 l.push_back(node3);
401
402 assert_eq!(3, l.get_length());
403 assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
404
405 let mut iter = l.iter();
407 assert_eq!(iter.next().unwrap().value, 1);
408 assert_eq!(iter.next().unwrap().value, 2);
409 assert_eq!(iter.next().unwrap().value, 3);
410 assert!(iter.next().is_none());
411
412 let n1 = l.pop_front();
414 assert!(n1.is_some());
415 assert_eq!(n1.unwrap().value, 1);
416 assert_eq!(l.get_length(), 2);
417
418 let n2 = l.pop_front();
419 assert!(n2.is_some());
420 assert_eq!(n2.unwrap().value, 2);
421 assert_eq!(l.get_length(), 1);
422
423 let n3 = l.pop_front();
424 assert!(n3.is_some());
425 assert_eq!(n3.unwrap().value, 3);
426 assert_eq!(l.get_length(), 0);
427
428 assert!(l.pop_front().is_none());
429 assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
430 }
431
432 #[test]
433 fn test_drain() {
434 ACTIVE_NODE_COUNT.store(0, Ordering::SeqCst);
435 let mut l = SLinkedList::<Box<TestNode>, TestTag>::new();
436
437 l.push_back(Box::new(new_node(10)));
438 l.push_back(Box::new(new_node(20)));
439 l.push_back(Box::new(new_node(30)));
440
441 assert_eq!(l.get_length(), 3);
442 assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 3);
443
444 {
445 let mut drain = l.drain();
446 assert_eq!(drain.next().unwrap().value, 10);
447 assert_eq!(drain.next().unwrap().value, 20);
448 assert_eq!(drain.next().unwrap().value, 30);
449 assert!(drain.next().is_none());
450 }
451
452 assert_eq!(l.get_length(), 0);
453 assert_eq!(ACTIVE_NODE_COUNT.load(Ordering::SeqCst), 0);
454 }
455}