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
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct Rawlist {
    pub prev: *mut Rawlist,
    pub next: *mut Rawlist,
}

impl Rawlist {
    pub unsafe fn init(p: *mut Self) {
        (*p).prev = p;
        (*p).next = p;
    }

    pub unsafe fn is_empty(head: *mut Self) -> bool {
        (*head).next == head
    }

    pub unsafe fn front(head: *mut Self) -> *mut Self {
        (*head).next
    }

    unsafe fn insert(cur: *mut Self, prev: *mut Self, next: *mut Self) {
        (*next).prev = cur;
        (*cur).next = next;
        (*cur).prev = prev;
        (*prev).next = cur;
    }

    unsafe fn del(prev: *mut Self, next: *mut Self) {
        (*next).prev = prev;
        (*prev).next = next;
    }

    pub unsafe fn drop(cur: *mut Self) {
        Self::del((*cur).prev, (*cur).next);
    }

    pub unsafe fn push_front(head: *mut Self, cur: *mut Self) {
        Self::insert(cur, head, (*head).next);
    }

    pub unsafe fn pop_front(head: *mut Self) -> *mut Self {
        let front = Self::front(head);
        Self::drop(front);
        front
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::ptr;

    #[test]
    fn test_push_pop_front() {
        const N: usize = 10;
        let mut item: [Rawlist; N] = [Rawlist {
            prev: ptr::null_mut(),
            next: ptr::null_mut(),
        }; N];
        let mut head = Rawlist {
            prev: ptr::null_mut(),
            next: ptr::null_mut(),
        };
        unsafe {
            Rawlist::init(&mut head);
            assert_eq!(Rawlist::is_empty(&mut head), true);
            for i in 0..N {
                Rawlist::push_front(&mut head, &mut item[i]);
                assert_eq!(Rawlist::is_empty(&mut head), false);
                assert_eq!(Rawlist::front(&mut head), &mut item[i] as *mut Rawlist);
            }

            for i in 0..N {
                assert_eq!(Rawlist::is_empty(&mut head), false);
                assert_eq!(
                    Rawlist::front(&mut head),
                    &mut item[N - 1 - i] as *mut Rawlist
                );

                let p = Rawlist::pop_front(&mut head);
                assert_eq!(p, &mut item[N - 1 - i] as *mut Rawlist);
            }
            assert_eq!(Rawlist::is_empty(&mut head), true);
        }
    }
}