Skip to main content

plain_ds/lite/list/
single_linked_list.rs

1//! This module contains single-linked list implementation.
2
3use std::ptr;
4
5use crate::lite::list::error::{ListError, Result};
6use crate::lite::list::iter::{IntoIter, Iter, IterMut};
7use crate::lite::list::merge_sort::merge_sort;
8use crate::lite::list::node::Node;
9
10pub struct SingleLinkedList<T> {
11    head: *mut Node<T>, // 8 bytes
12    last: *mut Node<T>, // 8 bytes
13    size: usize,        // 8 bytes
14}
15
16impl<T> SingleLinkedList<T> {
17    /// Creates empty list.
18    pub fn new() -> Self {
19        Self {
20            head: ptr::null_mut(),
21            last: ptr::null_mut(),
22            size: 0,
23        }
24    }
25
26    /// Creates list from slice.
27    pub fn from_slice(slice: &[T]) -> Self
28    where
29        T: Clone,
30    {
31        let mut list = SingleLinkedList::new();
32        for value in slice {
33            list.push_back((*value).clone());
34        }
35        list
36    }
37
38    /// Collect list values into a vector.
39    ///
40    /// Efficiency: O(n)
41    pub fn to_vec(&self) -> Vec<T>
42    where
43        T: Clone,
44    {
45        let mut vec = Vec::with_capacity(self.size);
46        vec.extend(self.iter().cloned());
47        vec
48    }
49
50    /// Returns list size.
51    ///
52    /// Efficiency: O(1)
53    pub fn len(&self) -> usize {
54        self.size
55    }
56
57    /// Checks if the list is empty.
58    /// Efficiency: O(1)
59    pub fn is_empty(&self) -> bool {
60        self.size == 0
61    }
62
63    /// Returns the payload value of the first node in the list.
64    ///
65    /// Efficiency: O(1)
66    pub fn head(&self) -> Option<&T> {
67        if self.head.is_null() {
68            None
69        } else {
70            Some(unsafe { &(*self.head).payload })
71        }
72    }
73
74    /// Returns the payload value of the last node in the list.
75    ///
76    /// Efficiency: O(1)
77    pub fn last(&self) -> Option<&T> {
78        if self.last.is_null() {
79            None
80        } else {
81            Some(unsafe { &(*self.last).payload })
82        }
83    }
84
85    /// Returns a list item by index, or error if index out of bounds.
86    ///
87    /// Efficiency: O(n)
88    pub fn get(&self, index: usize) -> Result<&T> {
89        if index + 1 == self.size {
90            return self.last().ok_or(ListError::IndexOutOfBounds { index, len: self.size });
91        }
92
93        // Finding by index
94        self.iter().nth(index).ok_or(ListError::IndexOutOfBounds { index, len: self.size })
95    }
96
97    /// Returns a mutable list item by index, or error if index out of bounds.
98    ///
99    /// Efficiency: O(n)
100    pub fn get_mut(&mut self, index: usize) -> Result<&mut T> {
101        let list_size = self.size;
102        if index + 1 == list_size {
103            return Ok(unsafe { &mut (*self.last).payload });
104        }
105
106        // Finding by index
107        self.iter_mut().nth(index).ok_or(ListError::IndexOutOfBounds { index, len: list_size })
108    }
109
110    /// Returns an iterator over the immutable items of the list.
111    pub fn iter(&self) -> impl Iterator<Item = &T> {
112        Iter::new(self.head)
113    }
114
115    /// Returns an iterator over the mutable items of the list.
116    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
117        IterMut::new(self.head)
118    }
119
120    /// Returns an iterator that consumes the list.
121    pub fn into_iter(self) -> impl Iterator<Item = T> {
122        IntoIter::new(self)
123    }
124
125    /// Adds a new node to the end of the list.
126    ///
127    /// Efficiency: O(1)
128    pub fn push_back(&mut self, payload: T) {
129        let ptr = Box::into_raw(Box::new(Node::new(payload)));
130        if self.is_empty() {
131            self.head = ptr;
132        } else {
133            unsafe { (*self.last).next = ptr };
134        }
135        self.last = ptr;
136        self.size += 1;
137    }
138
139    /// Adds a new node to the front of the list.
140    ///
141    /// Efficiency: O(1)
142    pub fn push_front(&mut self, payload: T) {
143        let ptr = Box::into_raw(Box::new(Node::new(payload)));
144        if self.is_empty() {
145            self.last = ptr;
146        } else {
147            unsafe { (*ptr).next = self.head }
148        }
149        self.head = ptr;
150        self.size += 1;
151    }
152
153    /// Removes a node from the end of the list and returns its payload value.
154    ///
155    /// Efficiency: O(n)
156    pub fn pop_back(&mut self) -> Option<T> {
157        if self.is_empty() {
158            return None;
159        }
160
161        // Case: only one node in list
162        if self.head == self.last {
163            let payload = unsafe { Box::from_raw(self.head).payload };
164            self.head = ptr::null_mut();
165            self.last = ptr::null_mut();
166            self.size -= 1;
167            return Some(payload);
168        }
169
170        // Finding the penultimate node
171        let mut current = self.head;
172        unsafe {
173            while (*current).next != self.last {
174                current = (*current).next;
175            }
176        }
177
178        // current now points to the penultimate node
179        let old_last = self.last;
180        self.last = current;
181        unsafe { (*self.last).next = ptr::null_mut() };
182
183        // Release the last node and extract the payload
184        let payload = unsafe {
185            let boxed = Box::from_raw(old_last);
186            boxed.payload
187        };
188
189        self.size -= 1;
190        Some(payload)
191    }
192
193    /// Removes a node from the front of the list and returns its payload value.
194    ///
195    /// Efficiency: O(1)
196    pub fn pop_front(&mut self) -> Option<T> {
197        if self.is_empty() {
198            return None;
199        }
200
201        let old_head = unsafe { Box::from_raw(self.head) };
202        self.head = old_head.next;
203        if self.len() == 1 {
204            self.last = ptr::null_mut();
205        }
206
207        self.size -= 1;
208        Some(old_head.payload)
209    }
210
211    /// Insert a new node at the specified location in the list.
212    /// Error returns, if the index out of bounds.
213    ///
214    /// Efficiency: O(n)
215    pub fn insert(&mut self, index: usize, payload: T) -> Result<()> {
216        if index > self.size {
217            return Err(ListError::IndexOutOfBounds { index, len: self.size });
218        }
219        if index == self.size {
220            self.push_back(payload);
221            return Ok(());
222        }
223        if index == 0 {
224            self.push_front(payload);
225            return Ok(());
226        }
227
228        // Finding the insert point
229        let mut current = self.head;
230        let mut index = index;
231        unsafe {
232            while index > 1 {
233                current = (*current).next;
234                index -= 1;
235            }
236        }
237
238        let mut boxed = Box::new(Node::new(payload));
239        unsafe {
240            boxed.next = (*current).next;
241            (*current).next = Box::into_raw(boxed);
242        }
243
244        self.size += 1;
245        Ok(())
246    }
247
248    /// Removes a node from the specified location in the list.
249    /// Error returns, if the index out of bounds.
250    ///
251    /// Efficiency: O(n)
252    pub fn remove(&mut self, index: usize) -> Result<T> {
253        if index >= self.size {
254            return Err(ListError::IndexOutOfBounds { index, len: self.size });
255        }
256        if index == 0 {
257            // remove first
258            return Ok(self.pop_front().unwrap());
259        }
260        if index + 1 == self.size {
261            // remove last
262            return Ok(self.pop_back().unwrap());
263        }
264
265        // Finding the removing item
266        let mut before = self.head;
267        let mut index = index;
268        unsafe {
269            while index > 1 {
270                before = (*before).next;
271                index -= 1;
272            }
273        }
274
275        let removed = unsafe { Box::from_raw((*before).next) };
276        unsafe { (*before).next = removed.next };
277
278        self.size -= 1;
279        Ok(removed.payload)
280    }
281
282    /// Removes all items from the list.
283    ///
284    /// Efficiency: O(n)
285    pub fn clear(&mut self) {
286        while self.len() != 0 {
287            let _ = self.pop_front();
288        }
289    }
290
291    /// Finds the first node whose payload is equal to the given one and returns its index.
292    /// Returns `None` if there is no such node.
293    ///
294    /// Efficiency: O(n)
295    pub fn find(&self, value: &T) -> Option<usize>
296    where
297        T: PartialEq,
298    {
299        self.find_if(|item| item == value)
300    }
301
302    /// Finds the first node whose payload satisfies the predicate and returns its index.
303    /// Returns `None` if there is no such node.
304    ///
305    /// Efficiency: O(n)
306    pub fn find_if(&self, predicate: impl Fn(&T) -> bool) -> Option<usize> {
307        self.iter()
308            .enumerate()
309            .find(|(_, item)| predicate(*item))
310            .map(|(index, _)| index)
311    }
312
313    /// Sorts the list in ascending order using merge sort algorithm.
314    ///
315    /// Efficiency: O(n log n)
316    ///
317    /// Space complexity: O(log n) due to recursion stack
318    pub fn sort(&mut self)
319    where
320        T: PartialOrd + Default,
321    {
322        if self.size <= 1 {
323            return; // Already sorted
324        }
325
326        // Extract the head and reset the list
327        let head = self.head;
328        self.head = ptr::null_mut();
329        self.last = ptr::null_mut();
330        self.size = 0;
331
332        // Sort the extracted nodes and get new head
333        let sorted_head = merge_sort(head);
334
335        // Reconstruct the list with sorted nodes
336        self.rebuild_from_sorted_list(sorted_head);
337    }
338
339    /// Rebuilds the SingleLinkedList from a sorted list of nodes
340    fn rebuild_from_sorted_list(&mut self, head: *mut Node<T>) {
341        self.head = head;
342        self.size = 0;
343
344        if head.is_null() {
345            self.last = std::ptr::null_mut();
346            return;
347        }
348
349        // Traverse to find the last node and count size
350        let mut current = head;
351        self.size = 1;
352
353        unsafe {
354            while !(*current).next.is_null() {
355                current = (*current).next;
356                self.size += 1;
357            }
358            self.last = current;
359        }
360    }
361}
362
363impl<T> Drop for SingleLinkedList<T> {
364    fn drop(&mut self) {
365        use std::mem::ManuallyDrop;
366
367        let mut current = ManuallyDrop::new(self.head);
368        while !current.is_null() {
369            unsafe {
370                let node = Box::from_raw(ManuallyDrop::take(&mut current));
371                current = ManuallyDrop::new(node.next);
372            }
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    // Helper function to create a list with values [0, 1, 2, ..., n-1]
382    fn setup_list(n: usize) -> SingleLinkedList<usize> {
383        let mut list = SingleLinkedList::new();
384        for i in 0..n {
385            list.push_back(i);
386        }
387        list
388    }
389
390    #[test]
391    fn test_creation() {
392        let list: SingleLinkedList<u8> = SingleLinkedList::new();
393        assert_eq!(list.len(), 0, "not zero length after creation");
394        assert_eq!(list.head(), None, "not empty head after creation");
395        assert_eq!(list.last(), None, "not empty last after creation");
396        assert!(list.is_empty(), "is_empty() returns `false` after creation");
397
398        let list: SingleLinkedList<String> = SingleLinkedList::new();
399        assert!(list.is_empty(), "is_empty() returns `false` after creation");
400
401        let list: SingleLinkedList<&[char]> = SingleLinkedList::new();
402        assert!(list.is_empty(), "is_empty() returns `false` after creation");
403    }
404
405    mod get {
406        use super::*;
407
408        #[test]
409        fn test_get_empty_list() {
410            let list: SingleLinkedList<i32> = SingleLinkedList::new();
411            assert!(
412                list.get(0).is_err(),
413                "get() on empty list should return error"
414            );
415            assert!(
416                list.get(1).is_err(),
417                "get() with any index on empty list should return error"
418            );
419        }
420
421        #[test]
422        fn test_get_index_out_of_bounds() {
423            let mut list = SingleLinkedList::new();
424            list.push_back(10);
425            list.push_back(20);
426            list.push_back(30);
427
428            assert!(
429                list.get(3).is_err(),
430                "get() with index == size should return error (out of bounds)"
431            );
432            assert!(
433                list.get(4).is_err(),
434                "get() with index > size should return error"
435            );
436            assert!(
437                list.get(100).is_err(),
438                "get() with large out-of-bounds index should return error"
439            );
440        }
441
442        #[test]
443        fn test_get_first_element() {
444            let mut list = SingleLinkedList::new();
445            list.push_back(100);
446            list.push_back(200);
447            list.push_back(300);
448
449            let result = list.get(0).unwrap();
450            assert_eq!(*result, 100, "get(0) should return first element (100)");
451        }
452
453        #[test]
454        fn test_get_last_element() {
455            let mut list = SingleLinkedList::new();
456            list.push_back(100);
457            list.push_back(200);
458            list.push_back(300);
459
460            let result = list.get(2).unwrap(); // index = size - 1
461            assert_eq!(
462                *result, 300,
463                "get(last_index) should return last element (300)"
464            );
465        }
466
467        #[test]
468        fn test_get_middle_element() {
469            let mut list = SingleLinkedList::new();
470            list.push_back(10);
471            list.push_back(20);
472            list.push_back(30);
473            list.push_back(40);
474            list.push_back(50);
475
476            let result = list.get(2).unwrap(); // middle element
477            assert_eq!(*result, 30, "get(2) should return middle element (30)");
478
479            let result2 = list.get(1).unwrap();
480            assert_eq!(*result2, 20, "get(1) should return second element (20)");
481        }
482
483        #[test]
484        fn test_get_single_element_list() {
485            let mut list = SingleLinkedList::new();
486            list.push_back(42);
487
488            let result = list.get(0).unwrap();
489            assert_eq!(
490                *result, 42,
491                "get(0) on single-element list should return that element"
492            );
493
494            assert!(
495                list.get(1).is_err(),
496                "get(1) on single-element list should be out of bounds"
497            );
498        }
499
500        #[test]
501        fn test_get_with_complex_types() {
502            // Test with String
503            let mut string_list = SingleLinkedList::new();
504            string_list.push_back("apple".to_string());
505            string_list.push_back("banana".to_string());
506            string_list.push_back("cherry".to_string());
507
508            let first = string_list.get(0).unwrap();
509            assert_eq!(first, "apple", "get(0) should return 'apple'");
510
511            let last = string_list.get(2).unwrap();
512            assert_eq!(last, "cherry", "get(2) should return 'cherry'");
513
514            // Test with Vec
515            let mut vec_list = SingleLinkedList::new();
516            vec_list.push_back(vec![1, 2]);
517            vec_list.push_back(vec![3, 4]);
518
519            let vec_result = vec_list.get(1).unwrap();
520            assert_eq!(vec_result, &vec![3, 4], "get(1) should return vec![3, 4]");
521        }
522
523        #[test]
524        fn test_get_preserves_list_integrity() {
525            let mut list = SingleLinkedList::new();
526            list.push_back(1);
527            list.push_back(2);
528            list.push_back(3);
529
530            // Get element in the middle
531            let _ = list.get(1).unwrap();
532
533            // Verify list is unchanged
534            assert_eq!(
535                list.len(),
536                3,
537                "list length should remain unchanged after get()"
538            );
539            assert_eq!(list.head(), Some(&1), "head should remain the same");
540            assert_eq!(list.last(), Some(&3), "last should remain the same");
541
542            // Verify we can still get other elements
543            assert_eq!(
544                *list.get(0).unwrap(),
545                1,
546                "get(0) after get(1) should still work"
547            );
548            assert_eq!(
549                *list.get(2).unwrap(),
550                3,
551                "get(2) after get(1) should still work"
552            );
553        }
554
555        #[test]
556        fn test_get_mut_empty_list() {
557            let mut list: SingleLinkedList<i32> = SingleLinkedList::new();
558            assert!(
559                list.get_mut(0).is_err(),
560                "get_mut() on empty list should return error"
561            );
562        }
563
564        #[test]
565        fn test_get_mut_index_out_of_bounds() {
566            let mut list = SingleLinkedList::new();
567            list.push_back(10);
568            list.push_back(20);
569
570            assert!(
571                list.get_mut(2).is_err(),
572                "get_mut() with index == size should return error"
573            );
574            assert!(
575                list.get_mut(5).is_err(),
576                "get_mut() with large out-of-bounds index should return error"
577            );
578        }
579
580        #[test]
581        fn test_get_mut_first_element() {
582            let mut list = SingleLinkedList::new();
583            list.push_back(100);
584            list.push_back(200);
585            list.push_back(300);
586
587            let mut_ref = list.get_mut(0).unwrap();
588            *mut_ref = 999;
589
590            assert_eq!(
591                *list.get(0).unwrap(),
592                999,
593                "first element should be modified to 999"
594            );
595            assert_eq!(
596                *list.head().unwrap(),
597                999,
598                "head should reflect the modification"
599            );
600        }
601
602        #[test]
603        fn test_get_mut_last_element() {
604            let mut list = SingleLinkedList::new();
605            list.push_back(100);
606            list.push_back(200);
607            list.push_back(300);
608
609            let mut_ref = list.get_mut(2).unwrap(); // last element
610            *mut_ref = 888;
611
612            assert_eq!(
613                *list.get(2).unwrap(),
614                888,
615                "last element should be modified to 888"
616            );
617            assert_eq!(
618                *list.last().unwrap(),
619                888,
620                "last should reflect the modification"
621            );
622        }
623
624        #[test]
625        fn test_get_mut_middle_element() {
626            let mut list = SingleLinkedList::new();
627            list.push_back(10);
628            list.push_back(20);
629            list.push_back(30);
630            list.push_back(40);
631
632            let mut_ref = list.get_mut(2).unwrap(); // third element
633            *mut_ref *= 2; // 30 * 2 = 60
634
635            assert_eq!(
636                *list.get(2).unwrap(),
637                60,
638                "middle element should be doubled to 60"
639            );
640        }
641
642        #[test]
643        fn test_get_mut_single_element_list() {
644            let mut list = SingleLinkedList::new();
645            list.push_back(42);
646
647            let mut_ref = list.get_mut(0).unwrap();
648            *mut_ref += 1;
649
650            assert_eq!(
651                *list.get(0).unwrap(),
652                43,
653                "single element should be modified to 43"
654            );
655        }
656
657        #[test]
658        fn test_get_mut_with_complex_types() {
659            // Test with String — modify by pushing more text
660            let mut string_list = SingleLinkedList::new();
661            string_list.push_back("hello".to_string());
662            string_list.push_back("world".to_string());
663
664            let mut_str = string_list.get_mut(0).unwrap();
665            mut_str.push_str(" there");
666
667            assert_eq!(
668                string_list.get(0).unwrap(),
669                "hello there",
670                "first string should be modified"
671            );
672
673            // Test with Vec — modify by adding elements
674            let mut vec_list = SingleLinkedList::new();
675            vec_list.push_back(vec![1, 2]);
676            vec_list.push_back(vec![3, 4]);
677
678            let mut_vec = vec_list.get_mut(1).unwrap();
679            mut_vec.push(5);
680
681            assert_eq!(
682                vec_list.get(1).unwrap(),
683                &vec![3, 4, 5],
684                "second vector should have new element"
685            );
686        }
687
688        #[test]
689        fn test_get_mut_preserves_list_integrity() {
690            let mut list = SingleLinkedList::new();
691            list.push_back(1);
692            list.push_back(2);
693            list.push_back(3);
694
695            // Modify middle element
696            let mut_ref = list.get_mut(1).unwrap();
697            *mut_ref *= 10; // 2 becomes 20
698
699            // Verify list structure is intact
700            assert_eq!(
701                list.len(),
702                3,
703                "list length should remain unchanged after get_mut()"
704            );
705            assert_eq!(list.head(), Some(&1), "head should remain the same");
706            assert_eq!(list.last(), Some(&3), "last should remain the same");
707
708            // Verify other elements are accessible and unchanged
709            assert_eq!(
710                *list.get(0).unwrap(),
711                1,
712                "first element should be unchanged"
713            );
714            assert_eq!(*list.get(2).unwrap(), 3, "last element should be unchanged");
715        }
716
717        #[test]
718        fn test_multiple_get_mut_calls() {
719            let mut list = SingleLinkedList::new();
720            list.push_back(10);
721            list.push_back(20);
722            list.push_back(30);
723
724            // First modification
725            let first = list.get_mut(0).unwrap();
726            *first += 5; // 10 becomes 15
727
728            // Second modification on different element
729            let last = list.get_mut(2).unwrap();
730            *last *= 2; // 30 becomes 60
731
732            // Final verification
733            let values: Vec<i32> = list.iter().copied().collect();
734            assert_eq!(
735                values,
736                vec![15, 20, 60],
737                "all modifications should be applied correctly"
738            );
739        }
740
741        #[test]
742        fn test_get_mut_then_get() {
743            let mut list = SingleLinkedList::new();
744            list.push_back(5);
745            list.push_back(15);
746            list.push_back(25);
747
748            // Modify using get_mut
749            let mid = list.get_mut(1).unwrap();
750            *mid = 99;
751
752            // Immediately read using get
753            let mid_value = list.get(1).unwrap();
754
755            assert_eq!(
756                *mid_value, 99,
757                "get() should reflect changes made by get_mut()"
758            );
759        }
760
761        #[test]
762        fn test_get_mut_error_propagation() {
763            let mut list = SingleLinkedList::new();
764            list.push_back(1);
765            list.push_back(2);
766
767            // Try to get mutable reference to out-of-bounds index
768            let result = list.get_mut(5);
769            assert!(
770                result.is_err(),
771                "get_mut() with out-of-bounds index should return error"
772            );
773
774            // Ensure list is still valid after failed operation
775            assert_eq!(
776                list.len(),
777                2,
778                "list should remain unchanged after failed get_mut()"
779            );
780            assert_eq!(*list.get(0).unwrap(), 1, "first element should remain 1");
781            assert_eq!(*list.get(1).unwrap(), 2, "second element should remain 2");
782        }
783    }
784
785    mod push {
786        use super::*;
787
788        #[test]
789        fn test_push_back() {
790            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
791            assert!(list.is_empty(), "is_empty() returns `false` after creation");
792
793            list.push_back(1);
794            assert_eq!(list.len(), 1, "bad length after push_back()");
795            assert_eq!(list.head(), Some(&1), "incorrect head after push_back()");
796            assert_eq!(list.last(), Some(&1), "incorrect last after push_back()");
797            assert!(
798                !list.is_empty(),
799                "is_empty() returns `true` after push_back()"
800            );
801
802            list.push_back(2);
803            assert_eq!(list.len(), 2, "bad length after push_back()");
804            assert!(list.head().is_some(), "head is None after push_back()");
805            assert_eq!(list.head(), Some(&1), "incorrect head payload");
806            assert_eq!(list.last(), Some(&2), "incorrect last after push_back()");
807            assert!(
808                !list.is_empty(),
809                "is_empty() returns `true` after push_back()"
810            );
811
812            let mut list: SingleLinkedList<String> = SingleLinkedList::new();
813            list.push_back("hello".to_string());
814            assert_eq!(list.len(), 1, "bad length after push_back()");
815            assert!(list.head().is_some(), "head is None after push_back()");
816            assert_eq!(list.head().unwrap(), "hello", "incorrect head payload");
817
818            let mut list: SingleLinkedList<&[char]> = SingleLinkedList::new();
819            list.push_back(&['a', 'b', 'c']);
820            assert_eq!(list.len(), 1, "bad length after push_back()");
821            assert!(list.head().is_some(), "head is None after push_back()");
822            assert_eq!(
823                list.head().unwrap(),
824                &['a', 'b', 'c'],
825                "incorrect head payload"
826            );
827        }
828
829        #[test]
830        fn test_push_to_empty_list_updates_head_and_last() {
831            let mut list = SingleLinkedList::new();
832
833            list.push_back(100);
834            assert_eq!(list.len(), 1);
835            assert_eq!(list.head(), Some(&100));
836            assert_eq!(list.last(), Some(&100));
837
838            let mut list2 = SingleLinkedList::new();
839            list2.push_front(200);
840            assert_eq!(list2.len(), 1);
841            assert_eq!(list2.head(), Some(&200));
842            assert_eq!(list2.last(), Some(&200));
843        }
844
845        #[test]
846        fn test_push_front() {
847            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
848            assert!(list.is_empty(), "is_empty() returns `false` after creation");
849
850            list.push_front(1);
851            assert_eq!(list.len(), 1, "bad length after push_front()");
852            assert_eq!(list.head(), Some(&1), "incorrect head after push_front()");
853            assert_eq!(list.last(), Some(&1), "incorrect last after push_front()");
854            assert!(
855                !list.is_empty(),
856                "is_empty() returns `true` after push_front()"
857            );
858
859            list.push_front(2);
860            assert_eq!(list.len(), 2, "bad length after push_front()");
861            assert!(list.head().is_some(), "head is None after push_front()");
862            assert_eq!(list.head(), Some(&2), "incorrect head payload");
863            assert_eq!(list.last(), Some(&1), "incorrect last after push_front()");
864            assert!(
865                !list.is_empty(),
866                "is_empty() returns `true` after push_front()"
867            );
868
869            let mut list: SingleLinkedList<String> = SingleLinkedList::new();
870            list.push_front("hello".to_string());
871            assert_eq!(list.len(), 1, "bad length after push_front()");
872            assert!(list.head().is_some(), "head is None after push_front()");
873            assert_eq!(list.head().unwrap(), "hello", "incorrect head payload");
874
875            let mut list: SingleLinkedList<&[char]> = SingleLinkedList::new();
876            list.push_front(&['a', 'b', 'c']);
877            assert_eq!(list.len(), 1, "bad length after push_front()");
878            assert!(list.head().is_some(), "head is None after push_front()");
879            assert_eq!(
880                list.head().unwrap(),
881                &['a', 'b', 'c'],
882                "incorrect head payload"
883            );
884        }
885
886        #[test]
887        fn test_mix_push() {
888            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
889            assert!(list.is_empty(), "is_empty() returns `false` after creation");
890
891            list.push_back(1);
892            assert_eq!(list.len(), 1, "bad length after push_back()");
893            assert_eq!(list.head(), Some(&1), "incorrect head after push_back()");
894            assert_eq!(list.last(), Some(&1), "incorrect last after push_back()");
895            assert!(
896                !list.is_empty(),
897                "is_empty() returns `true` after push_back()"
898            );
899
900            list.push_front(2);
901            assert_eq!(list.len(), 2, "bad length after push_front()");
902            assert!(list.head().is_some(), "head is None after push_front()");
903            assert_eq!(list.head(), Some(&2), "incorrect head payload");
904            assert_eq!(list.last(), Some(&1), "incorrect last after push_front()");
905            assert!(
906                !list.is_empty(),
907                "is_empty() returns `true` after push_front()"
908            );
909
910            list.push_back(3);
911            assert_eq!(list.len(), 3, "bad length after push_back()");
912            assert!(list.head().is_some(), "head is None after push_back()");
913            assert_eq!(list.head(), Some(&2), "incorrect head payload");
914            assert_eq!(list.last(), Some(&3), "incorrect last after push_back()");
915            assert!(
916                !list.is_empty(),
917                "is_empty() returns `true` after push_back()"
918            );
919        }
920    }
921
922    mod pop {
923        use super::*;
924
925        #[test]
926        fn test_pop_back_empty_list() {
927            let mut list: SingleLinkedList<u8> = SingleLinkedList::new();
928            assert_eq!(
929                list.pop_back(),
930                None,
931                "pop_back from empty list should return None"
932            );
933            assert!(
934                list.is_empty(),
935                "list should remain empty after pop_back on empty"
936            );
937        }
938
939        #[test]
940        fn test_pop_back_single_element() {
941            let mut list = SingleLinkedList::new();
942            list.push_back(42);
943            assert_eq!(
944                list.pop_back(),
945                Some(42),
946                "pop_back() should return the only element"
947            );
948            assert!(
949                list.is_empty(),
950                "list should be empty after popping the last element"
951            );
952            assert_eq!(
953                list.head(),
954                None,
955                "head should be None after popping last element"
956            );
957            assert_eq!(
958                list.last(),
959                None,
960                "last should be None after popping last element"
961            );
962        }
963
964        #[test]
965        fn test_pop_back_multiple_elements() {
966            let mut list = setup_list(3); // [0, 1, 2]
967            assert_eq!(
968                list.pop_back(),
969                Some(2),
970                "pop_back() should return last element (2)"
971            );
972            assert_eq!(list.len(), 2, "size should decrease by 1 after pop_back()");
973            assert_eq!(list.last(), Some(&1), "new last element should be 1");
974
975            assert_eq!(list.pop_back(), Some(1), "pop_back() should return 1 next");
976            assert_eq!(list.len(), 1, "size should be 1 after second pop_back()");
977            assert_eq!(list.head(), Some(&0), "head should still be 0");
978            assert_eq!(list.last(), Some(&0), "last should now be 0");
979
980            assert_eq!(
981                list.pop_back(),
982                Some(0),
983                "pop_back() should return 0 finally"
984            );
985            assert!(list.is_empty(), "list should be empty after all pop-backs");
986        }
987
988        #[test]
989        fn test_pop_front_empty_list() {
990            let mut list = SingleLinkedList::<u8>::new();
991            assert_eq!(
992                list.pop_front(),
993                None,
994                "pop_front() from empty list should return None"
995            );
996            assert!(
997                list.is_empty(),
998                "list should remain empty after pop_front() on empty"
999            );
1000        }
1001
1002        #[test]
1003        fn test_pop_front_single_element() {
1004            let mut list = SingleLinkedList::new();
1005            list.push_front(99);
1006            assert_eq!(
1007                list.pop_front(),
1008                Some(99),
1009                "pop_front() should return the only element"
1010            );
1011            assert!(
1012                list.is_empty(),
1013                "list should be empty after popping the only element"
1014            );
1015            assert_eq!(list.head(), None, "head should be None after pop");
1016            assert_eq!(list.last(), None, "last should be None after pop");
1017        }
1018
1019        #[test]
1020        fn test_pop_front_multiple_elements() {
1021            let mut list = setup_list(3); // [0, 1, 2]
1022            assert_eq!(
1023                list.pop_front(),
1024                Some(0),
1025                "pop_front should return first element (0)"
1026            );
1027            assert_eq!(list.len(), 2, "size should decrease by 1 after pop_front");
1028            assert_eq!(list.head(), Some(&1), "new head should be 1");
1029            assert_eq!(list.last(), Some(&2), "last should remain 2");
1030
1031            assert_eq!(list.pop_front(), Some(1), "pop_front should return 1 next");
1032            assert_eq!(list.len(), 1, "size should be 1 after second pop_front");
1033            assert_eq!(list.head(), Some(&2), "head should now be 2");
1034            assert_eq!(list.last(), Some(&2), "last should also be 2");
1035
1036            assert_eq!(
1037                list.pop_front(),
1038                Some(2),
1039                "pop_front should return 2 finally"
1040            );
1041            assert!(list.is_empty(), "list should be empty after all pop_fronts");
1042        }
1043    }
1044
1045    mod mixed {
1046        use super::*;
1047
1048        #[test]
1049        fn test_mixed_push_pop_operations() {
1050            let mut list = SingleLinkedList::new();
1051
1052            list.push_back(1);
1053            list.push_front(0);
1054            list.push_back(2);
1055
1056            // List: [0, 1, 2]
1057            assert_eq!(list.len(), 3);
1058            assert_eq!(list.head(), Some(&0));
1059            assert_eq!(list.last(), Some(&2));
1060
1061            assert_eq!(list.pop_front(), Some(0));
1062            assert_eq!(list.pop_back(), Some(2));
1063            assert_eq!(list.pop_front(), Some(1));
1064            assert!(list.is_empty());
1065
1066            // Try one more pop
1067            assert_eq!(list.pop_back(), None);
1068            assert_eq!(list.pop_front(), None);
1069        }
1070
1071        #[test]
1072        fn test_size_consistency_after_operations() {
1073            let mut list = SingleLinkedList::new();
1074
1075            // Push back
1076            list.push_back(10);
1077            assert_eq!(list.len(), 1, "size after push_back(10) should be 1");
1078
1079            list.push_back(20);
1080            assert_eq!(list.len(), 2, "size after second push_back should be 2");
1081
1082            // Pop back
1083            list.pop_back();
1084            assert_eq!(list.len(), 1, "size after pop_back should be 1");
1085
1086            // Push front
1087            list.push_front(5);
1088            assert_eq!(list.len(), 2, "size after push_front(5) should be 2");
1089
1090            // Pop front
1091            list.pop_front();
1092            assert_eq!(list.len(), 1, "size after pop_front should be 1");
1093
1094            // Final pop
1095            list.pop_back();
1096            assert_eq!(list.len(), 0, "size should be 0 after all pops");
1097            assert!(list.is_empty(), "list should be empty");
1098        }
1099
1100        #[test]
1101        fn test_head_last_consistency_after_mixed_operations() {
1102            let mut list = SingleLinkedList::new();
1103
1104            // Start: empty
1105            assert_eq!(list.head(), None);
1106            assert_eq!(list.last(), None);
1107
1108            // push_back(1)
1109            list.push_back(1);
1110            assert_eq!(list.head(), Some(&1));
1111            assert_eq!(list.last(), Some(&1));
1112
1113            // push_front(0)
1114            list.push_front(0);
1115            assert_eq!(list.head(), Some(&0));
1116            assert_eq!(list.last(), Some(&1));
1117
1118            // push_back(2)
1119            list.push_back(2);
1120            assert_eq!(list.head(), Some(&0));
1121            assert_eq!(list.last(), Some(&2));
1122
1123            // pop_front() → removes 0
1124            list.pop_front();
1125            assert_eq!(list.head(), Some(&1));
1126            assert_eq!(list.last(), Some(&2));
1127
1128            // pop_back() → removes 2
1129            list.pop_back();
1130            assert_eq!(list.head(), Some(&1));
1131            assert_eq!(list.last(), Some(&1));
1132
1133            // Final pop
1134            list.pop_front();
1135            assert_eq!(list.head(), None);
1136            assert_eq!(list.last(), None);
1137            assert!(list.is_empty());
1138        }
1139    }
1140
1141    mod complex_types {
1142        use super::*;
1143
1144        #[test]
1145        fn test_complex_types_string() {
1146            let mut list = SingleLinkedList::new();
1147            list.push_back("hello".to_string());
1148            list.push_back("world".to_string());
1149
1150            assert_eq!(list.len(), 2);
1151            assert_eq!(list.head().unwrap(), "hello");
1152            assert_eq!(list.last().unwrap(), "world");
1153
1154            assert_eq!(list.pop_front().unwrap(), "hello".to_string());
1155            assert_eq!(list.pop_back().unwrap(), "world".to_string());
1156            assert!(list.is_empty());
1157        }
1158
1159        #[test]
1160        fn test_complex_types_vec() {
1161            let mut list = SingleLinkedList::new();
1162            list.push_back(vec![1, 2]);
1163            list.push_back(vec![3, 4]);
1164
1165            assert_eq!(list.len(), 2);
1166            assert_eq!(list.head().unwrap(), &vec![1, 2]);
1167            assert_eq!(list.last().unwrap(), &vec![3, 4]);
1168
1169            let popped_front = list.pop_front().unwrap();
1170            assert_eq!(popped_front, vec![1, 2]);
1171
1172            let popped_back = list.pop_back().unwrap();
1173            assert_eq!(popped_back, vec![3, 4]);
1174            assert!(list.is_empty());
1175        }
1176    }
1177
1178    mod insert {
1179        use super::*;
1180
1181        #[test]
1182        fn test_insert_at_beginning_empty_list() {
1183            let mut list = SingleLinkedList::new();
1184            assert!(
1185                list.insert(0, 42).is_ok(),
1186                "insert at index 0 in empty list should succeed"
1187            );
1188            assert_eq!(list.len(), 1, "list size should be 1 after insertion");
1189            assert_eq!(list.head(), Some(&42), "head should contain inserted value");
1190            assert_eq!(list.last(), Some(&42), "last should contain inserted value");
1191        }
1192
1193        #[test]
1194        fn test_insert_at_beginning_non_empty_list() {
1195            let mut list = setup_list(3); // [0, 1, 2]
1196            assert!(
1197                list.insert(0, 99).is_ok(),
1198                "insert at beginning should succeed"
1199            );
1200            assert_eq!(list.len(), 4, "size should increase by 1");
1201            assert_eq!(list.head(), Some(&99), "new head should be 99");
1202            assert_eq!(list.find(&99), Some(0), "find should locate 99 at index 0");
1203        }
1204
1205        #[test]
1206        fn test_insert_at_end() {
1207            let mut list = setup_list(2); // [0, 1]
1208            assert!(
1209                list.insert(2, 999).is_ok(),
1210                "insert at end (index == size) should succeed"
1211            );
1212            assert_eq!(list.len(), 3, "size should increase by 1");
1213            assert_eq!(list.last(), Some(&999), "last element should be 999");
1214            assert_eq!(
1215                list.find(&999),
1216                Some(2),
1217                "find should locate 999 at index 2"
1218            );
1219        }
1220
1221        #[test]
1222        fn test_insert_in_middle() {
1223            let mut list = setup_list(3); // [0, 1, 2]
1224            assert!(
1225                list.insert(1, 50).is_ok(),
1226                "insert in middle should succeed"
1227            );
1228            assert_eq!(list.len(), 4, "size should increase by 1");
1229
1230            // Verify the order: [0, 50, 1, 2]
1231            let mut iter = list.iter();
1232            assert_eq!(iter.next(), Some(&0));
1233            assert_eq!(iter.next(), Some(&50));
1234            assert_eq!(iter.next(), Some(&1));
1235            assert_eq!(iter.next(), Some(&2));
1236        }
1237
1238        #[test]
1239        fn test_insert_out_of_bounds() {
1240            let mut list = setup_list(2); // [0, 1]
1241
1242            // Index greater than size
1243            assert!(
1244                list.insert(3, 42).is_err(),
1245                "insert with index > size should return error"
1246            );
1247
1248            // Very large index
1249            assert!(
1250                list.insert(100, 42).is_err(),
1251                "insert with large out-of-bounds index should return error"
1252            );
1253
1254            // Empty list with non-zero index
1255            let mut empty_list = SingleLinkedList::new();
1256            assert!(
1257                empty_list.insert(1, 42).is_err(),
1258                "insert to empty list with index > 0 should return error"
1259            );
1260        }
1261
1262        #[test]
1263        fn test_insert_with_complex_types_string() {
1264            let mut list = SingleLinkedList::new();
1265            list.push_back("first".to_string());
1266            list.push_back("third".to_string());
1267
1268            assert!(
1269                list.insert(1, "second".to_string()).is_ok(),
1270                "insert string in middle should succeed"
1271            );
1272            assert_eq!(list.len(), 3, "size should be 3 after insertion");
1273
1274            // Verify order: ["first", "second", "third"]
1275            let values: Vec<String> = list.iter().map(|payload| payload.clone()).collect();
1276            assert_eq!(values, vec!["first", "second", "third"]);
1277        }
1278
1279        #[test]
1280        fn test_insert_multiple_times() {
1281            let mut list = SingleLinkedList::new();
1282
1283            // Insert at various positions multiple times
1284            assert!(list.insert(0, 10).is_ok());
1285            assert!(list.insert(1, 30).is_ok());
1286            assert!(list.insert(1, 20).is_ok()); // Insert between 10 and 30
1287
1288            assert_eq!(list.len(), 3, "final size should be 3");
1289
1290            // Expected order: [10, 20, 30]
1291            let mut iter = list.iter();
1292            assert_eq!(iter.next(), Some(&10));
1293            assert_eq!(iter.next(), Some(&20));
1294            assert_eq!(iter.next(), Some(&30));
1295        }
1296
1297        #[test]
1298        fn test_insert_preserves_head_and_last_pointers() {
1299            let mut list = setup_list(2); // [0, 1]
1300
1301            // Insert in the middle
1302            assert!(list.insert(1, 5).is_ok());
1303
1304            // Head should still be the first element
1305            assert_eq!(list.head(), Some(&0), "head pointer should remain correct");
1306
1307            // Last should still be the last element
1308            assert_eq!(list.last(), Some(&1), "last pointer should remain correct");
1309        }
1310
1311        #[test]
1312        fn test_insert_edge_cases() {
1313            // Test inserting into a list with one element
1314            let mut single_element = SingleLinkedList::new();
1315            single_element.push_back(100);
1316
1317            // Insert at beginning (should work)
1318            assert!(single_element.insert(0, 50).is_ok());
1319            assert_eq!(single_element.find(&50), Some(0));
1320            assert_eq!(single_element.find(&100), Some(1));
1321
1322            // Insert at end (should work)
1323            assert!(single_element.insert(2, 150).is_ok());
1324            assert_eq!(single_element.find(&150), Some(2));
1325        }
1326    }
1327
1328    mod remove {
1329        use super::*;
1330
1331        #[test]
1332        fn test_remove_from_empty_list() {
1333            let mut list = SingleLinkedList::<u8>::new();
1334            assert!(
1335                list.remove(0).is_err(),
1336                "remove from empty list should return error"
1337            );
1338            assert_eq!(list.len(), 0, "size should remain 0");
1339        }
1340
1341        #[test]
1342        fn test_remove_first_element() {
1343            let mut list = setup_list(3); // [0, 1, 2]
1344            let removed = list.remove(0).unwrap();
1345            assert_eq!(removed, 0, "removed value should be 0 (first element)");
1346            assert_eq!(list.len(), 2, "size should decrease by 1");
1347            assert_eq!(list.head(), Some(&1), "new head should be 1");
1348            assert_eq!(list.find(&0), None, "0 should no longer be in the list");
1349        }
1350
1351        #[test]
1352        fn test_remove_last_element() {
1353            let mut list = setup_list(3); // [0, 1, 2]
1354            let removed = list.remove(2).unwrap(); // index = size - 1
1355            assert_eq!(removed, 2, "removed value should be 2 (last element)");
1356            assert_eq!(list.len(), 2, "size should decrease by 1");
1357            assert_eq!(list.last(), Some(&1), "new last should be 1");
1358            assert_eq!(list.find(&2), None, "2 should no longer be in the list");
1359        }
1360
1361        #[test]
1362        fn test_remove_middle_element() {
1363            let mut list = setup_list(4); // [0, 1, 2, 3]
1364            let removed = list.remove(1).unwrap(); // remove element at index 1 (value 1)
1365            assert_eq!(removed, 1, "removed value should be 1");
1366            assert_eq!(list.len(), 3, "size should decrease by 1");
1367
1368            // Verify the order: [0, 2, 3]
1369            let values: Vec<usize> = list.iter().copied().collect();
1370            assert_eq!(
1371                values,
1372                vec![0, 2, 3],
1373                "list should have correct order after removal"
1374            );
1375        }
1376
1377        #[test]
1378        fn test_remove_out_of_bounds() {
1379            let mut list = setup_list(2); // [0, 1]
1380
1381            // Index equal to size (should be out of bounds)
1382            assert!(
1383                list.remove(2).is_err(),
1384                "remove with index == size should return error"
1385            );
1386
1387            // Index greater than size
1388            assert!(
1389                list.remove(5).is_err(),
1390                "remove with large out-of-bounds index should return error"
1391            );
1392
1393            // Empty list
1394            let mut empty_list = SingleLinkedList::<u8>::new();
1395            assert!(
1396                empty_list.remove(0).is_err(),
1397                "remove from empty list should return error"
1398            );
1399        }
1400
1401        #[test]
1402        fn test_remove_single_element_list() {
1403            let mut list = SingleLinkedList::new();
1404            list.push_back(42);
1405            let removed = list.remove(0).unwrap();
1406            assert_eq!(removed, 42, "removed value should be 42");
1407            assert!(
1408                list.is_empty(),
1409                "list should be empty after removing the only element"
1410            );
1411            assert_eq!(list.head(), None, "head should be None");
1412            assert_eq!(list.last(), None, "last should be None");
1413        }
1414
1415        #[test]
1416        fn test_remove_preserves_head_and_last_pointers() {
1417            let mut list = setup_list(4); // [0, 1, 2, 3]
1418
1419            // Remove middle element (index 1, value 1)
1420            let _ = list.remove(1);
1421
1422            assert_eq!(list.head(), Some(&0), "head pointer should remain correct");
1423            assert_eq!(list.last(), Some(&3), "last pointer should remain correct");
1424        }
1425
1426        #[test]
1427        fn test_multiple_removes() {
1428            let mut list = setup_list(5); // [0, 1, 2, 3, 4]
1429
1430            // Remove second element (index 1, value 1)
1431            let removed1 = list.remove(1).unwrap();
1432            assert_eq!(removed1, 1);
1433            assert_eq!(list.len(), 4);
1434
1435            // Remove new second element (was 2, now at index 1)
1436            let removed2 = list.remove(1).unwrap();
1437            assert_eq!(removed2, 2);
1438            assert_eq!(list.len(), 3);
1439
1440            // Final state should be [0, 3, 4]
1441            let final_values: Vec<usize> = list.iter().copied().collect();
1442            assert_eq!(
1443                final_values,
1444                vec![0, 3, 4],
1445                "list should have correct values after multiple removes"
1446            );
1447        }
1448
1449        #[test]
1450        fn test_remove_with_complex_types_string() {
1451            let mut list = SingleLinkedList::new();
1452            list.push_back("first".to_string());
1453            list.push_back("second".to_string());
1454            list.push_back("third".to_string());
1455
1456            let removed = list.remove(1).unwrap(); // Remove "second"
1457            assert_eq!(
1458                removed,
1459                "second".to_string(),
1460                "removed value should be 'second'"
1461            );
1462            assert_eq!(list.len(), 2, "size should be 2 after removal");
1463
1464            // Verify order: ["first", "third"]
1465            let remaining: Vec<String> = list.iter().map(|s| s.clone()).collect();
1466            assert_eq!(remaining, vec!["first", "third"]);
1467        }
1468
1469        #[test]
1470        fn test_remove_edge_cases() {
1471            // Test removing from a list with two elements
1472            let mut two_elements = SingleLinkedList::new();
1473            two_elements.push_back(10);
1474            two_elements.push_back(20);
1475
1476            // Remove first (index 0)
1477            let removed_first = two_elements.remove(0).unwrap();
1478            assert_eq!(removed_first, 10);
1479            assert_eq!(two_elements.len(), 1);
1480            assert_eq!(two_elements.head(), Some(&20));
1481
1482            // Now remove the last (only remaining) element
1483            let removed_last = two_elements.remove(0).unwrap();
1484            assert_eq!(removed_last, 20);
1485            assert!(two_elements.is_empty());
1486        }
1487    }
1488
1489    mod clear {
1490        use super::*;
1491
1492        #[test]
1493        fn test_clear_empty_list() {
1494            let mut list = SingleLinkedList::<u8>::new();
1495            assert!(list.is_empty(), "list should be empty initially");
1496
1497            list.clear();
1498
1499            assert!(
1500                list.is_empty(),
1501                "clear() on empty list should leave it empty"
1502            );
1503            assert_eq!(
1504                list.len(),
1505                0,
1506                "length should remain 0 after clear() on empty list"
1507            );
1508            assert_eq!(
1509                list.head(),
1510                None,
1511                "head should be None after clear() on empty list"
1512            );
1513            assert_eq!(
1514                list.last(),
1515                None,
1516                "last should be None after clear() on empty list"
1517            );
1518        }
1519
1520        #[test]
1521        fn test_clear_single_element_list() {
1522            let mut list = SingleLinkedList::new();
1523            list.push_back(42);
1524            assert!(!list.is_empty(), "list should not be empty before clear()");
1525            assert_eq!(list.len(), 1, "list should have length 1 before clear()");
1526
1527            list.clear();
1528
1529            assert!(list.is_empty(), "list should be empty after clear()");
1530            assert_eq!(list.len(), 0, "length should be 0 after clear()");
1531            assert_eq!(list.head(), None, "head should be None after clear()");
1532            assert_eq!(list.last(), None, "last should be None after clear()");
1533        }
1534
1535        #[test]
1536        fn test_clear_multiple_elements_list() {
1537            let mut list = SingleLinkedList::new();
1538            list.push_back(10);
1539            list.push_back(20);
1540            list.push_back(30);
1541            assert_eq!(list.len(), 3, "list should have 3 elements before clear()");
1542
1543            list.clear();
1544
1545            assert!(
1546                list.is_empty(),
1547                "list should be empty after clearing multiple elements"
1548            );
1549            assert_eq!(
1550                list.len(),
1551                0,
1552                "length should be 0 after clearing multiple elements"
1553            );
1554            assert_eq!(
1555                list.head(),
1556                None,
1557                "head should be None after clearing multiple elements"
1558            );
1559            assert_eq!(
1560                list.last(),
1561                None,
1562                "last should be None after clearing multiple elements"
1563            );
1564        }
1565
1566        #[test]
1567        fn test_clear_then_reuse_list() {
1568            let mut list = SingleLinkedList::new();
1569            list.push_back(1);
1570            list.push_back(2);
1571
1572            list.clear();
1573            assert!(list.is_empty(), "list should be empty after clear()");
1574
1575            // Reuse the list after clearing
1576            list.push_back(100);
1577            list.push_back(200);
1578
1579            assert_eq!(
1580                list.len(),
1581                2,
1582                "list should accept new elements after clear()"
1583            );
1584            assert_eq!(*list.head().unwrap(), 100, "new head should be 100");
1585            assert_eq!(*list.last().unwrap(), 200, "new last should be 200");
1586        }
1587
1588        #[test]
1589        fn test_clear_with_complex_types() {
1590            // Test with String
1591            let mut string_list = SingleLinkedList::new();
1592            string_list.push_back("apple".to_string());
1593            string_list.push_back("banana".to_string());
1594
1595            string_list.clear();
1596            assert!(
1597                string_list.is_empty(),
1598                "string list should be empty after clear()"
1599            );
1600            assert_eq!(
1601                string_list.len(),
1602                0,
1603                "string list length should be 0 after clear()"
1604            );
1605
1606            // Test with Vec
1607            let mut vec_list = SingleLinkedList::new();
1608            vec_list.push_back(vec![1, 2]);
1609            vec_list.push_back(vec![3, 4]);
1610
1611            vec_list.clear();
1612            assert!(
1613                vec_list.is_empty(),
1614                "vec list should be empty after clear()"
1615            );
1616            assert_eq!(
1617                vec_list.len(),
1618                0,
1619                "vec list length should be 0 after clear()"
1620            );
1621        }
1622
1623        #[test]
1624        fn test_clear_preserves_list_integrity() {
1625            let mut list = SingleLinkedList::new();
1626            list.push_back(5);
1627            list.push_back(10);
1628            list.push_back(15);
1629
1630            let initial_len = list.len();
1631            let head_before = list.head().cloned();
1632            let last_before = list.last().cloned();
1633            assert_eq!(initial_len, 3);
1634            assert_eq!(head_before.unwrap(), 5);
1635            assert_eq!(last_before.unwrap(), 15);
1636
1637            list.clear();
1638
1639            // Verify the list is properly cleared
1640            assert!(list.is_empty(), "list should be empty after clear()");
1641            assert_eq!(list.len(), 0, "length should be 0 after clear()");
1642            assert_eq!(list.head(), None, "head should be None after clear()");
1643            assert_eq!(list.last(), None, "last should be None after clear()");
1644
1645            // Ensure we can create a new list and it works correctly
1646            let mut new_list = SingleLinkedList::new();
1647            new_list.push_back(100);
1648            assert_eq!(
1649                new_list.len(),
1650                1,
1651                "new list should work correctly after previous clear()"
1652            );
1653        }
1654
1655        #[test]
1656        fn test_clear_performance_consistency() {
1657            // Test that clear() works correctly regardless of list size
1658            for size in &[0, 1, 5, 10, 100] {
1659                let mut list = SingleLinkedList::new();
1660
1661                // Fill list with values
1662                for i in 0..*size {
1663                    list.push_back(i);
1664                }
1665
1666                assert_eq!(
1667                    list.len(),
1668                    *size,
1669                    "list should have correct length before clear() for size {}",
1670                    size
1671                );
1672
1673                list.clear();
1674
1675                assert!(
1676                    list.is_empty(),
1677                    "list of size {} should be empty after clear()",
1678                    size
1679                );
1680                assert_eq!(
1681                    list.len(),
1682                    0,
1683                    "list of size {} should have length 0 after clear()",
1684                    size
1685                );
1686                assert_eq!(
1687                    list.head(),
1688                    None,
1689                    "head should be None for cleared list of size {}",
1690                    size
1691                );
1692                assert_eq!(
1693                    list.last(),
1694                    None,
1695                    "last should be None for cleared list of size {}",
1696                    size
1697                );
1698            }
1699        }
1700
1701        #[test]
1702        fn test_clear_after_mixed_operations() {
1703            let mut list = SingleLinkedList::new();
1704
1705            // Perform various operations
1706            list.push_back(1);
1707            list.push_front(0);
1708            list.push_back(2);
1709            list.pop_front(); // removes 0
1710            list.push_back(3);
1711
1712            // List should now be [1, 2, 3]
1713            assert_eq!(
1714                list.len(),
1715                3,
1716                "list should have 3 elements after mixed operations"
1717            );
1718            assert_eq!(
1719                *list.head().unwrap(),
1720                1,
1721                "head should be 1 after mixed operations"
1722            );
1723            assert_eq!(
1724                *list.last().unwrap(),
1725                3,
1726                "last should be 3 after mixed operations"
1727            );
1728
1729            list.clear();
1730
1731            assert!(
1732                list.is_empty(),
1733                "list should be empty after clear() following mixed operations"
1734            );
1735            assert_eq!(
1736                list.len(),
1737                0,
1738                "length should be 0 after clear() following mixed operations"
1739            );
1740            assert_eq!(
1741                list.head(),
1742                None,
1743                "head should be None after clear() following mixed operations"
1744            );
1745            assert_eq!(
1746                list.last(),
1747                None,
1748                "last should be None after clear() following mixed operations"
1749            );
1750        }
1751    }
1752
1753    mod sort {
1754        use super::*;
1755
1756        #[test]
1757        fn test_sort_empty_list() {
1758            let mut list = SingleLinkedList::<i32>::new();
1759            assert_eq!(list.len(), 0, "list should be empty initially");
1760
1761            list.sort();
1762
1763            assert_eq!(list.len(), 0, "empty list should remain empty after sort()");
1764            assert!(list.is_empty(), "empty list should be empty after sort()");
1765        }
1766
1767        #[test]
1768        fn test_sort_single_element() {
1769            let mut list = SingleLinkedList::new();
1770            list.push_back(42);
1771            assert_eq!(list.len(), 1, "list should have one element");
1772
1773            list.sort();
1774
1775            assert_eq!(list.len(), 1, "single element list should have same length after sort()");
1776            let values = list.to_vec();
1777            assert_eq!(values, vec![42], "single element should remain unchanged");
1778        }
1779
1780        #[test]
1781        fn test_sort_already_sorted() {
1782            let mut list = SingleLinkedList::from_slice(&[1, 2, 3, 4, 5]);
1783            assert_eq!(list.len(), 5, "list should have 5 elements");
1784
1785            list.sort();
1786
1787            let values = list.to_vec();
1788            assert_eq!(values, vec![1, 2, 3, 4, 5], "already sorted list should remain sorted");
1789        }
1790
1791        #[test]
1792        fn test_sort_reverse_sorted() {
1793            let mut list = SingleLinkedList::from_slice(&[5, 4, 3, 2, 1]);
1794            assert_eq!(list.len(), 5, "list should have 5 elements");
1795
1796            list.sort();
1797
1798            let values = list.to_vec();
1799            assert_eq!(values, vec![1, 2, 3, 4, 5], "reverse sorted list should become ascending");
1800        }
1801
1802        #[test]
1803        fn test_sort_random_order() {
1804            let mut list = SingleLinkedList::from_slice(&[3, 1, 4, 1, 5, 9, 2, 6]);
1805            assert_eq!(list.len(), 8, "list should have 8 elements");
1806
1807            list.sort();
1808
1809            let values = list.to_vec();
1810            assert_eq!(values, vec![1, 1, 2, 3, 4, 5, 6, 9], "random order list should be sorted correctly");
1811        }
1812
1813        #[test]
1814        fn test_sort_with_duplicates() {
1815            let mut list = SingleLinkedList::from_slice(&[2, 2, 1, 1, 3, 3]);
1816            assert_eq!(list.len(), 6, "list should have 6 elements");
1817
1818            list.sort();
1819
1820            let values = list.to_vec();
1821            assert_eq!(values, vec![1, 1, 2, 2, 3, 3], "list with duplicates should be sorted with duplicates preserved");
1822        }
1823
1824        #[test]
1825        fn test_sort_two_elements_unsorted() {
1826            let mut list = SingleLinkedList::from_slice(&[2, 1]);
1827            assert_eq!(list.len(), 2, "list should have 2 elements");
1828
1829            list.sort();
1830
1831            let values = list.to_vec();
1832            assert_eq!(values, vec![1, 2], "two elements should be sorted in ascending order");
1833        }
1834
1835        #[test]
1836        fn test_sort_two_elements_sorted() {
1837            let mut list = SingleLinkedList::from_slice(&[1, 2]);
1838            assert_eq!(list.len(), 2, "list should have 2 elements");
1839
1840            list.sort();
1841
1842            let values = list.to_vec();
1843            assert_eq!(values, vec![1, 2], "already sorted two elements should remain the same");
1844        }
1845
1846        #[test]
1847        fn test_sort_large_list() {
1848            // Create a large list with random-like pattern
1849            let mut data: Vec<i32> = (1..=1000).collect();
1850            // Shuffle by reversing every 10 elements
1851            for chunk in data.chunks_mut(10) {
1852                chunk.reverse();
1853            }
1854
1855            let mut list = SingleLinkedList::new();
1856            for &value in &data {
1857                list.push_back(value);
1858            }
1859
1860            assert_eq!(list.len(), 1000, "large list should have 1000 elements");
1861
1862            list.sort();
1863
1864            let sorted_data: Vec<i32> = (1..=1000).collect();
1865            let values = list.to_vec();
1866            assert_eq!(values, sorted_data, "large list should be sorted correctly");
1867        }
1868
1869        #[test]
1870        fn test_sort_after_operations() {
1871            let mut list = SingleLinkedList::new();
1872
1873            // Perform various operations
1874            list.push_back(5);
1875            list.push_front(1);
1876            list.push_back(3);
1877            list.pop_front(); // removes 1
1878            list.push_back(2);
1879
1880            // List should now be [5, 3, 2]
1881            assert_eq!(list.len(), 3, "list should have 3 elements after mixed operations");
1882
1883            list.sort();
1884
1885            let values = list.to_vec();
1886            assert_eq!(values, vec![2, 3, 5], "list after mixed operations should be sorted correctly");
1887        }
1888
1889        #[test]
1890        fn test_sort_string_list() {
1891            let mut list = SingleLinkedList::new();
1892            list.push_back("zebra".to_string());
1893            list.push_back("apple".to_string());
1894            list.push_back("banana".to_string());
1895            list.push_back("cherry".to_string());
1896
1897            assert_eq!(list.len(), 4, "string list should have 4 elements");
1898
1899            list.sort();
1900
1901            let values: Vec<String> = list.into_iter().collect();
1902
1903            assert_eq!(
1904                values,
1905                vec!["apple".to_string(), "banana".to_string(), "cherry".to_string(), "zebra".to_string()],
1906                "string list should be sorted alphabetically"
1907            );
1908        }
1909
1910        #[test]
1911        fn test_sort_preserves_last_pointer() {
1912            let mut list = SingleLinkedList::from_slice(&[3, 1, 4, 2]);
1913
1914            list.sort();
1915
1916            // Verify that last pointer is correctly set to the last node
1917            let last_value = unsafe { (*list.last).payload };
1918            assert_eq!(last_value, 4, "last pointer should point to the maximum element after sorting");
1919        }
1920    }
1921
1922    mod memory_leaks {
1923        use super::*;
1924        use drop_tracker::DropTracker;
1925
1926        #[test]
1927        fn test_memory_leaks() {
1928            let mut tracker = DropTracker::new();
1929
1930            let mut list = SingleLinkedList::new();
1931            for i in 0..100 {
1932                list.push_back(tracker.track(i));
1933            }
1934            for i in 100..111 {
1935                list.push_front(tracker.track(i));
1936            }
1937
1938            assert_eq!(tracker.alive().count(), 111);
1939
1940            drop(list);
1941
1942            assert_eq!(tracker.alive().count(), 0);
1943            assert_eq!(tracker.dropped().count(), 111);
1944        }
1945
1946        #[test]
1947        fn test_iterators_with_drop_tracker() {
1948            let mut tracker = DropTracker::new();
1949
1950            let mut list = SingleLinkedList::new();
1951            for i in 0..5 {
1952                list.push_back(tracker.track(i));
1953            }
1954
1955            assert_eq!(tracker.alive().count(), 5);
1956
1957            // Use all types of iterators sequentially
1958            {
1959                // Итератор по ссылкам
1960                let ref_count: usize = list.iter().count();
1961                assert_eq!(ref_count, 5);
1962            }
1963            {
1964                // Mutable iterator (modify all elements)
1965                for item in list.iter_mut() {
1966                    **item += 10;
1967                }
1968            }
1969            {
1970                // IntoIterator — take ownership
1971                let collected: Vec<_> = list.into_iter().collect();
1972                assert_eq!(collected, vec![10, 11, 12, 13, 14]);
1973            }
1974
1975            // After IntoIterator the list is destroyed
1976            assert_eq!(tracker.alive().count(), 0);
1977            assert_eq!(tracker.dropped().count(), 5);
1978        }
1979
1980        #[test]
1981        fn test_memory_leaks_with_remove_operations() {
1982            let mut tracker = DropTracker::new();
1983
1984            let mut list = SingleLinkedList::new();
1985            for i in 0..50 {
1986                list.push_back(tracker.track(i));
1987            }
1988
1989            assert_eq!(
1990                tracker.alive().count(),
1991                50,
1992                "50 elements should be alive after push_back"
1993            );
1994
1995            // Removing elements from different positions
1996            assert_eq!(list.remove(0).unwrap(), 0);
1997            assert_eq!(list.remove(48).unwrap(), 49); // last item
1998            assert_eq!(list.remove(24).unwrap(), 25); // middle item
1999
2000            assert_eq!(
2001                tracker.alive().count(),
2002                47,
2003                "After removing 3 elements, 47 should remain alive"
2004            );
2005
2006            // Clear the list completely
2007            while list.len() > 0 {
2008                let _ = list.pop_front();
2009            }
2010
2011            assert_eq!(
2012                tracker.alive().count(),
2013                0,
2014                "All elements should be dropped after clearing the list"
2015            );
2016            assert_eq!(
2017                tracker.dropped().count(),
2018                50,
2019                "All 50 elements should have been dropped"
2020            );
2021        }
2022
2023        #[test]
2024        fn test_memory_leaks_with_insert_operations() {
2025            let mut tracker = DropTracker::new();
2026
2027            let mut list = SingleLinkedList::new();
2028            list.push_back(tracker.track(1));
2029            list.push_back(tracker.track(3));
2030
2031            assert_eq!(
2032                tracker.alive().count(),
2033                2,
2034                "2 elements should be alive initially"
2035            );
2036
2037            // Insert an element into the middle
2038            list.insert(1, tracker.track(2)).unwrap();
2039
2040            assert_eq!(
2041                tracker.alive().count(),
2042                3,
2043                "3 elements should be alive after insert"
2044            );
2045
2046            // Insert at the beginning and end
2047            list.insert(0, tracker.track(0)).unwrap();
2048            list.insert(3, tracker.track(4)).unwrap();
2049
2050            assert_eq!(
2051                tracker.alive().count(),
2052                5,
2053                "5 elements should be alive after all inserts"
2054            );
2055
2056            drop(list);
2057
2058            assert_eq!(
2059                tracker.alive().count(),
2060                0,
2061                "All elements should be dropped when list is dropped"
2062            );
2063            assert_eq!(
2064                tracker.dropped().count(),
2065                5,
2066                "All 5 elements should have been dropped"
2067            );
2068        }
2069
2070        #[test]
2071        fn test_memory_leaks_partial_operations() {
2072            let mut tracker = DropTracker::new();
2073
2074            let mut list = SingleLinkedList::new();
2075            for i in 0..20 {
2076                list.push_back(tracker.track(i));
2077            }
2078
2079            assert_eq!(tracker.alive().count(), 20, "20 elements should be alive");
2080
2081            // Perform several deletion and addition operations
2082            for _ in 0..5 {
2083                let _ = list.pop_back();
2084            }
2085            for i in 100..103 {
2086                list.push_front(tracker.track(i));
2087            }
2088
2089            assert!(
2090                tracker.alive().count() < 20,
2091                "Fewer elements should be alive after partial operations"
2092            );
2093
2094            drop(list);
2095
2096            assert_eq!(
2097                tracker.alive().count(),
2098                0,
2099                "All remaining elements should be dropped"
2100            );
2101            assert_eq!(
2102                tracker.dropped().count(),
2103                23,
2104                "Total 23 elements should have been dropped (20 original + 3 added - 5 removed)"
2105            );
2106        }
2107
2108        #[test]
2109        fn test_memory_leaks_with_complex_types() {
2110            let mut tracker = DropTracker::new();
2111
2112            #[derive(Debug, PartialEq, Eq, Hash, Clone)]
2113            struct ComplexStruct {
2114                id: usize,
2115                data: String,
2116            }
2117
2118            impl Drop for ComplexStruct {
2119                fn drop(&mut self) {
2120                    // Just mark the deletion
2121                }
2122            }
2123
2124            let mut list = SingleLinkedList::new();
2125            for i in 0..15 {
2126                list.push_back(tracker.track(ComplexStruct {
2127                    id: i,
2128                    data: format!("data_{}", i),
2129                }));
2130            }
2131
2132            assert_eq!(
2133                tracker.alive().count(),
2134                15,
2135                "15 ComplexStruct elements should be alive"
2136            );
2137
2138            // Deleting multiple elements
2139            for _ in 0..3 {
2140                let _ = list.pop_front();
2141            }
2142
2143            assert_eq!(
2144                tracker.alive().count(),
2145                12,
2146                "12 ComplexStruct elements should remain alive"
2147            );
2148
2149            drop(list);
2150
2151            assert_eq!(
2152                tracker.alive().count(),
2153                0,
2154                "All ComplexStruct elements should be dropped"
2155            );
2156            assert_eq!(
2157                tracker.dropped().count(),
2158                15,
2159                "All 15 ComplexStruct elements should have been dropped"
2160            );
2161        }
2162
2163        #[test]
2164        fn test_memory_leaks_error_conditions() {
2165            let mut tracker = DropTracker::new();
2166
2167            let mut list = SingleLinkedList::new();
2168            for i in 0..10 {
2169                list.push_back(tracker.track(i));
2170            }
2171
2172            assert_eq!(tracker.alive().count(), 10, "10 elements should be alive");
2173
2174            // Attempted to delete at an invalid index (should not cause leaks)
2175            assert!(list.remove(15).is_err());
2176
2177            // Attempt to insert at invalid index
2178            assert!(list.insert(15, tracker.track(99)).is_err());
2179
2180            assert_eq!(
2181                tracker.alive().count(),
2182                10,
2183                "10 elements should be alive (10 original + 1 attempted insert)"
2184            );
2185
2186            // Clearing the list
2187            while list.len() > 0 {
2188                let _ = list.pop_front();
2189            }
2190
2191            drop(list); // Explicit deletion
2192
2193            assert_eq!(
2194                tracker.alive().count(),
2195                0,
2196                "All elements should be dropped even after error conditions"
2197            );
2198            assert_eq!(
2199                tracker.dropped().count(),
2200                11,
2201                "All 11 elements should have been dropped"
2202            );
2203        }
2204
2205        // Test that clear() properly frees all nodes and there's no memory leak
2206        #[test]
2207        fn test_clear_no_memory_leak_with_drop_tracker() {
2208            // Create a list with tracked nodes
2209            let mut list = SingleLinkedList::new();
2210            let mut tracker = DropTracker::new();
2211
2212            // Add several elements — each will be wrapped in DropTracker
2213            list.push_back(tracker.track(10));
2214            list.push_back(tracker.track(20));
2215            list.push_back(tracker.track(30));
2216            list.push_back(tracker.track(40));
2217            list.push_back(tracker.track(50));
2218
2219            assert_eq!(list.len(), 5, "list should have 5 elements before clear()");
2220            assert_eq!(tracker.alive().count(), 5, "no nodes should be dropped yet");
2221
2222            // Clear the list — all nodes should be freed and their Drop impl called
2223            list.clear();
2224
2225            assert!(list.is_empty(), "list should be empty after clear()");
2226            assert_eq!(list.len(), 0, "length should be 0 after clear()");
2227            assert_eq!(
2228                tracker.alive().count(),
2229                0,
2230                "all 5 nodes should be dropped during clear()"
2231            );
2232
2233            assert_eq!(
2234                tracker.dropped().count(),
2235                5,
2236                "no additional drops should happen after list destruction"
2237            );
2238        }
2239
2240        // Test memory cleanup when clear() is called on a list with complex types
2241        #[test]
2242        fn test_clear_complex_types_no_memory_leak() {
2243            let mut list = SingleLinkedList::new();
2244            let mut tracker = DropTracker::new();
2245
2246            // Use DropTracker with String type
2247            list.push_back(tracker.track("first".to_string()));
2248            list.push_back(tracker.track("second".to_string()));
2249            list.push_back(tracker.track("third".to_string()));
2250
2251            assert_eq!(list.len(), 3, "complex type list should have correct size");
2252            assert_eq!(tracker.alive().count(), 3, "no drops before clear()");
2253
2254            list.clear();
2255
2256            assert!(
2257                list.is_empty(),
2258                "complex type list should be empty after clear()"
2259            );
2260            assert_eq!(
2261                tracker.alive().count(),
2262                0,
2263                "all 3 complex nodes should be dropped during clear()"
2264            );
2265
2266            assert_eq!(
2267                tracker.dropped().count(),
2268                3,
2269                "no extra drops after complex list destruction"
2270            );
2271        }
2272
2273        // Test that clear() works correctly even if some nodes were already dropped
2274        // through other operations
2275        #[test]
2276        fn test_clear_after_partial_removal_no_leak() {
2277            let mut list = SingleLinkedList::new();
2278            let mut tracker = DropTracker::new();
2279
2280            // Add 4 elements
2281            list.push_back(tracker.track(1));
2282            list.push_back(tracker.track(2));
2283            list.push_back(tracker.track(3));
2284            list.push_back(tracker.track(4));
2285
2286            assert_eq!(list.len(), 4, "initial list size should be 4");
2287            assert_eq!(tracker.alive().count(), 4, "no drops at start");
2288
2289            // Remove two elements manually
2290            let _ = list.pop_front(); // drops element 1
2291            let _ = list.pop_back(); // drops element 4
2292
2293            assert_eq!(list.len(), 2, "list size should be 2 after partial removal");
2294            assert_eq!(
2295                tracker.alive().count(),
2296                2,
2297                "2 nodes should be dropped by pop_front and pop_back"
2298            );
2299            assert_eq!(
2300                tracker.dropped().count(),
2301                2,
2302                "2 nodes should be dropped by pop_front and pop_back"
2303            );
2304
2305            // Now clear the remaining two elements
2306            list.clear();
2307
2308            assert!(list.is_empty(), "list should be empty after final clear()");
2309            assert_eq!(
2310                tracker.alive().count(),
2311                0,
2312                "total 4 nodes should be dropped (2 by pop, 2 by clear)"
2313            );
2314
2315            assert_eq!(
2316                tracker.dropped().count(),
2317                4,
2318                "no extra drops after list destruction"
2319            );
2320        }
2321    }
2322}