circular_doubly_linked_list 0.1.0

A high-performance Circular Doubly Linked List implementation in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Iterator module providing forward and backward iteration over the list.
//!
//! This module contains three iterator types for traversing a `CircularDoublyLinkedList`:
//! - [`Iter`]: Immutable reference iterator (yields `&T`)
//! - [`IterMut`]: Mutable reference iterator (yields `&mut T`)
//! - [`IntoIter`]: Owning iterator that consumes the list (yields `T`)

use core::marker::PhantomData;
use core::ptr::NonNull;

use crate::node::Node;

/// An immutable iterator over a `CircularDoublyLinkedList`.
///
/// This iterator yields immutable references (`&T`) to the elements in the list,
/// traversing from front (head) to back (tail) in order.
///
/// # Type Parameters
///
/// * `'a` - The lifetime of the references yielded (tied to the list borrow)
/// * `T` - The type of elements in the list
///
/// # Lifetime
///
/// The iterator borrows the list for its lifetime. The list cannot be modified
/// (except through interior mutability) while this iterator exists.
///
/// # Examples
///
/// ```rust
/// use circular_doubly_linked_list::CircularDoublyLinkedList;
///
/// let mut list = CircularDoublyLinkedList::new();
/// list.push_back(1);
/// list.push_back(2);
/// list.push_back(3);
///
/// // Iterate immutably
/// for item in list.iter() {
///     println!("{}", item);
/// }
/// // Output: 1, 2, 3
///
/// // Can still use list after iteration
/// assert_eq!(list.len(), 3);
/// ```
pub struct Iter<'a, T> {
    /// Current node pointer (next element to yield).
    current: Option<NonNull<Node<T>>>,
    /// Current node pointer (next element to yield from back).
    back: Option<NonNull<Node<T>>>,
    /// Number of remaining elements to iterate.
    remaining: usize,
    /// Phantom data to tie the lifetime to the borrowed list.
    _marker: PhantomData<&'a T>,
}

impl<'a, T> Iter<'a, T> {
    /// Creates a new immutable iterator.
    ///
    /// # Parameters
    ///
    /// * `head` - The head node of the list (starting point for iteration)
    /// * `length` - The number of elements in the list (used for bounds)
    ///
    /// # Returns
    ///
    /// Returns a new `Iter<'a, T>` instance ready to iterate from the head.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `head` accurately represents the list state
    /// and that `length` matches the actual number of nodes in the circular chain.
    pub(crate) fn new(head: Option<NonNull<Node<T>>>, length: usize) -> Self {
        let back = if length > 0 {
            head.map(|h| unsafe { Node::get_prev(h) })
        } else {
            None
        };

        Self {
            current: head,
            back,
            remaining: length,
            _marker: PhantomData,
        }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    /// Advances the iterator and returns the next immutable reference.
    ///
    /// # Returns
    ///
    /// - `Some(&'a T)` - Reference to the next element if available
    /// - `None` - When all elements have been iterated
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// let mut iter = list.iter();
    /// assert_eq!(iter.next(), Some(&1));
    /// assert_eq!(iter.next(), Some(&2));
    /// assert_eq!(iter.next(), None);
    /// ```
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        unsafe {
            let current = self.current.unwrap_unchecked();
            let data = Node::data_ref(current);

            self.current = Some(Node::get_next(current));
            self.remaining -= 1;

            Some(data)
        }
    }

    /// Returns the exact remaining length of the iterator.
    ///
    /// # Returns
    ///
    /// Returns a tuple `(min, max)` where both values equal the remaining count.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'a, T> ExactSizeIterator for Iter<'a, T> {
    /// Returns the exact number of remaining elements.
    ///
    /// # Returns
    ///
    /// Returns the number of elements yet to be iterated.
    fn len(&self) -> usize {
        self.remaining
    }
}

impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
    /// Advances the iterator from the back, returning the last element.
    ///
    /// This enables reverse iteration using `.rev()` or `next_back()`.
    ///
    /// # Returns
    ///
    /// - `Some(&'a T)` - Reference to the back element if available
    /// - `None` - When all elements have been iterated
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// let vec: Vec<_> = list.iter().rev().copied().collect();
    /// assert_eq!(vec, [3, 2, 1]);
    /// ```
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        unsafe {
            let back = self.back.unwrap_unchecked();
            let data = Node::data_ref(back);

            self.back = Some(Node::get_prev(back));
            self.remaining -= 1;

            Some(data)
        }
    }
}

impl<'a, T> Clone for Iter<'a, T> {
    /// Creates a clone of the iterator.
    ///
    /// # Returns
    ///
    /// Returns a new `Iter` with the same position and remaining count.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// let mut iter1 = list.iter();
    /// let _ = iter1.next(); // Advance iter1
    ///
    /// let mut iter2 = iter1.clone();
    /// // iter2 starts at the same position as iter1
    /// ```
    fn clone(&self) -> Self {
        Self {
            current: self.current,
            back: self.back,
            remaining: self.remaining,
            _marker: PhantomData,
        }
    }
}

/// A mutable iterator over a `CircularDoublyLinkedList`.
///
/// This iterator yields mutable references (`&mut T`) to the elements in the list,
/// traversing from front (head) to back (tail) in order.
///
/// # Type Parameters
///
/// * `'a` - The lifetime of the references yielded (tied to the list borrow)
/// * `T` - The type of elements in the list
///
/// # Lifetime
///
/// The iterator mutably borrows the list for its lifetime. The list cannot be
/// accessed through other means while this iterator exists (Rust's borrowing rules).
///
/// # Examples
///
/// ```rust
/// use circular_doubly_linked_list::CircularDoublyLinkedList;
///
/// let mut list = CircularDoublyLinkedList::new();
/// list.push_back(1);
/// list.push_back(2);
/// list.push_back(3);
///
/// // Iterate mutably and modify elements
/// for item in list.iter_mut() {
///     *item *= 2;
/// }
///
/// let vec: Vec<_> = list.iter().copied().collect();
/// assert_eq!(vec, [2, 4, 6]);
/// ```
pub struct IterMut<'a, T> {
    /// Current node pointer (next element to yield from front).
    current: Option<NonNull<Node<T>>>,
    /// Current node pointer (next element to yield from back).
    back: Option<NonNull<Node<T>>>,
    /// Number of remaining elements to iterate
    remaining: usize,
    /// Phantom data to tie the lifetime to the mutably borrowed list.
    _marker: PhantomData<&'a mut T>,
}

impl<'a, T> IterMut<'a, T> {
    /// Creates a new mutable iterator.
    ///
    /// # Parameters
    ///
    /// * `head` - The head node of the list (starting point for iteration)
    /// * `length` - The number of elements in the list (used for bounds)
    ///
    /// # Returns
    ///
    /// Returns a new `IterMut<'a, T>` instance ready to iterate from the head.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `head` accurately represents the list state
    /// and that `length` matches the actual number of nodes in the circular chain.
    pub(crate) fn new(head: Option<NonNull<Node<T>>>, length: usize) -> Self {
        let back = if length > 0 {
            head.map(|h| unsafe { Node::get_prev(h) })
        } else {
            None
        };

        Self {
            current: head,
            back,
            remaining: length,
            _marker: PhantomData,
        }
    }
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    /// Advances the iterator and returns the next mutable reference.
    ///
    /// # Returns
    ///
    /// - `Some(&'a mut T)` - Mutable reference to the next element if available
    /// - `None` - When all elements have been iterated
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// let mut iter = list.iter_mut();
    /// if let Some(first) = iter.next() {
    ///     *first = 100;
    /// }
    /// ```
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        unsafe {
            let current = self.current.unwrap_unchecked();
            let data = Node::data_mut(current);

            self.current = Some(Node::get_next(current));
            self.remaining -= 1;

            Some(data)
        }
    }

    /// Returns the exact remaining length of the iterator.
    ///
    /// # Returns
    ///
    /// Returns a tuple `(min, max)` where both values equal the remaining count.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
    /// Returns the exact number of remaining elements.
    ///
    /// # Returns
    ///
    /// Returns the number of elements yet to be iterated.
    fn len(&self) -> usize {
        self.remaining
    }
}

impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
    /// Advances the iterator from the back, returning the last element.
    ///
    /// # Returns
    ///
    /// - `Some(&'a mut T)` - Mutable reference to the back element if available
    /// - `None` - When all elements have been iterated
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        unsafe {
            let back = self.back.unwrap_unchecked();
            let data = Node::data_mut(back);

            self.back = Some(Node::get_prev(back));
            self.remaining -= 1;

            Some(data)
        }
    }
}

/// An owning iterator over a `CircularDoublyLinkedList`.
///
/// This iterator consumes the list and yields owned values (`T`). After iteration
/// completes, the original list is destroyed and cannot be used.
///
/// # Type Parameters
///
/// * `T` - The type of elements in the list
///
/// # Ownership
///
/// This iterator takes ownership of the list. Each call to `next()` removes and
/// returns one element. The `Drop` implementation ensures any remaining elements
/// are properly deallocated if iteration is not completed.
///
/// # Examples
///
/// ```rust
/// use circular_doubly_linked_list::CircularDoublyLinkedList;
///
/// let mut list = CircularDoublyLinkedList::new();
/// list.push_back(1);
/// list.push_back(2);
/// list.push_back(3);
///
/// // Consume the list
/// let vec: Vec<_> = list.into_iter().collect();
/// assert_eq!(vec, [1, 2, 3]);
///
/// // list is now consumed and cannot be used
/// ```
pub struct IntoIter<T> {
    /// Current node pointer (next element to yield and deallocate).
    current: Option<NonNull<Node<T>>>,
    /// Number of remaining elements to iterate.
    remaining: usize,
}

impl<T> IntoIter<T> {
    /// Creates a new owning iterator.
    ///
    /// # Parameters
    ///
    /// * `head` - The head node of the list (starting point for iteration)
    /// * `length` - The number of elements in the list (used for bounds)
    ///
    /// # Returns
    ///
    /// Returns a new `IntoIter<T>` instance that will consume the list.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `head` accurately represents the list state
    /// and that `length` matches the actual number of nodes in the circular chain.
    pub(crate) fn new(head: Option<NonNull<Node<T>>>, length: usize) -> Self {
        Self {
            current: head,
            remaining: length,
        }
    }
}

impl<T> Iterator for IntoIter<T> {
    type Item = T;

    /// Advances the iterator, removes, and returns the next owned value.
    ///
    /// # Returns
    ///
    /// - `Some(T)` - The next element (removed from the list) if available
    /// - `None` - When all elements have been iterated
    ///
    /// # Side Effects
    ///
    /// Each call to `next()` deallocates one node from the list.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    ///
    /// let mut iter = list.into_iter();
    /// assert_eq!(iter.next(), Some(1));
    /// assert_eq!(iter.next(), Some(2));
    /// assert_eq!(iter.next(), None);
    /// ```
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }

        unsafe {
            let current = self.current.unwrap_unchecked();
            let next = Node::get_next(current);

            self.current = if self.remaining == 1 {
                None
            } else {
                Some(next)
            };

            self.remaining -= 1;
            Some(Node::dealloc(current))
        }
    }

    /// Returns the exact remaining length of the iterator.
    ///
    /// # Returns
    ///
    /// Returns a tuple `(min, max)` where both values equal the remaining count.
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<T> ExactSizeIterator for IntoIter<T> {
    /// Returns the exact number of remaining elements.
    ///
    /// # Returns
    ///
    /// Returns the number of elements yet to be iterated and deallocated.
    fn len(&self) -> usize {
        self.remaining
    }
}

impl<T> Drop for IntoIter<T> {
    /// Deallocates any remaining nodes when the iterator is dropped.
    ///
    /// This ensures no memory leaks occur if the iterator is dropped before
    /// all elements are consumed (e.g., early return, panic, or `.take(n)`).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use circular_doubly_linked_list::CircularDoublyLinkedList;
    ///
    /// let mut list = CircularDoublyLinkedList::new();
    /// list.push_back(1);
    /// list.push_back(2);
    /// list.push_back(3);
    ///
    /// {
    ///     let mut iter = list.into_iter();
    ///     let _first = iter.next(); // Consume one element
    ///     // iter dropped here - remaining elements are deallocated
    /// }
    /// // No memory leak
    /// ```
    fn drop(&mut self) {
        if self.remaining == 0 {
            return;
        }

        unsafe {
            let mut current = self.current.unwrap();
            let mut count = 0;

            while count < self.remaining {
                let next = Node::get_next(current);
                Node::dealloc(current);
                current = next;
                count += 1;
            }
        }

        self.current = None;
        self.remaining = 0;
    }
}