unsafe_list 0.1.57

Linux 风格侵入式双向链表
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
//! Linux 风格侵入式双向链表
//!
//! 对标 Linux 内核 `<linux/list.h>` 的 `list_head` 实现。
//! 操作对象均为裸指针,无并发支持,无所有权语义。
//!
//! # Safety
//!
//! 所有公开 `unsafe` 方法均要求:
//! - 节点生命周期长于链表引用
//! - 无并发访问,或由调用方自行同步
#![no_std]
#![allow(unsafe_code)]

/// 已删除节点的 next 哨兵值(use-after-free 检测)
pub const LIST_POISON1: usize = 0xdead0100;
/// 已删除节点的 prev 哨兵值(use-after-free 检测)
pub const LIST_POISON2: usize = 0xdead0200;

/// 侵入式双向链表头
#[derive(Clone, Copy)]
pub struct UnsafeListHead<T> {
    next: *mut UnsafeListNode<T>,
    prev: *mut UnsafeListNode<T>,
    offset: usize,
}

impl<T> Default for UnsafeListHead<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> UnsafeListHead<T> {
    /// 构造链表头(未初始化),需调用 [`init_list_head`](Self::init_list_head) 后使用
    pub const fn new() -> Self {
        let init = core::ptr::null_mut::<UnsafeListNode<T>>();
        Self { next: init, prev: init, offset: 0 }
    }

    #[inline(always)]
    fn head_node(&self) -> *mut UnsafeListNode<T> {
        core::ptr::from_ref(self).cast_mut().cast()
    }

    #[inline(always)]
    unsafe fn container_of(&self, node: *const UnsafeListNode<T>) -> *const T {
        unsafe { node.byte_sub(self.offset).cast() }
    }

    #[inline(always)]
    unsafe fn container_of_mut(&self, node: *mut UnsafeListNode<T>) -> *mut T {
        unsafe { node.byte_sub(self.offset).cast() }
    }

    /// 初始化链表头,`offset` 为节点字段在包含结构体中的偏移
    pub fn init_list_head(&mut self, offset: usize) {
        let ptr = self.head_node();
        unsafe {
            core::ptr::write_volatile(&raw mut self.next, ptr);
        }
        self.prev = ptr;
        self.offset = offset;
    }

    #[inline(always)]
    unsafe fn __list_add(
        new: &mut UnsafeListNode<T>,
        prev: &mut UnsafeListNode<T>,
        next: &mut UnsafeListNode<T>,
    ) {
        next.prev = new;
        new.next = next;
        new.prev = prev;
        unsafe {
            core::ptr::write_volatile(&raw mut prev.next, new);
        }
    }

    /// 在链表头部插入节点
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_add(&mut self, new: &mut UnsafeListNode<T>) {
        unsafe {
            Self::__list_add(new, &mut *self.head_node(), &mut *self.next);
        }
    }

    /// 在链表尾部插入节点
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_add_tail(&mut self, new: &mut UnsafeListNode<T>) {
        unsafe {
            Self::__list_add(new, &mut *self.prev, &mut *self.head_node());
        }
    }

    /// 判断节点是否为链表最后一个元素
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_is_last(&self, list: &UnsafeListNode<T>) -> bool {
        core::ptr::eq(list.next, self.head_node())
    }

    /// 判断链表是否为空(volatile 读取 next)
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_empty(&self) -> bool {
        unsafe {
            let next = core::ptr::read_volatile(&raw const self.next);
            core::ptr::eq(next, self.head_node())
        }
    }

    /// 判断链表是否为空(同时检查 next 和 prev)
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_empty_careful(&self) -> bool {
        unsafe {
            let next = core::ptr::read_volatile(&raw const self.next);
            core::ptr::eq(next, self.head_node()) && core::ptr::eq(next, self.prev)
        }
    }

    /// 获取第一个元素,空链表返回 `None`
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_first_entry_or_null(&self) -> Option<&T> {
        if core::ptr::eq(self.next, self.head_node()) {
            None
        } else {
            Some(unsafe { &*self.container_of(self.next) })
        }
    }

    /// 获取第一个元素的可变引用,空链表返回 `None`
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_first_entry_or_null_mut(&mut self) -> Option<&mut T> {
        if core::ptr::eq(self.next, self.head_node()) {
            None
        } else {
            Some(unsafe { &mut *self.container_of_mut(self.next) })
        }
    }

    /// 获取第一个元素(调用方需确保链表非空)
    ///
    /// # Safety
    /// 见模块文档,且链表必须非空
    #[inline(always)]
    pub unsafe fn list_first_entry(&self) -> &T {
        unsafe { &*self.container_of(self.next) }
    }

    /// 获取第一个元素的可变引用(调用方需确保链表非空)
    ///
    /// # Safety
    /// 见模块文档,且链表必须非空
    #[inline(always)]
    pub unsafe fn list_first_entry_mut(&mut self) -> &mut T {
        unsafe { &mut *self.container_of_mut(self.next) }
    }

    /// 获取最后一个元素(调用方需确保链表非空)
    ///
    /// # Safety
    /// 见模块文档,且链表必须非空
    #[inline(always)]
    pub unsafe fn list_last_entry(&self) -> &T {
        unsafe { &*self.container_of(self.prev) }
    }

    /// 获取最后一个元素的可变引用(调用方需确保链表非空)
    ///
    /// # Safety
    /// 见模块文档,且链表必须非空
    #[inline(always)]
    pub unsafe fn list_last_entry_mut(&mut self) -> &mut T {
        unsafe { &mut *self.container_of_mut(self.prev) }
    }
}

/// 初始化链表头
#[macro_export]
macro_rules! init_unsafe_list_head {
    ($var:ident, $type:ty, $($member:tt).+ $(,)?) => {
        $var.init_list_head(core::mem::offset_of!($type, $($member).+));
    };
}

/// 定义并初始化链表头
#[macro_export]
macro_rules! define_unsafe_list_head {
    ($var:ident, $type:ty, $($member:tt).+ $(,)?) => {
        let mut $var = $crate::UnsafeListHead::<$type>::new();
        $crate::init_unsafe_list_head!($var, $type, $($member).+);
    };
}

/// 侵入式双向链表节点
#[derive(Clone, Copy)]
pub struct UnsafeListNode<T> {
    next: *mut UnsafeListNode<T>,
    prev: *mut UnsafeListNode<T>,
}

impl<T> Default for UnsafeListNode<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> UnsafeListNode<T> {
    /// 构造链表节点(null 指针,嵌入结构体后由链表操作初始化)
    pub const fn new() -> Self {
        let init = core::ptr::null_mut::<UnsafeListNode<T>>();
        Self { next: init, prev: init }
    }

    #[inline(always)]
    unsafe fn init_list_node(&mut self) {
        let value = self as *mut UnsafeListNode<T>;
        unsafe {
            core::ptr::write_volatile(&raw mut self.next, value);
        }
        self.prev = value;
    }

    #[inline(always)]
    unsafe fn __list_del(prev: &mut UnsafeListNode<T>, next: &mut UnsafeListNode<T>) {
        next.prev = prev;
        unsafe {
            core::ptr::write_volatile(&raw mut prev.next, next);
        }
    }

    #[inline(always)]
    unsafe fn __list_del_entry(&mut self) {
        unsafe {
            Self::__list_del(&mut *self.prev, &mut *self.next);
        }
    }

    /// 从链表中删除节点,指针置为 poison 值
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_del(&mut self) {
        unsafe {
            self.__list_del_entry();
        }
        self.next = LIST_POISON1 as *mut UnsafeListNode<T>;
        self.prev = LIST_POISON2 as *mut UnsafeListNode<T>;
    }

    /// 用 `new` 替换当前节点在链表中的位置
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_replace(&mut self, new: &mut UnsafeListNode<T>) {
        unsafe {
            new.next = self.next;
            (*new.next).prev = new;
            new.prev = self.prev;
            (*new.prev).next = new;
        }
    }

    /// 用 `new` 替换当前节点,并将当前节点重新初始化为自引用
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_replace_init(&mut self, new: &mut UnsafeListNode<T>) {
        unsafe {
            self.list_replace(new);
            self.init_list_node();
        }
    }

    /// 从链表中删除节点,并重新初始化为自引用
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_del_init(&mut self) {
        unsafe {
            self.__list_del_entry();
            self.init_list_node();
        }
    }

    /// 将节点移动到另一个链表的头部
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_move(&mut self, head: &mut UnsafeListHead<T>) {
        unsafe {
            self.__list_del_entry();
            head.list_add(self);
        }
    }

    /// 将节点移动到另一个链表的尾部
    ///
    /// # Safety
    /// 见模块文档
    #[inline(always)]
    pub unsafe fn list_move_tail(&mut self, head: &mut UnsafeListHead<T>) {
        unsafe {
            self.__list_del_entry();
            head.list_add_tail(self);
        }
    }
}

/// 不可变迭代器
pub struct UnsafeListHeadIter<'a, T> {
    front: *const UnsafeListNode<T>,
    back: *const UnsafeListNode<T>,
    head: &'a UnsafeListHead<T>,
}

impl<'a, T> UnsafeListHeadIter<'a, T> {
    fn new(head: &'a UnsafeListHead<T>) -> Self {
        Self { front: head.next.cast_const(), back: head.prev.cast_const(), head }
    }
}

impl<T> UnsafeListHead<T> {
    /// 创建不可变迭代器
    pub fn iter(&self) -> UnsafeListHeadIter<'_, T> {
        UnsafeListHeadIter::new(self)
    }
}

impl<'a, T> IntoIterator for &'a UnsafeListHead<T> {
    type IntoIter = UnsafeListHeadIter<'a, T>;
    type Item = &'a T;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let sentinel = self.head.head_node().cast_const();
            if self.front == sentinel {
                return None;
            }
            let node = self.front;
            if self.front == self.back {
                self.front = sentinel;
                self.back = sentinel;
            } else {
                self.front = (*self.front).next.cast_const();
            }
            Some(&*self.head.container_of(node))
        }
    }
}

impl<'a, T> DoubleEndedIterator for UnsafeListHeadIter<'a, T> {
    fn next_back(&mut self) -> Option<&'a T> {
        unsafe {
            let sentinel = self.head.head_node().cast_const();
            if self.back == sentinel {
                return None;
            }
            let node = self.back;
            if self.front == self.back {
                self.front = sentinel;
                self.back = sentinel;
            } else {
                self.back = (*self.back).prev.cast_const();
            }
            Some(&*self.head.container_of(node))
        }
    }
}

/// 可变迭代器
pub struct UnsafeListHeadIterMut<'a, T> {
    front: *mut UnsafeListNode<T>,
    back: *mut UnsafeListNode<T>,
    head: &'a mut UnsafeListHead<T>,
}

impl<'a, T> UnsafeListHeadIterMut<'a, T> {
    fn new(head: &'a mut UnsafeListHead<T>) -> Self {
        Self { front: head.next, back: head.prev, head }
    }
}

impl<T> UnsafeListHead<T> {
    /// 创建可变迭代器
    pub fn iter_mut(&mut self) -> UnsafeListHeadIterMut<'_, T> {
        UnsafeListHeadIterMut::new(self)
    }
}

impl<'a, T> IntoIterator for &'a mut UnsafeListHead<T> {
    type IntoIter = UnsafeListHeadIterMut<'a, T>;
    type Item = &'a mut T;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let sentinel = self.head.head_node();
            if self.front == sentinel {
                return None;
            }
            let node = self.front;
            if self.front == self.back {
                self.front = sentinel;
                self.back = sentinel;
            } else {
                self.front = (*self.front).next;
            }
            Some(&mut *self.head.container_of_mut(node))
        }
    }
}

impl<'a, T> DoubleEndedIterator for UnsafeListHeadIterMut<'a, T> {
    fn next_back(&mut self) -> Option<&'a mut T> {
        unsafe {
            let sentinel = self.head.head_node();
            if self.back == sentinel {
                return None;
            }
            let node = self.back;
            if self.front == self.back {
                self.front = sentinel;
                self.back = sentinel;
            } else {
                self.back = (*self.back).prev;
            }
            Some(&mut *self.head.container_of_mut(node))
        }
    }
}