persistent_list/lib.rs
1//-
2// Copyright 2020 Axel Boldt-Christmas
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! # A singly-linked persistent thread safe list
11//!
12//! [`List`] is a basic singly-linked list which uses
13//! structural sharing and [`Arc`] + [clone-on-write](`std::sync::Arc::make_mut`)
14//! mechanics to provide a persistent thread safe list.
15//!
16//! Because of the the structure is only cloned when it needs
17//! too it has relatively little overhead when no structural sharing
18//! occurs.
19//!
20//! ## Immutability
21//!
22//! Purist would probably never call this structure immutable as there many
23//! provided ways to modify the underlying data. However with respect to rusts
24//! strict mutability and borrowing mechanics this crate provides a way to have
25//! a persistent data structure which can share underlying memory / state, while
26//! still appearing immutable to everyone sharing. Even if somewhere some instance
27//! is declared as mutable and starts modifying their view.
28//!
29//! Much inspiration was taken from the [`im`](http://immutable.rs/) crate. It is worth
30//! looking at as it gives both some great motivations for when and why to use these types
31//! of structures as well as providing some excellent implementations of the most important
32//! structural sharing persistent data structures Maps, Sets and Vectors (using [HAMT][hamt],
33//! [RRB trees][rrb-tree] and [B-trees][b-tree])
34//!
35//! # Examples
36//!
37//! ```
38//! # #[macro_use] extern crate persistent_list;
39//! # use persistent_list::{List, cons};
40//! # fn main() {
41//! // list1 and list2 structurally share the data
42//! let list1 = list![1,2,3,4];
43//! let mut list2 = list1.clone();
44//!
45//! // they still share a tail even if one starts
46//! // to be modified.
47//! assert_eq!(list2.pop_front(), Some(1));
48//!
49//! // Every time around the loop they share less and
50//! // less data
51//! for i in &mut list2 {
52//! *i *= 2;
53//! }
54//!
55//! // Until finally no structural sharing is possible
56//! assert_eq!(list1, list![1,2,3,4]); // unchanged
57//! assert_eq!(list2, list![4,6,8]); // modified
58//! # }
59//! ```
60//!
61//! [rrb-tree]: https://infoscience.epfl.ch/record/213452/files/rrbvector.pdf
62//! [hamt]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie
63//! [b-tree]: https://en.wikipedia.org/wiki/B-tree
64//!
65#[cfg(test)]
66extern crate rand;
67
68use std::{
69 borrow::Borrow,
70 fmt,
71 hash::Hash,
72 iter::{FromIterator, IntoIterator, Iterator},
73 mem,
74 sync::Arc,
75};
76
77/// Construct a list from a sequence of elements.
78///
79/// # Examples
80///
81/// ```
82/// #[macro_use] extern crate persistent_list;
83/// # use persistent_list::{List, cons};
84/// # fn main() {
85/// assert_eq!(
86/// list![1, 2, 3],
87/// List::from(vec![1, 2, 3])
88/// );
89///
90/// assert_eq!(
91/// list![1, 2, 3],
92/// cons(1, cons(2, cons(3, List::new())))
93/// );
94/// # }
95/// ```
96#[macro_export]
97macro_rules! list {
98 [] => {List::new()};
99 [$ele:expr] => {crate::cons($ele, List::new())};
100 [$ele:expr, $($tail:expr),*] => {crate::cons($ele, list![$($tail),*])};
101 [$ele:expr, $($tail:expr ,)*] => {crate::cons($ele, list![$($tail),*])};
102}
103
104/// A singly-linked persistent thread safe list.
105#[derive(Clone)]
106pub struct List<E> {
107 size: usize,
108 node: Option<Arc<Node<E>>>,
109}
110
111#[derive(Clone)]
112struct Node<E>(E, Option<Arc<Node<E>>>);
113
114/// An iterator over the elements of a `List`.
115///
116/// This `struct` is created by the [`iter`] method on [`List`]. See its
117/// documentation for more.
118///
119/// [`iter`]: struct.List.html#method.iter
120/// [`List`]: struct.List.html
121#[derive(Clone)]
122pub struct Iter<'a, E> {
123 node: &'a Option<Arc<Node<E>>>,
124 len: usize,
125}
126
127impl<'a, E: 'a + fmt::Debug + Clone> fmt::Debug for Iter<'a, E> {
128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129 f.debug_tuple("Iter")
130 .field(&self.len)
131 .field(&self.node)
132 .finish()
133 }
134}
135
136/// A mutable iterator over the elements of a `List`.
137///
138/// This `struct` is created by the [`iter_mut`] method on [`List`]. See its
139/// documentation for more.
140///
141/// [`iter_mut`]: struct.List.html#method.iter_mut
142/// [`List`]: struct.List.html
143pub struct IterMut<'a, E> {
144 node: Option<&'a mut Arc<Node<E>>>,
145 len: usize,
146}
147
148impl<'a, E: 'a + fmt::Debug + Clone> fmt::Debug for IterMut<'a, E> {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 f.debug_tuple("IterMut")
151 .field(&self.node)
152 .field(&self.len)
153 .finish()
154 }
155}
156
157/// An owning iterator over the elements of a `List`.
158///
159/// This `struct` is created by the [`into_iter`] method on [`List`][`List`]
160/// (provided by the `IntoIterator` trait). See its documentation for more.
161///
162/// [`into_iter`]: struct.List.html#method.into_iter
163/// [`List`]: struct.List.html
164#[derive(Clone)]
165pub struct IntoIter<E> {
166 list: List<E>,
167}
168
169impl<E: fmt::Debug + Clone> fmt::Debug for IntoIter<E> {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 f.debug_tuple("IntoIter").field(&self.list).finish()
172 }
173}
174
175impl<E: Clone> Default for List<E> {
176 /// Creates an empty `List<E>`.
177 #[inline]
178 fn default() -> Self {
179 Self::new()
180 }
181}
182
183/// Construct a `List` with a new element at the front of the
184/// current `List`.
185///
186/// Alternative to using [`List::cons`], but enables
187/// writing list construction from front to back.
188///
189/// ```
190/// # #[macro_use] extern crate persistent_list;
191/// # use persistent_list::{List, cons};
192/// # fn main() {
193/// // Enables this:
194/// let list = cons(1, cons(2, List::new()));
195///
196/// // Instead of
197/// let list = List::new().cons(2).cons(1);
198///
199/// // Or
200/// let mut list = List::new();
201/// list.push_front(2);
202/// list.push_front(1);
203///
204/// // Which all result in the equivalent
205/// let list = list![1, 2];
206/// # }
207/// ```
208///
209/// # Examples
210///
211/// ```
212/// #[macro_use] extern crate persistent_list;
213/// # use persistent_list::{List, cons};
214/// # fn main() {
215///
216/// assert_eq!(
217/// cons(1, cons(2, cons(3, List::new()))),
218/// list![1, 2, 3]
219/// );
220/// # }
221/// ```
222#[inline]
223pub fn cons<E: Clone, T: Borrow<List<E>>>(first: E, rest: T) -> List<E> {
224 let mut list: List<E> = rest.borrow().clone().into();
225 // List {
226 // size: list.size + 1,
227 // node: Some(Arc::new(Node(first, list.node))),
228 // }
229 list.push_front(first);
230 list
231}
232
233impl<E: Clone> List<E> {
234 /// Creates an empty `List`.
235 ///
236 /// # Examples
237 ///
238 /// ```
239 /// use persistent_list::List;
240 ///
241 /// let list: List<u32> = List::new();
242 /// ```
243 #[inline]
244 pub fn new() -> Self {
245 Self {
246 size: 0,
247 node: None,
248 }
249 }
250
251 /// Moves all elements from `other` to the end of the list.
252 ///
253 /// This reuses all the nodes from `other` and moves them into `self`. After
254 /// this operation, `other` becomes empty.
255 ///
256 /// This operation should compute in O(`self.len()`) time and O(`self.len()`)* memory.
257 /// The memory usage depends on how much of the `self` List is shared. Nodes are taken
258 /// using clone-on-write mechanics, only cloning any shared tail part.
259 ///
260 /// # Examples
261 ///
262 /// ```
263 /// use persistent_list::List;
264 ///
265 /// let mut list1 = List::new();
266 /// list1.push_front('a');
267 ///
268 /// let mut list2 = List::new();
269 /// list2.push_front('c');
270 /// list2.push_front('b');
271 ///
272 /// list1.append(&mut list2);
273 ///
274 /// let mut iter = list1.iter();
275 /// assert_eq!(iter.next(), Some(&'a'));
276 /// assert_eq!(iter.next(), Some(&'b'));
277 /// assert_eq!(iter.next(), Some(&'c'));
278 /// assert!(iter.next().is_none());
279 ///
280 /// assert!(list2.is_empty());
281 /// ```
282 pub fn append(&mut self, other: &mut Self) {
283 if other.node.is_none() {
284 return;
285 }
286 let mut node = &mut self.node;
287 while let Some(next) = node {
288 node = &mut Arc::make_mut(next).1;
289 }
290 mem::swap(node, &mut other.node);
291 self.size += other.size;
292 other.size = 0;
293 }
294
295 /// Provides a forward iterator.
296 ///
297 /// # Examples
298 ///
299 /// ```
300 /// use persistent_list::List;
301 ///
302 /// let mut list: List<u32> = List::new();
303 ///
304 /// list.push_front(2);
305 /// list.push_front(1);
306 /// list.push_front(0);
307 ///
308 /// let mut iter = list.iter();
309 /// assert_eq!(iter.next(), Some(&0));
310 /// assert_eq!(iter.next(), Some(&1));
311 /// assert_eq!(iter.next(), Some(&2));
312 /// assert_eq!(iter.next(), None);
313 /// ```
314 #[inline]
315 pub fn iter(&self) -> Iter<'_, E> {
316 Iter {
317 node: &self.node,
318 len: self.size,
319 }
320 }
321
322 /// Provides a forward iterator with mutable references.
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// use persistent_list::List;
328 ///
329 /// let mut list: List<u32> = List::new();
330 ///
331 /// list.push_front(2);
332 /// list.push_front(1);
333 /// list.push_front(0);
334 ///
335 /// for element in list.iter_mut() {
336 /// *element += 10;
337 /// }
338 ///
339 /// let mut iter = list.iter();
340 /// assert_eq!(iter.next(), Some(&10));
341 /// assert_eq!(iter.next(), Some(&11));
342 /// assert_eq!(iter.next(), Some(&12));
343 /// assert_eq!(iter.next(), None);
344 /// ```
345 #[inline]
346 pub fn iter_mut(&mut self) -> IterMut<'_, E> {
347 IterMut {
348 node: self.node.as_mut(),
349 len: self.size,
350 }
351 }
352
353 /// Returns `true` if the `List` is empty.
354 ///
355 /// This operation should compute in O(1) time.
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// use persistent_list::List;
361 ///
362 /// let mut list = List::new();
363 /// assert!(list.is_empty());
364 ///
365 /// list.push_front("foo");
366 /// assert!(!list.is_empty());
367 /// ```
368 #[inline]
369 pub fn is_empty(&self) -> bool {
370 match &self.node {
371 Some(_) => false,
372 None => true,
373 }
374 }
375
376 /// Returns the length of the `List`.
377 ///
378 /// This operation should compute in O(1) time.
379 ///
380 /// # Examples
381 ///
382 /// ```
383 /// use persistent_list::List;
384 ///
385 /// let mut list = List::new();
386 ///
387 /// list.push_front(2);
388 /// assert_eq!(list.len(), 1);
389 ///
390 /// list.push_front(1);
391 /// assert_eq!(list.len(), 2);
392 ///
393 /// list.push_front(3);
394 /// assert_eq!(list.len(), 3);
395 /// ```
396 #[inline]
397 pub fn len(&self) -> usize {
398 self.size
399 }
400 /// Construct a `List` with a single value.
401 ///
402 /// # Examples
403 ///
404 /// ```
405 /// use persistent_list::List;
406 ///
407 /// let list = List::unit(1);
408 /// assert_eq!(1, list.len());
409 /// assert_eq!(
410 /// list.front(),
411 /// Some(&1)
412 /// );
413 /// ```
414 #[inline]
415 pub fn unit(first: E) -> Self {
416 crate::cons(first, Self::new())
417 }
418
419 /// Removes all elements from the `List`.
420 ///
421 /// This operation should compute in O(n) time.
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// use persistent_list::List;
427 ///
428 /// let mut list = List::new();
429 ///
430 /// list.push_front(2);
431 /// list.push_front(1);
432 /// assert_eq!(list.len(), 2);
433 /// assert_eq!(list.front(), Some(&1));
434 ///
435 /// list.clear();
436 /// assert_eq!(list.len(), 0);
437 /// assert_eq!(list.front(), None);
438 /// ```
439 #[inline]
440 pub fn clear(&mut self) {
441 *self = Self::new();
442 }
443
444 /// Construct a `List` with a new element at the front of the
445 /// current `List`.
446 ///
447 /// See [`crate::cons`] for alternative version.
448 #[inline]
449 pub fn cons(&self, first: E) -> Self {
450 Self {
451 size: self.size + 1,
452 node: Some(Arc::new(Node(first, self.node.clone()))),
453 }
454 }
455
456 /// Get the head and the tail of a list.
457 ///
458 /// This function performs both the `head` function and
459 /// the `tail` function in one go, returning a tuple
460 /// of the head and the tail, or `None` if the list is
461 /// empty.
462 ///
463 /// # Examples
464 ///
465 /// This can be useful when pattern matching your way through
466 /// a list:
467 ///
468 /// ```
469 /// # #[macro_use] extern crate persistent_list;
470 /// use persistent_list::{List, cons};
471 /// use std::fmt::Debug;
472 ///
473 /// fn walk_through_list<E: Clone>(list: &List<E>) where E: Debug {
474 /// match list.uncons() {
475 /// None => (),
476 /// Some((ref head, ref tail)) => {
477 /// print!("{:?}", head);
478 /// walk_through_list(tail)
479 /// }
480 /// }
481 /// }
482 /// # fn main() {
483 /// # }
484 /// ```
485 #[inline]
486 pub fn uncons(&self) -> Option<(&E, Self)> {
487 self.head().and_then(|h| self.tail().map(|t| (h, t)))
488 }
489
490 /// Returns `true` if the `List` contains an element equal to the
491 /// given value.
492 ///
493 /// # Examples
494 ///
495 /// ```
496 /// use persistent_list::List;
497 ///
498 /// let mut list: List<u32> = List::new();
499 ///
500 /// list.push_front(2);
501 /// list.push_front(1);
502 /// list.push_front(0);
503 ///
504 /// assert_eq!(list.contains(&0), true);
505 /// assert_eq!(list.contains(&10), false);
506 /// ```
507 pub fn contains(&self, x: &E) -> bool
508 where
509 E: PartialEq<E>,
510 {
511 self.iter().any(|e| e == x)
512 }
513
514 /// Provides a reference to the front element, or `None` if the `List` is
515 /// empty.
516 ///
517 /// # Examples
518 ///
519 /// ```
520 /// use persistent_list::List;
521 ///
522 /// let mut list = List::new();
523 /// assert_eq!(list.front(), None);
524 ///
525 /// list.push_front(1);
526 /// assert_eq!(list.front(), Some(&1));
527 /// ```
528 #[inline]
529 pub fn front(&self) -> Option<&E> {
530 match &self.node {
531 Some(node) => Some(&node.0),
532 None => None,
533 }
534 }
535
536 /// Provides a mutable reference to the front element, or `None` if the list
537 /// is empty.
538 ///
539 /// # Examples
540 ///
541 /// ```
542 /// use persistent_list::List;
543 ///
544 /// let mut list = List::new();
545 /// assert_eq!(list.front(), None);
546 ///
547 /// list.push_front(1);
548 /// assert_eq!(list.front(), Some(&1));
549 ///
550 /// match list.front_mut() {
551 /// None => {},
552 /// Some(x) => *x = 5,
553 /// }
554 /// assert_eq!(list.front(), Some(&5));
555 /// ```
556 #[inline]
557 pub fn front_mut(&mut self) -> Option<&mut E> {
558 self.node.as_mut().map(|node| &mut Arc::make_mut(node).0)
559 }
560
561 /// Adds an element first in the list.
562 ///
563 /// This operation should compute in O(1) time.
564 ///
565 /// # Examples
566 ///
567 /// ```
568 /// use persistent_list::List;
569 ///
570 /// let mut list = List::new();
571 ///
572 /// list.push_front(2);
573 /// assert_eq!(list.front().unwrap(), &2);
574 ///
575 /// list.push_front(1);
576 /// assert_eq!(list.front().unwrap(), &1);
577 /// ```
578 pub fn push_front(&mut self, element: E) {
579 let node = self.node.take();
580 self.node = Some(Arc::new(Node(element, node)));
581 self.size += 1;
582 }
583
584 /// Removes the first element and returns it, or `None` if the list is
585 /// empty.
586 ///
587 /// This operation should compute in O(1) time.
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// use persistent_list::List;
593 ///
594 /// let mut list = List::new();
595 /// assert_eq!(list.pop_front(), None);
596 ///
597 /// list.push_front(1);
598 /// list.push_front(3);
599 /// assert_eq!(list.pop_front(), Some(3));
600 /// assert_eq!(list.pop_front(), Some(1));
601 /// assert_eq!(list.pop_front(), None);
602 /// ```
603 pub fn pop_front(&mut self) -> Option<E> {
604 match self.node.take() {
605 Some(node) => {
606 self.size -= 1;
607 match Arc::try_unwrap(node) {
608 Ok(node) => {
609 self.node = node.1;
610 Some(node.0)
611 }
612 Err(node) => {
613 self.node = node.1.clone();
614 Some(node.0.clone())
615 }
616 }
617 }
618 None => None,
619 }
620 }
621
622 /// Splits the list into two at the given index. Returns everything after the given index,
623 /// including the index.
624 ///
625 /// This operation should compute in O(at) time.
626 ///
627 /// # Panics
628 ///
629 /// Panics if `at > len`.
630 ///
631 /// # Examples
632 ///
633 /// ```
634 /// use persistent_list::List;
635 ///
636 /// let mut list = List::new();
637 ///
638 /// list.push_front(1);
639 /// list.push_front(2);
640 /// list.push_front(3);
641 ///
642 /// let mut splitted = list.split_off(2);
643 ///
644 /// assert_eq!(splitted.pop_front(), Some(1));
645 /// assert_eq!(splitted.pop_front(), None);
646 ///
647 /// assert_eq!(list.pop_front(), Some(3));
648 /// assert_eq!(list.pop_front(), Some(2));
649 /// assert_eq!(list.pop_front(), None);
650 /// ```
651 pub fn split_off(&mut self, at: usize) -> Self {
652 let len = self.len();
653 assert!(at <= len, "Cannot split off at a nonexistent index");
654 if at == 0 {
655 return mem::replace(self, Self::new());
656 } else if at == len {
657 return Self::new();
658 }
659
660 let mut iter = self.iter_mut();
661 for _ in 0..at - 1 {
662 iter.next();
663 }
664 match iter.node.take() {
665 Some(node) => {
666 let node = Arc::make_mut(node);
667 match node.1.take() {
668 Some(node) => {
669 self.size = at;
670 List {
671 size: len - at,
672 node: Some(node),
673 }
674 }
675 None => unreachable!(),
676 }
677 }
678 None => unreachable!(),
679 }
680 }
681 /// Split a `List` at a given index.
682 ///
683 /// Split a `List` at a given index, consuming the `List` and
684 /// returning a pair of the left hand side and the right hand side
685 /// of the split.
686 ///
687 /// This operation should compute in O(at) time.
688 ///
689 /// # Panics
690 ///
691 /// Panics if `at > len`.
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// # #[macro_use] extern crate persistent_list;
697 /// # use persistent_list::{List,cons};
698 /// # fn main() {
699 /// let mut list = list![1, 2, 3, 7, 8, 9];
700 /// let (left, right) = list.split_at(3);
701 /// assert_eq!(list![1, 2, 3], left);
702 /// assert_eq!(list![7, 8, 9], right);
703 /// # }
704 /// ```
705 pub fn split_at(mut self, at: usize) -> (Self, Self) {
706 let right = self.split_off(at);
707 (self, right)
708 }
709
710 /// Reverses the list
711 ///
712 /// This operation should compute in O(n) time and O(n)* memory allocations, O(1) if
713 /// this list does not share any node (tail) with another list.
714 ///
715 /// The memory usage depends on how much of the `self` List is shared. Nodes are taken
716 /// using clone-on-write mechanics, only cloning any shared tail part.
717 ///
718 /// # Examples
719 ///
720 /// ```
721 /// use persistent_list::List;
722 ///
723 /// let mut list1 = List::from(vec![1, 2, 3, 4]);
724 /// list1.reverse();
725 /// assert_eq!(list1, List::from(vec![4, 3, 2, 1]));
726 ///
727 /// let list2 = list1.clone();
728 /// list1.reverse();
729 /// assert_eq!(list2, List::from(vec![4, 3, 2, 1]));
730 ///
731 /// list1.reverse();
732 /// assert_eq!(list1, list2);
733 /// ```
734 #[inline]
735 pub fn reverse(&mut self) {
736 if self.node.is_none() {
737 return;
738 }
739 // New list new.node == None
740 let mut new = Self::new();
741 // After take head from self
742 // node == head of old list
743 // and self.node == None
744 let mut node = self.node.take();
745 while let Some(_) = node {
746 // current head of the old list tail was not the end
747 // swap head of the old list tail with the head of our new list
748 mem::swap(&mut new.node, &mut node);
749 match &mut new.node {
750 // Get inner reference
751 Some(new_node) => {
752 // new_node is the head of the old list tail which may be shared.
753 // So we clone-on-write and get a non shared ref mut into our new
754 // head location but with the old list tail data.
755 let new_node = Arc::make_mut(new_node);
756 // swap the next item in the old list tail and or new tail.
757 mem::swap(&mut new_node.1, &mut node);
758 // The local variable node now has the head of the old list tail
759 // new_node == new.node now contains the head of the previous
760 // old list tail and new.node.1 == old new_node.
761 }
762 None => unreachable!(),
763 }
764 }
765 new.size = self.size;
766 *self = new;
767 }
768
769 /// Get the rest of the `List` after any potential
770 /// front element has been removed.
771 ///
772 /// # Examples
773 ///
774 /// ```
775 /// use persistent_list::List;
776 ///
777 /// let mut list = List::new();
778 /// assert_eq!(list.rest(), List::new());
779 ///
780 /// list.push_front(2);
781 /// assert_eq!(list.rest(), List::new());
782 ///
783 /// list.push_front(1);
784 /// assert_eq!(list.rest(), List::unit(2));
785 /// ```
786 #[inline]
787 pub fn rest(&self) -> Self {
788 match &self.node {
789 None => Self::new(),
790 Some(node) => Self {
791 size: self.size - 1,
792 node: node.1.clone(),
793 },
794 }
795 }
796
797 /// Get the first element of a `List`.
798 ///
799 /// If the `List` is empty, `None` is returned.
800 ///
801 /// This is an alias for the [`front`][front] method.
802 ///
803 /// [front]: #method.front
804 #[inline]
805 #[must_use]
806 pub fn head(&self) -> Option<&E> {
807 self.front()
808 }
809
810 /// Get the tail of a `List`.
811 ///
812 /// The tail means all elements in the `List` after the
813 /// first item. If the list only has one element, the
814 /// result is an empty list. If the list is empty, the
815 /// result is `None`.
816 ///
817 /// # Examples
818 ///
819 /// ```
820 /// use persistent_list::List;
821 ///
822 /// let mut list = List::new();
823 /// assert_eq!(list.tail(), None);
824 ///
825 /// list.push_front(2);
826 /// assert_eq!(list.tail(), Some(List::new()));
827 ///
828 /// list.push_front(1);
829 /// assert_eq!(list.tail(), Some(List::unit(2)));
830 /// ```
831 #[inline]
832 pub fn tail(&self) -> Option<Self> {
833 match &self.node {
834 None => None,
835 Some(node) => Some(Self {
836 size: self.size - 1,
837 node: node.1.clone(),
838 }),
839 }
840 }
841
842 pub fn skip(&self, count: usize) -> Self {
843 if count > self.size {
844 Self::new()
845 } else {
846 let mut rest = &self.node;
847 for _ in 0..count {
848 match rest {
849 Some(node) => rest = &node.1,
850 None => unreachable!(),
851 }
852 }
853 Self {
854 size: self.size - count,
855 node: rest.clone(),
856 }
857 }
858 }
859}
860
861impl<E: fmt::Debug + Clone> fmt::Debug for List<E> {
862 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
863 f.debug_list().entries(self).finish()
864 }
865}
866impl<E: fmt::Debug + Clone> fmt::Debug for Node<E> {
867 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
868 f.debug_tuple("ListNode")
869 .field(&self.0)
870 .field(&self.1)
871 .finish()
872 }
873}
874
875impl<E: Clone> FromIterator<E> for List<E> {
876 #[inline]
877 fn from_iter<I: IntoIterator<Item = E>>(iterator: I) -> Self {
878 iterator
879 .into_iter()
880 .fold(Self::new(), |list, element| crate::cons(element, list))
881 }
882}
883
884impl<'s, 'a, E, OE> From<&'s List<&'a E>> for List<OE>
885where
886 E: ToOwned<Owned = OE>,
887 OE: Borrow<E> + Clone,
888{
889 fn from(vec: &List<&E>) -> Self {
890 let mut list: Self = vec.iter().map(|a| (*a).to_owned()).collect();
891 list.reverse();
892 list
893 }
894}
895
896impl<'a, E: Clone> From<&'a [E]> for List<E> {
897 fn from(slice: &[E]) -> Self {
898 slice.iter().rev().cloned().collect()
899 }
900}
901
902impl<E: Clone> From<Vec<E>> for List<E> {
903 /// Create a `List` from a [`std::vec::Vec`][vec].
904 ///
905 /// Time: O(n)
906 ///
907 /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
908 fn from(vec: Vec<E>) -> Self {
909 vec.into_iter().rev().collect()
910 }
911}
912
913impl<'a, E: Clone> From<&'a Vec<E>> for List<E> {
914 /// Create a vector from a [`std::vec::Vec`][vec].
915 ///
916 /// Time: O(n)
917 ///
918 /// [vec]: https://doc.rust-lang.org/std/vec/struct.Vec.html
919 fn from(vec: &Vec<E>) -> Self {
920 vec.iter().rev().cloned().collect()
921 }
922}
923
924impl<E: Clone> IntoIterator for List<E> {
925 type Item = E;
926 type IntoIter = IntoIter<E>;
927
928 #[inline]
929 fn into_iter(self) -> Self::IntoIter {
930 IntoIter { list: self }
931 }
932}
933
934impl<'a, E: Clone> IntoIterator for &'a List<E> {
935 type Item = &'a E;
936 type IntoIter = Iter<'a, E>;
937
938 #[inline]
939 fn into_iter(self) -> Self::IntoIter {
940 self.iter()
941 }
942}
943
944impl<'a, E: Clone> IntoIterator for &'a mut List<E> {
945 type Item = &'a mut E;
946 type IntoIter = IterMut<'a, E>;
947
948 #[inline]
949 fn into_iter(self) -> Self::IntoIter {
950 self.iter_mut()
951 }
952}
953
954impl<E: Clone> Iterator for IntoIter<E> {
955 type Item = E;
956
957 #[inline]
958 fn next(&mut self) -> Option<Self::Item> {
959 self.list.pop_front()
960 }
961
962 #[inline]
963 fn size_hint(&self) -> (usize, Option<usize>) {
964 (self.list.len(), Some(self.list.len()))
965 }
966}
967
968impl<E: Clone> ExactSizeIterator for IntoIter<E> {}
969
970impl<'a, E> Iterator for Iter<'a, E> {
971 type Item = &'a E;
972
973 #[inline]
974 fn next(&mut self) -> Option<Self::Item> {
975 match &self.node {
976 Some(node) => {
977 self.len -= 1;
978 self.node = &node.1;
979 Some(&node.0)
980 }
981 None => None,
982 }
983 }
984
985 fn size_hint(&self) -> (usize, Option<usize>) {
986 (self.len, Some(self.len))
987 }
988}
989
990impl<'a, E> ExactSizeIterator for Iter<'a, E> {}
991
992impl<'a, E: Clone> Iterator for IterMut<'a, E> {
993 type Item = &'a mut E;
994
995 #[inline]
996 fn next(&mut self) -> Option<Self::Item> {
997 match self.node.take() {
998 Some(node) => {
999 let node = Arc::make_mut(node);
1000 self.len -= 1;
1001 self.node = node.1.as_mut();
1002 Some(&mut node.0)
1003 }
1004 None => None,
1005 }
1006 }
1007
1008 #[inline]
1009 fn size_hint(&self) -> (usize, Option<usize>) {
1010 (self.len, Some(self.len))
1011 }
1012}
1013
1014impl<'a, E: Clone> ExactSizeIterator for IterMut<'a, E> {}
1015
1016impl<E: Hash + Clone> Hash for List<E> {
1017 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1018 for i in self {
1019 i.hash(state);
1020 }
1021 // Not hashing size for consistency with im::Vector
1022 // self.len().hash(state);
1023 }
1024}
1025
1026impl<E> Drop for List<E> {
1027 fn drop(&mut self) {
1028 let mut node = self.node.take();
1029 while let Some(next) = node {
1030 match Arc::try_unwrap(next) {
1031 Ok(mut next) => {
1032 node = next.1.take();
1033 }
1034 Err(_) => {
1035 break;
1036 }
1037 }
1038 }
1039 }
1040}
1041
1042impl<E: PartialEq + Clone> PartialEq for List<E> {
1043 fn eq(&self, other: &Self) -> bool {
1044 self.len() == other.len() && self.iter().eq(other)
1045 }
1046
1047 fn ne(&self, other: &Self) -> bool {
1048 self.len() != other.len() || self.iter().ne(other)
1049 }
1050}
1051
1052impl<T: Eq + Clone> Eq for List<T> {}
1053
1054#[cfg(test)]
1055mod tests {
1056
1057 use super::*;
1058 #[test]
1059 fn list_macro() {
1060 assert_eq!(list![1, 2, 3], cons(1, cons(2, cons(3, List::new()))));
1061 assert_eq!(list![1, 2, 3,], cons(1, cons(2, cons(3, List::new()))));
1062 assert_eq!(List::<i32>::new(), list![]);
1063 }
1064
1065 #[test]
1066 fn list_iterator() {
1067 let list1 = list![1, 2, 3, 4];
1068 let list2: List<String> = list1
1069 .into_iter()
1070 .filter(|&x| x > 3)
1071 .map(|x| x.to_string())
1072 .collect();
1073
1074 assert_eq!(list2, list![String::from("4")]);
1075
1076 let list1 = list![1, 2, 3, 4];
1077 let list2: List<_> = list1
1078 .iter()
1079 // Explicit Deref instead of cloned()
1080 .map(|i| *i)
1081 .collect();
1082 assert_eq!(list![4, 3, 2, 1], list2);
1083
1084 let mut list1 = list![1, 2, 3, 4];
1085 for i in &mut list1 {
1086 *i *= 2;
1087 }
1088 assert_eq!(list1, list![2, 4, 6, 8]);
1089
1090 let mut list1 = list![1, 2, 3, 4];
1091 let list2 = list1.clone();
1092 for i in &mut list1 {
1093 *i *= 2;
1094 }
1095 assert_eq!(list1, list![2, 4, 6, 8]);
1096 assert_eq!(list2, list![1, 2, 3, 4]);
1097 }
1098
1099 #[test]
1100 fn list_front() {
1101 let list1 = list![1];
1102 let list2 = list![1, 2];
1103 assert_eq!(list1.front(), list2.front());
1104
1105 let list1 = list![1];
1106 let list2 = list![2, 1];
1107 assert!(list1.front() != list2.front());
1108
1109 let list: List<i32> = list![];
1110 assert_eq!(list.front(), None);
1111 }
1112
1113 #[test]
1114 fn list_rest() {
1115 let list1 = list![1, 2, 3];
1116 assert_eq!(list1.rest(), list![2, 3]);
1117
1118 let list1: List<i32> = list![];
1119 assert_eq!(list1.rest(), list![]);
1120
1121 let list1 = list![1, 2];
1122 let list2 = list![1, 2, 3];
1123 assert!(list1.rest() != list2.rest());
1124
1125 let list1: List<i32> = list![];
1126 let list2 = list![1];
1127 assert!(list1.rest() == list2.rest());
1128 }
1129
1130 #[test]
1131 fn list_length() {
1132 let list1 = list![1, 2, 3];
1133 assert_eq!(list1.len(), 3);
1134
1135 let list1: List<i32> = list![];
1136 assert_eq!(list1.len(), 0);
1137
1138 let list1 = list![1, 2];
1139 let list2 = list![1, 2, 3];
1140 assert!(list1.len() != list2.len());
1141 }
1142
1143 #[test]
1144 fn list_skip() {
1145 let list1 = list![1, 2, 3];
1146 assert_eq!(list1, list1.skip(0));
1147
1148 let list2 = list![2, 3];
1149 assert_eq!(list2, list1.skip(1));
1150
1151 let list2 = list![3];
1152 assert_eq!(list2, list1.skip(2));
1153
1154 let list2: List<i32> = list![];
1155 assert_eq!(list2, list1.skip(3));
1156 }
1157
1158 #[test]
1159 fn list_append() {
1160 let mut list1 = list![1, 2, 3];
1161 let mut list2 = list![4, 5];
1162
1163 list1.append(&mut list2);
1164 assert_eq!(list1, list![1, 2, 3, 4, 5]);
1165 assert_eq!(list2, List::new());
1166
1167 let mut list1 = list![1, 2, 3];
1168 let mut list2 = list![4, 5];
1169 let list3 = list1.clone();
1170 let list4 = list2.rest();
1171
1172 list1.append(&mut list2);
1173 assert_eq!(list1, list![1, 2, 3, 4, 5]);
1174 assert_eq!(list2, List::new());
1175 assert_eq!(list3, list![1, 2, 3]);
1176 assert_eq!(list4, list![5]);
1177 }
1178
1179 #[test]
1180 fn list_thread() {
1181 use crate::rand::RngCore;
1182 use std::collections::VecDeque;
1183 use std::thread;
1184 let size = 10000;
1185 let list = List::from_iter(0..size);
1186 let vec: VecDeque<_> = list.iter().cloned().collect();
1187
1188 let mut threads = Vec::new();
1189
1190 for i in 0..24 {
1191 let list = list.clone();
1192 let vec = vec.clone();
1193 threads.push(thread::spawn(move || {
1194 let mut rng = rand::thread_rng();
1195 let mut list = list;
1196 let mut vec = vec;
1197 assert!(list.iter().eq(vec.iter()));
1198 match i {
1199 i if i < 6 => {
1200 for i in 0..size {
1201 if rng.next_u32() % 2 == 0 {
1202 list.pop_front();
1203 vec.pop_front();
1204 } else {
1205 list.push_front(i);
1206 vec.push_front(i);
1207 }
1208 }
1209 }
1210 i if i < 12 => {
1211 for i in 0..size {
1212 if i < size / 2 {
1213 list.pop_front();
1214 vec.pop_front();
1215 } else {
1216 list.push_front(i);
1217 vec.push_front(i);
1218 }
1219 }
1220 }
1221 i if i < 18 => {
1222 for (i1, i2) in list.iter_mut().zip(vec.iter_mut()) {
1223 *i1 *= 2;
1224 *i2 *= 2;
1225 }
1226 }
1227 _ => {
1228 for _ in 0..(size / 10) {
1229 let at = rng.next_u32() % size;
1230 let (left, mut right) = list.split_at(at as usize);
1231 list = left;
1232 list.append(&mut right);
1233 }
1234 }
1235 }
1236 assert!(list.iter().eq(vec.iter()));
1237 println!("Thread {} done!", i);
1238 }))
1239 }
1240 assert!(list.iter().eq(vec.iter()));
1241 while let Some(handle) = threads.pop() {
1242 handle.join().expect("Thread panicked.")
1243 }
1244 assert!(list.iter().eq(vec.iter()));
1245 }
1246 #[test]
1247 fn list_split_append() {
1248 // Recursion test. Fails unless we specify a non recursive Drop
1249 use crate::rand::RngCore;
1250 use std::collections::VecDeque;
1251 let size = 10000;
1252 let list = List::from_iter(0..size);
1253 let vec: VecDeque<_> = list.iter().cloned().collect();
1254
1255 let mut rng = rand::thread_rng();
1256 let mut list = list;
1257
1258 for _ in 0..(size / 10) {
1259 let at = rng.next_u32() % size;
1260 let (left, mut right) = list.split_at(at as usize);
1261 list = left;
1262 list.append(&mut right);
1263 assert!(list.iter().eq(vec.iter()));
1264 }
1265 }
1266}