cdll/head/
mod.rs

1use {crate::CircularList, alloc::boxed::Box, core::ptr};
2
3pub mod cursor;
4
5/// List element for a doubly linked list.
6pub struct ListHead<T> {
7    next: *const ListHead<T>,
8    prev: *const ListHead<T>,
9    value: T,
10}
11
12/// The present implementation aims to preserve the following invariant (3):
13/// * The `next` and `prev` pointers are always valid
14/// * Following the `next` field recursively must always end up to the original `Self`
15/// * Following the `prev` field recursively must give the exact reverse path as the `next` one
16impl<T> ListHead<T> {
17    /// Creates a new element with value `val`.
18    /// The created element is its own previous and next element.
19    /// # Layout
20    /// ```text
21    /// ┌───┐
22    /// │   │
23    /// │ ┌─▼──┐
24    /// └─┤val ├─┐
25    ///   └──▲─┘ │
26    ///      │   │
27    ///      └───┘
28    /// ```
29    pub fn new(val: T) -> Box<Self> {
30        let mut new = Box::new(Self {
31            next: ptr::null(),
32            prev: ptr::null(),
33            value: val,
34        });
35
36        // Preserving invariant (3)
37        new.next = &*new;
38        new.prev = &*new;
39
40        new
41    }
42
43    /// Gets a pointer to the next element.
44    pub fn next(&self) -> *const Self {
45        self.next
46    }
47
48    /// Gets a pointer to the previous element.
49    pub fn prev(&self) -> *const Self {
50        self.prev
51    }
52
53    /// Gets a shared reference to the value of the list head.
54    pub fn value(&self) -> &T {
55        &self.value
56    }
57
58    /// Gets an exclusive reference to the value of the list head.
59    pub fn value_mut(&mut self) -> &mut T {
60        &mut self.value
61    }
62
63    /// Inserts `new` between `prev` and `next`.
64    ///
65    /// # Sketch
66    /// ```text
67    /// ┌────┬──►┌────┬──►┌────┐
68    /// │prev│   │new │   │next│
69    /// └────┘◄──┴────┘◄──┴────┘
70    /// ```
71    ///
72    /// # Safety
73    /// * `next`, `new` and `prev` must be valid pointers
74    /// * `next` should be the next of `prev` and `prev` should be the
75    /// previous of `next`
76    /// * `new` must be disconnected from its old place (i.e. with
77    /// `__del` or `__replace`) before
78    /// calling this function otherwise it would break
79    /// [`INVARIANT_3`](`crate::invariants::INVARIANT_3`).
80    unsafe fn __add(new: *mut Self, prev: *mut Self, next: *mut Self) {
81        unsafe {
82            // SAFETY: See the caller contract.
83            (*next).prev = new;
84            (*new).next = next;
85            (*new).prev = prev;
86            (*prev).next = new;
87        }
88    }
89
90    /// Disconnects element(s) by connecting the previous and next elements
91    /// together.
92    ///
93    /// # Sketch
94    /// ```text
95    ///      ┌────┬──┐
96    ///      │list│  │
97    ///  ┌───┴────┘  │
98    /// ┌▼───┬──►┌───▼┐
99    /// │prev│   │next│
100    /// └────┘◄──┴────┘
101    /// ```
102    /// # Safety
103    /// * `next` and `prev` must be valid pointers.
104    /// * the element(s) between `next` and `prev` must be dropped or
105    /// connected somewhere else
106    /// after calling this function in order to preserve
107    /// [`INVARIANT_3`](`crate::invariants::INVARIANT_3`).
108    unsafe fn __del(prev: *mut Self, next: *mut Self) {
109        unsafe {
110            // SAFETY: See the caller contract.
111            (*next).prev = prev;
112            (*prev).next = next;
113        }
114    }
115
116    /// Disconnects an element from the list then returns its value and a pointer to the
117    /// next element. The `ListHead` is dropped in the process.
118    ///
119    /// # Safety
120    /// `to_del` must be a valid pointer to a `ListHead` with valid pointers to its next
121    /// and previous elements.
122    pub unsafe fn del_entry(to_del: *mut Self) -> (*const Self, T) {
123        let mut next = (*to_del).next;
124        if to_del as *const _ != next {
125            unsafe {
126                // `to_del` is valid as promised by the caller.
127                // `(*to_del).prev` and `(*to_del).next` should be valid according to invariant (3).
128                Self::__del((*to_del).prev as *mut _, (*to_del).next as *mut _);
129            }
130        } else {
131            next = ptr::null();
132        }
133
134        // `to_del` has to be dropped in order to preserve invariant (3).
135        let to_del = Box::from_raw(to_del);
136        (next, to_del.value)
137    }
138
139    /// Inserts an element before this one.
140    ///
141    /// # Safety
142    /// `new` must be a valid pointer to a `ListHead` a must not be connected to other `ListHead`s.
143    pub unsafe fn add(&mut self, new: *mut Self) {
144        unsafe {
145            // SAFETY: Since `self` is a borrow checked reference, it must be true that
146            // it is a valid pointer. The caller promises us that `new` is valid.
147            // As for the `prev` parameter, it is the same as `self` or
148            // another valid pointer according to invariant (3).
149            Self::__add(new, self.prev as *mut _, self);
150        }
151    }
152
153    /// Inserts an element after this one.
154    ///
155    /// # Safety
156    /// `new` must be a valid pointer to a `ListHead` a must not be connected to other `ListHead`s.
157    pub unsafe fn add_after(&mut self, new: *mut Self) {
158        unsafe {
159            // SAFETY: Since `self` is a borrow checked reference, it must be true that
160            // it is a valid pointer. The caller promises us that `new` is valid.
161            // As for the `prev` parameter, it is the same as `self` or
162            // another valid pointer according to invariant (3).
163            Self::__add(new, self, self.next as *mut _);
164        }
165    }
166
167    /// Connects `new` in place of `old` in the list.
168    ///
169    /// # Sketch
170    ///
171    /// ## Before
172    /// ```text
173    ///     ┌────┬──►?
174    ///     │new │
175    /// ?◄──┴────┘
176    /// ┌────┬──►┌────┬──►┌────┐
177    /// │prev│   │old │   │next│
178    /// └────┘◄──┴────┘◄──┴────┘
179    /// ```
180    ///
181    /// ## After
182    /// ```text
183    /// ┌───────►┌────┬───────┐
184    /// │        │new │       │
185    /// │   ┌────┴────┘◄──┐   │
186    /// │   │             │   │
187    /// ├───▼┐   ┌────┬──►├───▼┐
188    /// │prev│   │old │   │next│
189    /// └────┘◄──┴────┘   └────┘
190    /// ```
191    ///
192    /// # Safety
193    /// * `old` and `new` must be valid pointers
194    /// * `old` has to be dropped or connected somewhere else after calling this function in
195    /// order to preserve [`INVARIANT_3`](`crate::invariants::INVARIANT_3`).
196    unsafe fn __replace(old: *mut Self, new: *mut Self) {
197        unsafe {
198            // SAFETY: The caller garantee that `old` and
199            // `new` are valid pointers and that `old` will
200            // be dropped or connected somewhere else.
201            (*new).next = (*old).next;
202            (*((*new).next as *mut Self)).prev = new;
203            (*new).prev = (*old).prev;
204            (*((*new).prev as *mut Self)).next = new;
205        }
206    }
207
208    /// Exchanges 2 elements by interchanging their connection to their list (which could be not
209    /// the same).
210    ///
211    /// # Safety
212    /// `entry1` and `entry2` must be valid pointers to valid circular linked lists.
213    pub unsafe fn swap(entry1: *mut Self, entry2: *mut Self) {
214        unsafe {
215            // `entry2` is valid as promised by the caller.
216            // `(*entry2).prev` and `(*entry2).next` should be valid according to invariant (3)
217            let mut pos = (*entry2).prev;
218            Self::__del((*entry2).prev as *mut _, (*entry2).next as *mut _);
219
220            // `entry1` is valid as promised by the caller.
221            // `entry2` is connected in place of `entry1` which preserve invariant (3).
222            Self::__replace(entry1, entry2);
223
224            // in case `entry1` was already behind `entry2`, it is place next to it.
225            if pos == entry1 {
226                pos = entry2;
227            }
228
229            // `pos` and `(*pos).next` are valid according to invariant (3) and `entry1` was just
230            // disconnected from its old place.
231            Self::__add(entry1 as *mut _, pos as *mut _, (*pos).next as *mut _);
232        }
233    }
234
235    /// Moves out `entry` and inserts it between `prev` and `next`.
236    ///
237    /// # Safety
238    /// The caller must give valid pointers and make sure `next` is the next element of `prev`
239    /// otherwise there could be memory leaks.
240    pub unsafe fn move_entry(entry: *mut Self, prev: *mut Self, next: *mut Self) {
241        unsafe {
242            // `(*entry).prev` and `(*entry).next` should be valid according to invariant (3)
243            Self::__del((*entry).prev as *mut _, (*entry).next as *mut _);
244            // We know `entry` is valid and `next` and `prev` are consecutive (because of course the
245            // caller is cautious)
246            Self::__add(entry, prev, next);
247        }
248    }
249
250    /// Insert `list` before `next`.
251    ///
252    /// # Safety
253    /// * `list` must be a valid pointer and be part of a valid circular list
254    /// * Idem for `next`
255    /// * `list` **must not** be an element of the same circular list as `next` without defining a
256    /// new head for the orphaned list, otherwise it would cause a memory leak.
257    pub unsafe fn add_list(list: *mut Self, next: *mut Self) {
258        unsafe {
259            // `last_of_list` should be valid according to invariant (3)
260            let last_of_list = (*list).prev as *mut Self;
261            // idem
262            let prev = (*next).prev as *mut Self;
263
264            // Preserving invariant (3): as soon as `list` is part of a valid circular list as well as
265            // `next`, the connections made here will create 1 or 2 valid circular list(s).
266
267            // The end of `list` is connected to `next`
268            Self::__del(last_of_list, next);
269
270            // The beginning of `list` is connected to the element before `next`
271            Self::__del(prev, list);
272        }
273    }
274
275    /// Cuts a circular list in two parts.
276    ///
277    /// # Safety
278    /// * `head` and `new_head` must be valid pointers
279    /// * `new_head` **must** be the head of a newly created `CircularList` after the call
280    pub unsafe fn split(head: *mut Self, new_head: *mut Self) {
281        unsafe {
282            // The last element of the list where `new_head` is the head.
283            let new_tail = (*head).prev as *mut _;
284
285            // close the list where `head` is the head
286            Self::__del((*new_head).prev as *mut Self, head);
287
288            // close the list where `new_head` is the head
289            Self::__del(new_tail, new_head);
290        }
291    }
292}
293
294/// Circular list iterator.
295pub struct Iter<'life, T> {
296    _list: &'life CircularList<T>,
297    next: *const ListHead<T>,
298}
299impl<'life, T> Iterator for Iter<'life, T> {
300    type Item = &'life T;
301
302    fn next(&mut self) -> Option<Self::Item> {
303        // SAFETY: the lifetime `'life` of `self` is bound to the lifetime of the list. We
304        // return a `'life` shared reference to the current value which is bound to the list.
305        // Plus, the list is circular so next should always be non null if the list is non empty.
306        let (current, next) = unsafe {
307            let r = &*self.next;
308            (&r.value, r.next)
309        };
310        self.next = next;
311        Some(current)
312    }
313}
314impl<'life, T> Iter<'life, T> {
315    pub fn new(list: &'life CircularList<T>) -> Self {
316        let first = list.head;
317        Self {
318            _list: list,
319            next: first,
320        }
321    }
322}
323
324/// Circular list iterator with mutability.
325pub struct IterMut<'life, T> {
326    _list: &'life mut CircularList<T>,
327    next: *mut ListHead<T>,
328}
329impl<'life, T> Iterator for IterMut<'life, T> {
330    type Item = &'life mut T;
331
332    fn next(&mut self) -> Option<Self::Item> {
333        // SAFETY: the lifetime `'life` of `self` is bound to the lifetime of the list. We
334        // return a `'life` shared reference to the current value which is bound to the list.
335        // Plus, the list is circular so next should always be non null if the list is non empty.
336        let (current, next) = unsafe {
337            let r = &mut *self.next;
338            (&mut r.value, r.next as *mut _)
339        };
340        self.next = next;
341        Some(current)
342    }
343}
344impl<'life, T> IterMut<'life, T> {
345    pub fn new(list: &'life mut CircularList<T>) -> Self {
346        let first = list.head as *mut _;
347        Self {
348            _list: list,
349            next: first,
350        }
351    }
352}
353
354impl<T: PartialEq> PartialEq for ListHead<T> {
355    fn eq(&self, other: &Self) -> bool {
356        self.value.eq(&other.value)
357    }
358}
359
360impl<T: PartialOrd> PartialOrd for ListHead<T> {
361    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
362        self.value.partial_cmp(&other.value)
363    }
364}