Skip to main content

collection_selection_confection/list/
mod.rs

1mod cursor;
2mod selection;
3
4pub use cursor::CursorMut;
5pub use selection::SelectionMut;
6
7/// A doubly-linked list.
8///
9/// The name is a lie; it is actually backed by a `Vec`. The interface reflects what would be possible with a real linked list.
10pub struct LinkedList<T> {
11    items: Vec<T>,
12}
13
14impl<T> LinkedList<T> {
15    pub fn new() -> Self {
16        Self { items: Vec::new() }
17    }
18
19    pub fn len(&self) -> usize {
20        self.items.len()
21    }
22
23    pub fn is_empty(&self) -> bool {
24        self.items.is_empty()
25    }
26
27    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + ExactSizeIterator {
28        self.items.iter()
29    }
30
31    pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + ExactSizeIterator {
32        self.items.iter_mut()
33    }
34
35    /// Returns a cursor in the gap before the first element.
36    pub fn cursor_mut_at_start<'a>(&'a mut self) -> CursorMut<'a, T> {
37        CursorMut::new(self, 0)
38    }
39
40    /// Returns a cursor in the gap after the last element.
41    pub fn cursor_mut_at_end<'a>(&'a mut self) -> CursorMut<'a, T> {
42        let index = self.items.len();
43        CursorMut::new(self, index)
44    }
45}
46
47impl<T> Default for LinkedList<T> {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    pub(super) fn list_of(values: &[i32]) -> LinkedList<i32> {
58        let mut list = LinkedList::new();
59        let mut cursor = list.cursor_mut_at_start();
60        for &value in values {
61            cursor.insert_before(value);
62        }
63        list
64    }
65
66    #[test]
67    fn new_empty() {
68        let _ = LinkedList::<i32>::new();
69    }
70
71    #[test]
72    fn default_is_empty() {
73        let list = LinkedList::<i32>::default();
74        assert!(list.is_empty());
75        assert_eq!(list.len(), 0);
76    }
77
78    #[test]
79    fn len_counts_elements() {
80        let list = list_of(&[0, 1, 2]);
81        assert!(!list.is_empty());
82        assert_eq!(list.len(), 3);
83    }
84
85    #[test]
86    fn iter_both_directions() {
87        let list = list_of(&[0, 1, 2]);
88        assert_eq!(list.iter().copied().collect::<Vec<_>>(), [0, 1, 2]);
89        assert_eq!(list.iter().rev().copied().collect::<Vec<_>>(), [2, 1, 0]);
90    }
91
92    #[test]
93    fn iter_mut_modifies_values() {
94        let mut list = list_of(&[0, 1, 2]);
95        for value in list.iter_mut() {
96            *value *= 10;
97        }
98        assert_eq!(list.items, [0, 10, 20]);
99    }
100}