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
// Copyright 2022 Colin Finck <colin@reactos.org>
// SPDX-License-Identifier: MIT OR Apache-2.0

use core::iter::FusedIterator;
use core::marker::PhantomPinned;
use core::pin::Pin;
use core::ptr;

use moveit::{new, New};

use super::traits::NtList;
use crate::traits::{NtListElement, NtTypedList};

/// A doubly linked list header compatible to [`LIST_ENTRY`] of the Windows NT API.
///
/// This variant requires elements to be allocated beforehand on a stable address and be
/// valid as long as the list is used.
/// As the Rust compiler cannot guarantee the validity of them, almost all `NtListHead`
/// functions are `unsafe`.
/// You almost always want to use [`NtBoxingListHead`] over this.
///
/// See the [module-level documentation](crate::list) for more details.
///
/// This structure substitutes the `LIST_ENTRY` structure of the Windows NT API for the list header.
///
/// [`LIST_ENTRY`]: https://docs.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-list_entry
/// [`NtBoxingListHead`]: crate::list::NtBoxingListHead
#[repr(C)]
pub struct NtListHead<E: NtListElement<L>, L: NtTypedList<T = NtList>> {
    pub(crate) flink: *mut NtListEntry<E, L>,
    pub(crate) blink: *mut NtListEntry<E, L>,
    pub(crate) pin: PhantomPinned,
}

impl<E, L> NtListHead<E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    /// Creates a new doubly linked list.
    ///
    /// This function substitutes [`InitializeListHead`] of the Windows NT API.
    ///
    /// [`InitializeListHead`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-initializelisthead
    pub fn new() -> impl New<Output = Self> {
        new::of(Self {
            flink: ptr::null_mut(),
            blink: ptr::null_mut(),
            pin: PhantomPinned,
        })
        .with(|this| {
            let this = unsafe { this.get_unchecked_mut() };
            this.flink = (this as *mut Self).cast();
            this.blink = this.flink;
        })
    }

    /// Moves all elements from `other` to the end of the list.
    ///
    /// This reuses all the nodes from `other` and moves them into `self`.
    /// After this operation, `other` becomes empty.
    ///
    /// This operation computes in *O*(*1*) time.
    pub unsafe fn append(mut self: Pin<&mut Self>, other: Pin<&mut Self>) {
        if other.as_ref().is_empty() {
            return;
        }

        // Append `other` to `self` by remounting the respective elements:
        // - The last element of `self` shall be followed by the first element of `other`.
        // - The first element of `other` shall be preceded by the last element of `self`.
        // - The last element of `other` shall be followed by the end marker of `self`.
        // - The last element of `self` shall be changed to the last element of `other`.
        (*self.blink).flink = other.flink;
        (*other.flink).blink = self.blink;
        (*other.blink).flink = self.as_mut().end_marker_mut();
        self.get_unchecked_mut().blink = other.blink;

        // Clear `other` without touching any of its elements.
        other.clear();
    }

    /// Provides a reference to the last element, or `None` if the list is empty.
    ///
    /// This operation computes in *O*(*1*) time.
    pub unsafe fn back(self: Pin<&Self>) -> Option<&E> {
        (!self.is_empty()).then(|| NtListEntry::containing_record(self.blink))
    }

    /// Provides a mutable reference to the last element, or `None` if the list is empty.
    ///
    /// This operation computes in *O*(*1*) time.
    pub unsafe fn back_mut(self: Pin<&mut Self>) -> Option<&mut E> {
        (!self.as_ref().is_empty()).then(|| NtListEntry::containing_record_mut(self.blink))
    }

    /// Removes all elements from the list.
    ///
    /// This operation computes in *O*(*1*) time, because it only resets the forward and
    /// backward links of the header.
    pub fn clear(mut self: Pin<&mut Self>) {
        let end_marker = self.as_mut().end_marker_mut();
        let self_mut = unsafe { self.get_unchecked_mut() };

        self_mut.flink = end_marker;
        self_mut.blink = end_marker;
    }

    /// Returns a const pointer to the "end marker element" (which is the address of our own `NtListHead`, but interpreted as a `NtListEntry` element address).
    pub(crate) fn end_marker(self: Pin<&Self>) -> *const NtListEntry<E, L> {
        (self.get_ref() as *const Self).cast()
    }

    /// Returns a mutable pointer to the "end marker element" (which is the address of our own `NtListHead`, but interpreted as a `NtListEntry` element address).
    pub(crate) fn end_marker_mut(self: Pin<&mut Self>) -> *mut NtListEntry<E, L> {
        (unsafe { self.get_unchecked_mut() } as *mut Self).cast()
    }

    /// Returns the [`NtListEntry`] for the given element.
    pub(crate) fn entry(element: &mut E) -> *mut NtListEntry<E, L> {
        let element_ptr = element as *mut E;

        // This is the canonical implementation of `byte_add`
        let entry = unsafe { element_ptr.cast::<u8>().add(E::offset()).cast::<E>() };

        entry.cast()
    }

    /// Provides a reference to the first element, or `None` if the list is empty.
    ///
    /// This operation computes in *O*(*1*) time.
    pub unsafe fn front(self: Pin<&Self>) -> Option<&E> {
        (!self.is_empty()).then(|| NtListEntry::containing_record(self.flink))
    }

    /// Provides a mutable reference to the first element, or `None` if the list is empty.
    ///
    /// This operation computes in *O*(*1*) time.
    pub unsafe fn front_mut(self: Pin<&mut Self>) -> Option<&mut E> {
        (!self.as_ref().is_empty()).then(|| NtListEntry::containing_record_mut(self.flink))
    }

    /// Returns `true` if the list is empty.
    ///
    /// This function substitutes [`IsListEmpty`] of the Windows NT API.
    ///
    /// This operation computes in *O*(*1*) time.
    ///
    /// [`IsListEmpty`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-islistempty
    pub fn is_empty(self: Pin<&Self>) -> bool {
        self.flink as *const NtListEntry<E, L> == (self.get_ref() as *const Self).cast()
    }

    /// Returns an iterator yielding references to each element of the list.
    pub unsafe fn iter(self: Pin<&Self>) -> Iter<E, L> {
        let head = self;
        let flink = head.flink;
        let blink = head.blink;

        Iter { head, flink, blink }
    }

    /// Returns an iterator yielding mutable references to each element of the list.
    pub unsafe fn iter_mut(self: Pin<&mut Self>) -> IterMut<E, L> {
        let head = self;
        let flink = head.flink;
        let blink = head.blink;

        IterMut { head, flink, blink }
    }

    /// Counts all elements and returns the length of the list.
    ///
    /// This operation computes in *O*(*n*) time.
    pub unsafe fn len(self: Pin<&Self>) -> usize {
        self.iter().count()
    }

    /// Removes the last element from the list and returns it, or `None` if the list is empty.
    ///
    /// This function substitutes [`RemoveTailList`] of the Windows NT API.
    ///
    /// This operation computes in *O*(*1*) time.
    ///
    /// [`RemoveTailList`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-removetaillist
    pub unsafe fn pop_back(self: Pin<&mut Self>) -> Option<&mut E> {
        (!self.as_ref().is_empty()).then(|| {
            let entry = self.blink;
            (*entry).remove();
            NtListEntry::containing_record_mut(entry)
        })
    }

    /// Removes the first element from the list and returns it, or `None` if the list is empty.
    ///
    /// This function substitutes [`RemoveHeadList`] of the Windows NT API.
    ///
    /// This operation computes in *O*(*1*) time.
    ///
    /// [`RemoveHeadList`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-removeheadlist
    pub unsafe fn pop_front(self: Pin<&mut Self>) -> Option<&mut E> {
        (!self.as_ref().is_empty()).then(|| {
            let entry = self.flink;
            (*entry).remove();
            NtListEntry::containing_record_mut(entry)
        })
    }

    /// Appends an element to the back of the list.
    ///
    /// This function substitutes [`InsertTailList`] of the Windows NT API.
    ///
    /// This operation computes in *O*(*1*) time.
    ///
    /// [`InsertTailList`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-inserttaillist
    pub unsafe fn push_back(mut self: Pin<&mut Self>, element: &mut E) {
        let entry = Self::entry(element);

        let old_blink = self.blink;
        (*entry).flink = self.as_mut().end_marker_mut();
        (*entry).blink = old_blink;
        (*old_blink).flink = entry;
        self.get_unchecked_mut().blink = entry;
    }

    /// Appends an element to the front of the list.
    ///
    /// This function substitutes [`InsertHeadList`] of the Windows NT API.
    ///
    /// This operation computes in *O*(*1*) time.
    ///
    /// [`InsertHeadList`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-insertheadlist
    pub unsafe fn push_front(mut self: Pin<&mut Self>, element: &mut E) {
        let entry = Self::entry(element);

        let old_flink = self.flink;
        (*entry).flink = old_flink;
        (*entry).blink = self.as_mut().end_marker_mut();
        (*old_flink).blink = entry;
        self.get_unchecked_mut().flink = entry;
    }

    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
    ///
    /// In other words, remove all elements `e` for which `f(&mut e)` returns `false`.
    /// This method operates in place, visiting each element exactly once in the original order,
    /// and preserves the order of the retained elements.
    ///
    /// This function substitutes [`RemoveEntryList`] of the Windows NT API.
    ///
    /// This operation computes in *O*(*n*) time.
    ///
    /// [`RemoveEntryList`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-removeentrylist
    pub unsafe fn retain<F>(self: Pin<&mut Self>, mut f: F)
    where
        F: FnMut(&mut E) -> bool,
    {
        for element in self.iter_mut() {
            if !f(element) {
                let entry = Self::entry(element);
                (*entry).remove();
            }
        }
    }
}

/// Iterator over the elements of a doubly linked list.
///
/// This iterator is returned from the [`NtListHead::iter`] and [`NtBoxingListHead::iter`] functions.
///
/// [`NtBoxingListHead::iter`]: crate::list::NtBoxingListHead::iter
pub struct Iter<'a, E: NtListElement<L>, L: NtTypedList<T = NtList>> {
    head: Pin<&'a NtListHead<E, L>>,
    flink: *const NtListEntry<E, L>,
    blink: *const NtListEntry<E, L>,
}

impl<'a, E, L> Iter<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    fn terminate(&mut self) {
        self.flink = self.head.end_marker();
        self.blink = self.flink;
    }
}

impl<'a, E, L> Iterator for Iter<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    type Item = &'a E;

    fn next(&mut self) -> Option<&'a E> {
        if self.flink == self.head.end_marker() {
            None
        } else {
            unsafe {
                let element_ptr = self.flink;

                if self.flink == self.blink {
                    // We are crossing the other end of the iterator and must not iterate any further.
                    self.terminate();
                } else {
                    self.flink = (*self.flink).flink;
                }

                Some(NtListEntry::containing_record(element_ptr))
            }
        }
    }

    fn last(mut self) -> Option<&'a E> {
        self.next_back()
    }
}

impl<'a, E, L> DoubleEndedIterator for Iter<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    fn next_back(&mut self) -> Option<&'a E> {
        if self.blink == self.head.end_marker() {
            None
        } else {
            unsafe {
                let element_ptr = self.blink;

                if self.blink == self.flink {
                    // We are crossing the other end of the iterator and must not iterate any further.
                    self.terminate();
                } else {
                    self.blink = (*self.blink).blink;
                }

                Some(NtListEntry::containing_record(element_ptr))
            }
        }
    }
}

impl<'a, E, L> FusedIterator for Iter<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
}

/// Mutable iterator over the elements of a doubly linked list.
///
/// This iterator is returned from the [`NtListHead::iter_mut`] and [`NtBoxingListHead::iter_mut`] functions.
///
/// [`NtBoxingListHead::iter_mut`]: crate::list::NtBoxingListHead::iter_mut
pub struct IterMut<'a, E: NtListElement<L>, L: NtTypedList<T = NtList>> {
    head: Pin<&'a mut NtListHead<E, L>>,
    flink: *mut NtListEntry<E, L>,
    blink: *mut NtListEntry<E, L>,
}

impl<'a, E, L> IterMut<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    fn terminate(&mut self) {
        self.flink = self.head.as_mut().end_marker_mut();
        self.blink = self.flink;
    }
}

impl<'a, E, L> Iterator for IterMut<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    type Item = &'a mut E;

    fn next(&mut self) -> Option<&'a mut E> {
        if self.flink == self.head.as_mut().end_marker_mut() {
            None
        } else {
            unsafe {
                let element_ptr = self.flink;

                if self.flink == self.blink {
                    // We are crossing the other end of the iterator and must not iterate any further.
                    self.terminate();
                } else {
                    self.flink = (*self.flink).flink;
                }

                Some(NtListEntry::containing_record_mut(element_ptr))
            }
        }
    }

    fn last(mut self) -> Option<&'a mut E> {
        self.next_back()
    }
}

impl<'a, E, L> DoubleEndedIterator for IterMut<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    fn next_back(&mut self) -> Option<&'a mut E> {
        if self.blink == self.head.as_mut().end_marker_mut() {
            None
        } else {
            unsafe {
                let element_ptr = self.blink;

                if self.blink == self.flink {
                    // We are crossing the other end of the iterator and must not iterate any further.
                    self.terminate();
                } else {
                    self.blink = (*self.blink).blink;
                }

                Some(NtListEntry::containing_record_mut(element_ptr))
            }
        }
    }
}

impl<'a, E, L> FusedIterator for IterMut<'a, E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
}

/// This structure substitutes the `LIST_ENTRY` structure of the Windows NT API for actual list entries.
#[derive(Debug)]
#[repr(C)]
pub struct NtListEntry<E: NtListElement<L>, L: NtTypedList<T = NtList>> {
    pub(crate) flink: *mut NtListEntry<E, L>,
    pub(crate) blink: *mut NtListEntry<E, L>,
    pin: PhantomPinned,
}

impl<E, L> NtListEntry<E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    /// Allows the creation of an `NtListEntry`, but leaves all fields uninitialized.
    ///
    /// Its fields are only initialized when an entry is pushed to a list.
    pub fn new() -> Self {
        Self {
            flink: ptr::null_mut(),
            blink: ptr::null_mut(),
            pin: PhantomPinned,
        }
    }

    pub(crate) unsafe fn containing_record<'a>(ptr: *const Self) -> &'a E {
        // This is the canonical implementation of `byte_sub`
        let element_ptr = unsafe { ptr.cast::<u8>().sub(E::offset()).cast::<Self>() };

        unsafe { &*element_ptr.cast() }
    }

    pub(crate) unsafe fn containing_record_mut<'a>(ptr: *mut Self) -> &'a mut E {
        // This is the canonical implementation of `byte_sub`
        let element_ptr = unsafe { ptr.cast::<u8>().sub(E::offset()).cast::<Self>() };

        unsafe { &mut *element_ptr.cast() }
    }

    pub(crate) unsafe fn remove(&mut self) {
        let old_flink = self.flink;
        let old_blink = self.blink;
        (*old_flink).blink = old_blink;
        (*old_blink).flink = old_flink;
    }
}

impl<E, L> Default for NtListEntry<E, L>
where
    E: NtListElement<L>,
    L: NtTypedList<T = NtList>,
{
    fn default() -> Self {
        Self::new()
    }
}