Skip to main content

array_linked_list/
lib.rs

1#![deny(missing_docs)]
2
3/*!
4The `ArrayLinkedList` data structure combines the benefit of an array and a linked list.
5
6Every supported operation, which does not (re-)allocate the array, is done in *O*(1):
7
8* inserting elements at the front and back
9* popping element at the front or back
10* getting the element count
11* removing elements at an arbitrary index
12* inserting elements at an arbitrary index
13* replacing elements at an arbitrary index
14
15It's stored like an array, but contains some additional information.
16
17You would typically use it, where you need to be able to do multiple of the following tasks efficiently:
18
19* accessing single elements by index
20* adding and removing elements without changing order or indices
21* sorting elements without changing indices or moving the content around.
22
23# Order and indexing
24
25You might also use it as a more convenient version of a `Vec<Option<T>>`.
26When iterating over it, only the elements, which are `Some` are given to the user.
27And even the checks for `Some` are optimized away.
28So when it's likely, that most of the options of a large array are `None`, this might be a huge performance improvement.
29
30Another advantage over a `LinkedList` is the cache locality.
31Everything is laid out in a contiguous region of memory.
32Compared to a `Vec` on the other hand, it might be bad.
33The iteration does not necessarily take place in the same order.
34That's mostly a problem for large arrays.
35The iterator would jump back and forth in the array.
36
37In order to understand this type, it's necessary to know about the iteration order.
38There is a logical order, which is used by the iterators, or when doing anything with the first and last elements.
39You can think of it as the order of a linked list, which is just packed into an array here.
40And then there is indexing, which has nothing to do with the order of the linked list.
41The indices just return the array elements.
42
43## Index Example
44
45So when adding an element to the linked array without specifying the index, you get the index, it was put to, as a result.
46The results are always added to the array in order, so the indices increase, no matter if you add the indices to the front or to the back:
47
48```
49use array_linked_list::ArrayLinkedList;
50
51let mut array = ArrayLinkedList::new();
52
53assert_eq!(array.push_front(1), 0);
54assert_eq!(array.push_back(2), 1);
55assert_eq!(array.push_front(3), 2);
56assert_eq!(array.push_front(4), 3);
57assert_eq!(array.push_back(5), 4);
58```
59
60## Order example
61
62When you just apped elements from the front or back, the indices even correlate to the order:
63
64```
65use array_linked_list::ArrayLinkedList;
66
67let mut array = ArrayLinkedList::new();
68
69array.push_front(1);
70array.push_front(2);
71array.push_front(3);
72
73for (i, element) in array.iter().rev().enumerate() {
74    assert_eq!(*element, array[i].unwrap());
75}
76```
77
78```
79use array_linked_list::ArrayLinkedList;
80
81let mut array = ArrayLinkedList::new();
82
83array.push_back(1);
84array.push_back(2);
85array.push_back(3);
86
87for (i, element) in array.iter().enumerate() {
88    assert_eq!(*element, array[i].unwrap());
89}
90```
91
92## Iteration over unsorted lists
93
94In realistic cases, you need to store the indices somewhere else, if you need them.
95Alternatively, you can also use
96
97```
98use array_linked_list::ArrayLinkedList;
99
100let mut array = ArrayLinkedList::new();
101
102array.push_back(1);
103array.push_front(2);
104array.push_front(3);
105array.push_back(4);
106array.push_front(5);
107
108for (index, element) in array.indexed().rev() {
109    assert_eq!(*element, array[index].unwrap());
110}
111```
112
113## Conclusion
114
115Just remember, that indices and order are two different things, which don't correlate, and you should be safe.
116
117**/
118
119use std::{
120    mem,
121    ops::{Index, IndexMut},
122};
123
124mod id {
125    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
126    pub struct Id(usize);
127
128    impl Default for Id {
129        fn default() -> Self {
130            Self(usize::MAX)
131        }
132    }
133
134    impl Id {
135        #[inline(always)]
136        pub fn new(i: usize) -> Self {
137            Self(i)
138        }
139
140        #[inline(always)]
141        pub fn is_empty(self) -> bool {
142            self.0 == usize::MAX
143        }
144
145        #[inline(always)]
146        pub fn index(self) -> Option<usize> {
147            if self.is_empty() { None } else { Some(self.0) }
148        }
149
150        #[inline(always)]
151        pub fn valid_index(self) -> usize {
152            self.0
153        }
154    }
155}
156
157use id::Id;
158
159#[derive(Copy, Clone, Debug)]
160struct LinkedListNode<T> {
161    next_index: Id,
162    prev_index: Id,
163    data: Option<T>,
164}
165
166impl<T> LinkedListNode<T> {
167    fn new(prev_index: Id, next_index: Id, data: T) -> Self {
168        Self {
169            next_index,
170            prev_index,
171            data: Some(data),
172        }
173    }
174
175    fn front(first_index: Id, data: T) -> Self {
176        Self {
177            next_index: first_index,
178            prev_index: Id::default(),
179            data: Some(data),
180        }
181    }
182
183    fn back(last_index: Id, data: T) -> Self {
184        Self {
185            next_index: Id::default(),
186            prev_index: last_index,
187            data: Some(data),
188        }
189    }
190
191    fn deleted(free_index: Id) -> Self {
192        Self {
193            next_index: free_index,
194            prev_index: Id::default(),
195            data: None,
196        }
197    }
198}
199
200/// The `ArrayLinkedList` type, which combines the advantages of dynamic arrays and linked lists.
201#[derive(Clone, Debug, Default)]
202pub struct ArrayLinkedList<T> {
203    count: usize,
204    first_index: Id,
205    last_index: Id,
206    free_index: Id,
207    end_index: Id,
208    elements: Vec<LinkedListNode<T>>,
209}
210
211impl<T> ArrayLinkedList<T> {
212    /// Constructs a new, empty `ArrayLinkedList`.
213    ///
214    /// The linked array will not allocate until elements are pushed onto it.
215    pub fn new() -> Self {
216        Self {
217            count: 0,
218            first_index: Id::default(),
219            last_index: Id::default(),
220            free_index: Id::default(),
221            end_index: Id::default(),
222            elements: Vec::new(),
223        }
224    }
225
226    #[inline]
227    fn fill_elements(&mut self, capacity: usize) {
228        if capacity == 0 {
229            return;
230        }
231        for i in 1..capacity {
232            self.elements.push(LinkedListNode::deleted(Id::new(i)))
233        }
234        self.elements.push(LinkedListNode::deleted(Id::default()));
235
236        self.free_index = Id::new(0);
237        self.end_index = Id::new(capacity - 1);
238    }
239
240    /// Returns a reference to the element at the given index, or `None` if the index is out of bounds or the slot is empty.
241    ///
242    /// # Examples
243    ///
244    /// ```
245    /// use array_linked_list::ArrayLinkedList;
246    ///
247    /// let mut array = ArrayLinkedList::new();
248    /// let index = array.push_back(42);
249    ///
250    /// assert_eq!(array.get(index), Some(&42));
251    /// assert_eq!(array.get(999), None);
252    ///
253    /// array.remove(index);
254    /// assert_eq!(array.get(index), None);
255    /// ```
256    pub fn get(&self, index: usize) -> Option<&T> {
257        self.elements.get(index)?.data.as_ref()
258    }
259
260    /// Returns a mutable reference to the element at the given index, or `None` if the index is out of bounds or the slot is empty.
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use array_linked_list::ArrayLinkedList;
266    ///
267    /// let mut array = ArrayLinkedList::new();
268    /// let index = array.push_back(42);
269    ///
270    /// if let Some(elem) = array.get_mut(index) {
271    ///     *elem = 100;
272    /// }
273    /// assert_eq!(array[index], Some(100));
274    /// ```
275    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
276        self.elements.get_mut(index)?.data.as_mut()
277    }
278
279    /// Constructs a new, empty `ArrayLinkedList<T>` with the specified capacity.
280    ///
281    /// The array will be able to hold exactly `capacity` elements without reallocating.
282    // If `capacity` is 0, the vector will not allocate.
283    pub fn with_capacity(capacity: usize) -> Self {
284        let mut result = Self::new();
285        result.elements = Vec::with_capacity(capacity);
286        result.fill_elements(capacity);
287        result
288    }
289
290    fn insert_free_element(&mut self, element: LinkedListNode<T>) -> Id {
291        Id::new(if let Some(free_index) = self.free_index.index() {
292            let recycle_element = &mut self.elements[free_index];
293            self.free_index = recycle_element.next_index;
294            *recycle_element = element;
295            free_index
296        } else {
297            let index = self.elements.len();
298            self.elements.push(element);
299            index
300        })
301    }
302
303    /// Adds an element at the front of the array and returns its index.
304    /// The indices are returned in a raising order, starting with zero.
305    /// See the module description for more information.
306    ///
307    /// This operation should compute in *O*(1) time.
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// use array_linked_list::ArrayLinkedList;
313    ///
314    /// let mut array = ArrayLinkedList::new();
315    ///
316    /// assert_eq!(array.push_front(2), 0);
317    /// assert_eq!(array.front().unwrap(), &2);
318    ///
319    /// assert_eq!(array.push_front(1), 1);
320    /// assert_eq!(array.front().unwrap(), &1);
321    /// ```
322    pub fn push_front(&mut self, value: T) -> usize {
323        let element = LinkedListNode::front(self.first_index, value);
324
325        let next_index = self.insert_free_element(element);
326
327        *self.prev_of_next(self.first_index, true) = next_index;
328
329        self.first_index = next_index;
330        self.count += 1;
331
332        next_index.valid_index()
333    }
334
335    /// Adds an element at the back of the array and returns its index.
336    /// The indices are returned in a raising order, starting with zero.
337    /// See the module description for more information.
338    ///
339    /// This operation should compute in *O*(1) time.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use array_linked_list::ArrayLinkedList;
345    ///
346    /// let mut array = ArrayLinkedList::new();
347    ///
348    /// assert_eq!(array.push_back(1), 0);
349    /// assert_eq!(array.push_back(3), 1);
350    /// assert_eq!(3, *array.back().unwrap());
351    /// ```
352    pub fn push_back(&mut self, value: T) -> usize {
353        let element = LinkedListNode::back(self.last_index, value);
354
355        let prev_index = self.insert_free_element(element);
356
357        *self.next_of_prev(self.last_index, true) = prev_index;
358
359        self.last_index = prev_index;
360        self.count += 1;
361
362        prev_index.valid_index()
363    }
364
365    fn insert_between(&mut self, prev_index: Id, next_index: Id, value: T) -> usize {
366        let element = LinkedListNode::new(prev_index, next_index, value);
367
368        let index = self.insert_free_element(element);
369
370        *self.next_of_prev(prev_index, true) = index;
371        *self.prev_of_next(next_index, true) = index;
372
373        self.count += 1;
374
375        index.valid_index()
376    }
377
378    /// Inserts an element after the element at the specified index.
379    /// Returns the index of the inserted element on success.
380    /// If no element was found at the specified index, `None` is returned.
381    ///
382    /// # Panics
383    ///
384    /// Panics if `prev_index >= capacity`
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use array_linked_list::ArrayLinkedList;
390    ///
391    /// let mut array = ArrayLinkedList::new();
392    ///
393    /// let first = array.push_back(1);
394    /// let second = array.push_back(2);
395    /// let third = array.push_back(3);
396    ///
397    /// array.insert_after(second, 100);
398    ///
399    /// assert_eq!(array.pop_front(), Some(1));
400    /// assert_eq!(array.pop_front(), Some(2));
401    /// assert_eq!(array.pop_front(), Some(100));
402    /// assert_eq!(array.pop_front(), Some(3));
403    /// assert_eq!(array.pop_front(), None);
404    /// ```
405    pub fn insert_after(&mut self, prev_index: usize, value: T) -> Option<usize> {
406        let LinkedListNode {
407            next_index, data, ..
408        } = &self.elements[prev_index];
409
410        if data.is_some() {
411            let next_index = *next_index;
412            Some(self.insert_between(Id::new(prev_index), next_index, value))
413        } else {
414            None
415        }
416    }
417
418    /// Inserts an element before the element at the specified index.
419    /// Returns the index of the inserted element on success.
420    /// If no element was found at the specified index, `None` is returned.
421    ///
422    /// # Panics
423    ///
424    /// Panics if `next_index >= capacity`
425    ///
426    /// # Examples
427    ///
428    /// ```
429    /// use array_linked_list::ArrayLinkedList;
430    ///
431    /// let mut array = ArrayLinkedList::new();
432    ///
433    /// let first = array.push_back(1);
434    /// let second = array.push_back(2);
435    /// let third = array.push_back(3);
436    ///
437    /// array.insert_before(second, 100);
438    ///
439    /// assert_eq!(array.pop_front(), Some(1));
440    /// assert_eq!(array.pop_front(), Some(100));
441    /// assert_eq!(array.pop_front(), Some(2));
442    /// assert_eq!(array.pop_front(), Some(3));
443    /// assert_eq!(array.pop_front(), None);
444    /// ```
445    pub fn insert_before(&mut self, next_index: usize, value: T) -> Option<usize> {
446        let LinkedListNode {
447            prev_index, data, ..
448        } = &self.elements[next_index];
449
450        if data.is_some() {
451            let prev_index = *prev_index;
452            Some(self.insert_between(prev_index, Id::new(next_index), value))
453        } else {
454            None
455        }
456    }
457
458    #[inline]
459    fn prev_of_next(&mut self, index: Id, active: bool) -> &mut Id {
460        if let Some(index) = index.index() {
461            &mut self.elements[index].prev_index
462        } else if active {
463            &mut self.last_index
464        } else {
465            &mut self.end_index
466        }
467    }
468
469    #[inline]
470    fn next_of_prev(&mut self, index: Id, active: bool) -> &mut Id {
471        if let Some(index) = index.index() {
472            &mut self.elements[index].next_index
473        } else if active {
474            &mut self.first_index
475        } else {
476            &mut self.free_index
477        }
478    }
479
480    fn connect_indices(&mut self, prev_index: Id, next_index: Id, active: bool) {
481        *self.prev_of_next(next_index, active) = prev_index;
482        *self.next_of_prev(prev_index, active) = next_index;
483    }
484
485    /// Removes the element at the given index and returns it, or `None` if it is empty.
486    /// The indices of other items are not changed.
487    /// Indices, which have never been used (see `capacity`), will not be available, but panic instead.
488    ///
489    /// Indices are not the position they appear in, when iterating over them.
490    /// So you can't use enumerate to get the index to delete.
491    /// But the iteration order of the elements (in both directions) is preserved.
492    /// See the module description for more information.
493    ///
494    /// This operation should compute in *O*(1) time.
495    ///
496    /// # Panics
497    ///
498    /// Panics if index >= capacity
499    ///
500    /// # Examples
501    ///
502    /// ```
503    /// use array_linked_list::ArrayLinkedList;
504    ///
505    /// let mut array = ArrayLinkedList::new();
506    ///
507    /// let first = array.push_front(1);
508    /// let second = array.push_back(2);
509    /// let third = array.push_front(3);
510    ///
511    /// assert_eq!(array.len(), 3);
512    ///
513    /// assert_eq!(array.remove(second).unwrap(), 2);
514    /// assert_eq!(array[second], None);
515    /// assert_eq!(array.len(), 2);
516    /// assert_eq!(array.remove(second), None);
517    /// assert_eq!(array.len(), 2);
518    ///
519    /// assert_eq!(array.remove(first).unwrap(), 1);
520    /// assert_eq!(array.len(), 1);
521    /// assert_eq!(array.remove(third).unwrap(), 3);
522    /// assert_eq!(array.len(), 0);
523    /// assert!(array.is_empty());
524    /// ```
525    pub fn remove(&mut self, index: usize) -> Option<T> {
526        let LinkedListNode {
527            next_index,
528            prev_index,
529            data,
530        } = mem::replace(
531            &mut self.elements[index],
532            LinkedListNode::deleted(self.free_index),
533        );
534
535        let removed = data.is_some();
536        self.connect_indices(prev_index, next_index, removed);
537
538        if removed {
539            self.count -= 1;
540        }
541
542        if let Some(free_index) = self.free_index.index() {
543            self.elements[free_index].prev_index = Id::new(index);
544        }
545
546        self.free_index = Id::new(index);
547        data
548    }
549
550    /// Adds element at specified index at the front of the list.
551    /// Useful for updating contents.
552    ///
553    /// It basically does the same as `remove` and `push_back`, even if the specified index is already removed.
554    ///
555    /// # Panics
556    ///
557    /// Panics if index >= capacity
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use array_linked_list::ArrayLinkedList;
563    ///
564    /// let mut array = ArrayLinkedList::new();
565    ///
566    /// array.push_front(1);
567    /// let first_index = array.push_back(2);
568    /// array.push_front(3);
569    /// let second_index = array.push_front(4);
570    /// array.push_back(5);
571    ///
572    /// let mut array2 = array.clone();
573    /// for (a, b) in array.iter().zip(&array2) {
574    ///     assert_eq!(a, b)
575    /// }
576    ///
577    /// let first_element = array.replace_front(first_index, 100);
578    /// let first_element2 = array2.remove(first_index);
579    /// array2.push_front(100);
580    ///
581    /// assert_eq!(first_element, first_element2);
582    /// for (a, b) in array.iter().zip(&array2) {
583    ///     assert_eq!(a, b)
584    /// }
585    ///
586    /// let second_element = array.replace_front(first_index, 0);
587    /// let second_element2 = array2.remove(first_index);
588    /// array2.push_back(0);
589    ///
590    /// assert_eq!(second_element, second_element2);
591    ///
592    /// assert!(array.iter().zip(&array2).any(|(a, b)| a != b));
593    ///
594    /// assert_eq!(array.len(), 5);
595    /// assert_eq!(array2.len(), 5);
596    /// ```
597    pub fn replace_front(&mut self, index: usize, value: T) -> Option<T> {
598        let LinkedListNode {
599            next_index,
600            prev_index,
601            data,
602        } = mem::replace(
603            &mut self.elements[index],
604            LinkedListNode::front(self.first_index, value),
605        );
606
607        let removed = data.is_some();
608        self.connect_indices(prev_index, next_index, removed);
609
610        if !removed {
611            self.count += 1;
612        }
613
614        if let Some(first_index) = self.first_index.index() {
615            self.elements[first_index].prev_index = Id::new(index);
616        }
617
618        self.first_index = Id::new(index);
619        data
620    }
621
622    /// Adds element at specified index at the front of the list.
623    /// Useful for updating contents.
624    ///
625    /// It basically does the same as `remove` and `push_back`, even if the specified index is already removed.
626    ///
627    /// # Panics
628    ///
629    /// Panics if index >= capacity
630    ///
631    /// # Examples
632    ///
633    /// ```
634    /// use array_linked_list::ArrayLinkedList;
635    ///
636    /// let mut array = ArrayLinkedList::new();
637    ///
638    /// array.push_front(1);
639    /// array.push_back(2);
640    /// let middle_index = array.push_back(3);
641    /// array.push_front(4);
642    /// array.push_back(5);
643    ///
644    /// let mut array2 = array.clone();
645    /// for (a, b) in array.iter().zip(&array2) {
646    ///     assert_eq!(a, b)
647    /// }
648    ///
649    /// let element = array.replace_back(middle_index, 100);
650    /// let element2 = array2.remove(middle_index);
651    /// array2.push_back(100);
652    ///
653    /// assert_eq!(element, element2);
654    /// for (a, b) in array.iter().zip(&array2) {
655    ///     assert_eq!(a, b)
656    /// }
657    ///
658    /// assert_eq!(array.len(), 5);
659    /// assert_eq!(array2.len(), 5);
660    /// ```
661    pub fn replace_back(&mut self, index: usize, value: T) -> Option<T> {
662        let LinkedListNode {
663            next_index,
664            prev_index,
665            data,
666        } = mem::replace(
667            &mut self.elements[index],
668            LinkedListNode::back(self.last_index, value),
669        );
670
671        let removed = data.is_some();
672        self.connect_indices(prev_index, next_index, removed);
673
674        if !removed {
675            self.count += 1;
676        }
677
678        if let Some(last_index) = self.last_index.index() {
679            self.elements[last_index].next_index = Id::new(index);
680        }
681
682        self.last_index = Id::new(index);
683        data
684    }
685
686    /// Removes the first element from the array and returns it, or `None` if it is empty.
687    ///
688    /// This operation should compute in *O*(1) time.
689    ///
690    /// # Examples
691    ///
692    /// ```
693    /// use array_linked_list::ArrayLinkedList;
694    ///
695    /// let mut array = ArrayLinkedList::new();
696    /// assert_eq!(array.pop_front(), None);
697    /// array.push_back(1);
698    /// array.push_back(3);
699    /// assert_eq!(array.pop_front(), Some(1));
700    /// array.push_front(5);
701    /// array.push_front(7);
702    /// assert_eq!(array.pop_front(), Some(7));
703    /// array.push_front(9);
704    /// let mut array = array.into_iter();
705    /// assert_eq!(array.next(), Some(9));
706    /// assert_eq!(array.next_back(), Some(3));
707    /// assert_eq!(array.next(), Some(5));
708    /// ```
709    pub fn pop_front(&mut self) -> Option<T> {
710        let index = self.first_index.index()?;
711
712        let LinkedListNode {
713            next_index, data, ..
714        } = mem::replace(
715            &mut self.elements[index],
716            LinkedListNode::deleted(self.free_index),
717        );
718
719        *self.prev_of_next(next_index, true) = Id::default();
720        self.first_index = next_index;
721
722        self.count -= 1;
723        if let Some(free_index) = self.free_index.index() {
724            self.elements[free_index].prev_index = Id::new(index);
725        }
726
727        self.free_index = Id::new(index);
728        Some(unsafe { data.unwrap_unchecked() })
729    }
730
731    /// Removes the last element from the array and returns it, or `None` if it is empty.
732    ///
733    /// This operation should compute in *O*(1) time.
734    ///
735    /// # Examples
736    ///
737    /// ```
738    /// use array_linked_list::ArrayLinkedList;
739    ///
740    /// let mut array = ArrayLinkedList::new();
741    /// assert_eq!(array.pop_back(), None);
742    /// array.push_back(1);
743    /// array.push_back(3);
744    /// assert_eq!(array.pop_back(), Some(3));
745    /// array.push_back(5);
746    /// array.push_back(7);
747    /// let mut array = array.into_iter();
748    /// assert_eq!(array.next_back(), Some(7));
749    /// assert_eq!(array.next(), Some(1));
750    /// assert_eq!(array.next_back(), Some(5));
751    /// ```
752    pub fn pop_back(&mut self) -> Option<T> {
753        let index = self.last_index.index()?;
754
755        let LinkedListNode {
756            prev_index, data, ..
757        } = mem::replace(
758            &mut self.elements[index],
759            LinkedListNode::deleted(self.free_index),
760        );
761
762        self.last_index = prev_index;
763        *self.next_of_prev(prev_index, true) = Id::default();
764
765        self.count -= 1;
766        if let Some(free_index) = self.free_index.index() {
767            self.elements[free_index].prev_index = Id::new(index);
768        }
769
770        self.free_index = Id::new(index);
771        Some(unsafe { data.unwrap_unchecked() })
772    }
773
774    /// The index of the first list element.
775    /// Returns `None` if array is empty.
776    pub fn front_index(&self) -> Option<usize> {
777        self.first_index.index()
778    }
779
780    /// The index of the last list element.
781    /// Returns `None` if array is empty.
782    pub fn back_index(&self) -> Option<usize> {
783        self.last_index.index()
784    }
785
786    /// The first list element.
787    /// Returns `None` if array is empty.
788    pub fn front(&self) -> Option<&T> {
789        let index = self.first_index.index()?;
790
791        Some(unsafe { self.elements[index].data.as_ref().unwrap_unchecked() })
792    }
793
794    /// The last list element.
795    /// Returns `None` if array is empty.
796    pub fn back(&self) -> Option<&T> {
797        let index = self.last_index.index()?;
798
799        Some(unsafe { self.elements[index].data.as_ref().unwrap_unchecked() })
800    }
801
802    /// The first list element as a mutable reference.
803    /// Returns `None` if array is empty.
804    pub fn front_mut(&mut self) -> Option<&mut T> {
805        let index = self.first_index.index()?;
806
807        Some(unsafe { self.elements[index].data.as_mut().unwrap_unchecked() })
808    }
809
810    /// The last list element as a mutable reference.
811    /// Returns `None` if array is empty.
812    pub fn back_mut(&mut self) -> Option<&mut T> {
813        let index = self.last_index.index()?;
814
815        Some(unsafe { self.elements[index].data.as_mut().unwrap_unchecked() })
816    }
817
818    /// Checks if the list is empty.
819    pub fn is_empty(&self) -> bool {
820        self.first_index.is_empty() && self.last_index.is_empty()
821    }
822
823    /// Clears the linked array, removing all values.
824    ///
825    /// Note that this method has no effect on the allocated capacity of the array.
826    /// So all indices, which have already been used (see `capacity`), are still available.
827    pub fn clear(&mut self) {
828        self.count = 0;
829        self.first_index = Id::default();
830        self.last_index = Id::default();
831        self.free_index = Id::default();
832        self.end_index = Id::default();
833
834        let capacity = self.elements.len();
835        self.elements.clear();
836        self.fill_elements(capacity);
837    }
838
839    /// Returns the number of elements in the linked array.
840    pub fn len(&self) -> usize {
841        self.count
842    }
843
844    /// Returns the number of elements the vector can hold without reallocating.
845    ///
846    /// Methods, which take indices, require the specified index to be below the capacity.
847    ///
848    /// All the following methods require indices:
849    ///
850    /// * `insert_before`
851    /// * `insert_after`
852    /// * `remove`
853    /// * `replace_front`
854    /// * `replace_back`
855    ///
856    /// Besides that, some of the iterators are constructed using indices in the same range.
857    pub fn capacity(&self) -> usize {
858        self.elements.len()
859    }
860
861    /// Returns a borrowing iterator over its elements.
862    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> {
863        Values(Indexed::new(self))
864    }
865
866    /// Returns a borrowing iterator over its indexed elements.
867    pub fn indexed(&self) -> impl DoubleEndedIterator<Item = (usize, &T)> {
868        Indexed::new(self)
869    }
870
871    /// Returns a borrowing iterator over its indices.
872    pub fn indices(&self) -> impl DoubleEndedIterator<Item = usize> + '_ {
873        Indices(Indexed::new(self))
874    }
875
876    /// Returns a borrowing iterator over its elements, starting after the element at the specified index.
877    ///
878    /// # Panics
879    ///
880    /// Panics if index >= capacity
881    pub fn iter_after(&self, index: usize) -> impl DoubleEndedIterator<Item = &T> {
882        Values(Indexed::after(self, index))
883    }
884
885    /// Returns a borrowing iterator over its indexed elements, starting after the element at the specified index.
886    ///
887    /// # Panics
888    ///
889    /// Panics if index >= capacity
890    pub fn indexed_after(&self, index: usize) -> impl DoubleEndedIterator<Item = (usize, &T)> {
891        Indexed::after(self, index)
892    }
893
894    /// Returns a borrowing iterator over its indices, starting after the element at the specified index.
895    ///
896    /// # Panics
897    ///
898    /// Panics if index >= capacity
899    pub fn indices_after(&self, index: usize) -> impl DoubleEndedIterator<Item = usize> + '_ {
900        Indices(Indexed::after(self, index))
901    }
902
903    /// Returns a borrowing iterator over its elements, ending before the element at the specified index.
904    ///
905    /// # Panics
906    ///
907    /// Panics if index >= capacity
908    pub fn iter_before(&self, index: usize) -> impl DoubleEndedIterator<Item = &T> {
909        Values(Indexed::before(self, index))
910    }
911
912    /// Returns a borrowing iterator over its indexed elements, ending before the element at the specified index.
913    ///
914    /// # Panics
915    ///
916    /// Panics if index >= capacity
917    pub fn indexed_before(&self, index: usize) -> impl DoubleEndedIterator<Item = (usize, &T)> {
918        Indexed::before(self, index)
919    }
920
921    /// Returns a borrowing iterator over its indices, ending before the element at the specified index.
922    ///
923    /// # Panics
924    ///
925    /// Panics if index >= capacity
926    pub fn indices_before(&self, index: usize) -> impl DoubleEndedIterator<Item = usize> + '_ {
927        Indices(Indexed::before(self, index))
928    }
929
930    /// Returns an owning iterator returning its indexed elements.
931    pub fn into_indexed(self) -> impl DoubleEndedIterator<Item = (usize, T)> {
932        IntoIndexed(self)
933    }
934
935    /// Returns an owning iterator returning its indices.
936    pub fn into_indices(self) -> impl DoubleEndedIterator<Item = usize> {
937        IntoIndices(IntoIndexed(self))
938    }
939}
940
941impl<T> Index<usize> for ArrayLinkedList<T> {
942    type Output = Option<T>;
943    fn index(&self, index: usize) -> &Option<T> {
944        &self.elements[index].data
945    }
946}
947
948impl<T> IndexMut<usize> for ArrayLinkedList<T> {
949    fn index_mut(&mut self, index: usize) -> &mut Option<T> {
950        &mut self.elements[index].data
951    }
952}
953
954struct Indexed<'a, T> {
955    front_index: Id,
956    back_index: Id,
957    array: &'a ArrayLinkedList<T>,
958}
959
960impl<'a, T> Indexed<'a, T> {
961    fn empty(array: &'a ArrayLinkedList<T>) -> Self {
962        Self {
963            front_index: Id::default(),
964            back_index: Id::default(),
965            array,
966        }
967    }
968
969    fn new(array: &'a ArrayLinkedList<T>) -> Self {
970        Self {
971            front_index: array.first_index,
972            back_index: array.last_index,
973            array,
974        }
975    }
976
977    fn after(array: &'a ArrayLinkedList<T>, prev_index: usize) -> Self {
978        let element = &array.elements[prev_index];
979        if element.data.is_some() {
980            Self {
981                front_index: element.next_index,
982                back_index: array.last_index,
983                array,
984            }
985        } else {
986            Self::empty(array)
987        }
988    }
989
990    fn before(array: &'a ArrayLinkedList<T>, next_index: usize) -> Self {
991        let element = &array.elements[next_index];
992        if element.data.is_some() {
993            Self {
994                front_index: array.first_index,
995                back_index: element.prev_index,
996                array,
997            }
998        } else {
999            Self::empty(array)
1000        }
1001    }
1002}
1003
1004struct Indices<'a, T>(Indexed<'a, T>);
1005
1006/// Borrowing iterator over values of the linked array.
1007pub struct Values<'a, T>(Indexed<'a, T>);
1008
1009impl<'a, T> Iterator for Indexed<'a, T> {
1010    type Item = (usize, &'a T);
1011    #[inline]
1012    fn next(&mut self) -> Option<Self::Item> {
1013        let index = self.front_index.index()?;
1014
1015        let element = &self.array.elements[index];
1016        if self.front_index == self.back_index {
1017            self.front_index = Id::default();
1018            self.back_index = Id::default();
1019        } else {
1020            self.front_index = element.next_index;
1021        }
1022        Some((index, unsafe { element.data.as_ref().unwrap_unchecked() }))
1023    }
1024}
1025
1026impl<T> DoubleEndedIterator for Indexed<'_, T> {
1027    #[inline]
1028    fn next_back(&mut self) -> Option<Self::Item> {
1029        let index = self.back_index.index()?;
1030
1031        let element = &self.array.elements[index];
1032        if self.front_index == self.back_index {
1033            self.front_index = Id::default();
1034            self.back_index = Id::default();
1035        } else {
1036            self.back_index = element.prev_index;
1037        }
1038        Some((index, unsafe { element.data.as_ref().unwrap_unchecked() }))
1039    }
1040}
1041
1042impl<T> Iterator for Indices<'_, T> {
1043    type Item = usize;
1044    fn next(&mut self) -> Option<Self::Item> {
1045        self.0.next().map(|(index, _)| index)
1046    }
1047}
1048
1049impl<T> DoubleEndedIterator for Indices<'_, T> {
1050    fn next_back(&mut self) -> Option<Self::Item> {
1051        self.0.next_back().map(|(index, _)| index)
1052    }
1053}
1054
1055impl<'a, T> Iterator for Values<'a, T> {
1056    type Item = &'a T;
1057    fn next(&mut self) -> Option<Self::Item> {
1058        self.0.next().map(|(_, value)| value)
1059    }
1060}
1061
1062impl<T> DoubleEndedIterator for Values<'_, T> {
1063    fn next_back(&mut self) -> Option<Self::Item> {
1064        self.0.next_back().map(|(_, value)| value)
1065    }
1066}
1067
1068impl<'a, T> IntoIterator for &'a ArrayLinkedList<T> {
1069    type Item = &'a T;
1070    type IntoIter = Values<'a, T>;
1071
1072    #[inline]
1073    fn into_iter(self) -> Self::IntoIter {
1074        Values(Indexed::new(self))
1075    }
1076}
1077
1078struct IntoIndexed<T>(ArrayLinkedList<T>);
1079struct IntoIndices<T>(IntoIndexed<T>);
1080
1081/// Owning iterator over values of the linked array.
1082pub struct IntoValues<T>(IntoIndexed<T>);
1083
1084impl<T> Iterator for IntoIndexed<T> {
1085    type Item = (usize, T);
1086    #[inline]
1087    fn next(&mut self) -> Option<Self::Item> {
1088        let index = self.0.first_index.index()?;
1089
1090        let element = &mut self.0.elements[index];
1091        if self.0.first_index == self.0.last_index {
1092            self.0.first_index = Id::default();
1093            self.0.last_index = Id::default();
1094        } else {
1095            self.0.first_index = element.next_index;
1096        }
1097        Some((index, unsafe { element.data.take().unwrap_unchecked() }))
1098    }
1099}
1100
1101impl<T> DoubleEndedIterator for IntoIndexed<T> {
1102    #[inline]
1103    fn next_back(&mut self) -> Option<Self::Item> {
1104        let index = self.0.last_index.index()?;
1105
1106        let element = &mut self.0.elements[index];
1107        if self.0.first_index == self.0.last_index {
1108            self.0.first_index = Id::default();
1109            self.0.last_index = Id::default();
1110        } else {
1111            self.0.last_index = element.prev_index;
1112        }
1113        Some((index, unsafe { element.data.take().unwrap_unchecked() }))
1114    }
1115}
1116
1117impl<T> Iterator for IntoIndices<T> {
1118    type Item = usize;
1119    fn next(&mut self) -> Option<Self::Item> {
1120        self.0.next().map(|(index, _)| index)
1121    }
1122}
1123
1124impl<T> DoubleEndedIterator for IntoIndices<T> {
1125    fn next_back(&mut self) -> Option<Self::Item> {
1126        self.0.next_back().map(|(index, _)| index)
1127    }
1128}
1129
1130impl<T> Iterator for IntoValues<T> {
1131    type Item = T;
1132    fn next(&mut self) -> Option<Self::Item> {
1133        self.0.next().map(|(_, value)| value)
1134    }
1135}
1136
1137impl<T> DoubleEndedIterator for IntoValues<T> {
1138    fn next_back(&mut self) -> Option<Self::Item> {
1139        self.0.next_back().map(|(_, value)| value)
1140    }
1141}
1142
1143impl<T> IntoIterator for ArrayLinkedList<T> {
1144    type Item = T;
1145    type IntoIter = IntoValues<T>;
1146
1147    fn into_iter(self) -> Self::IntoIter {
1148        IntoValues(IntoIndexed(self))
1149    }
1150}