difft/diff/
stack.rs

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
use bumpalo::Bump;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Node<'b, T> {
    val: T,
    next: Option<&'b Node<'b, T>>,
}

/// A persistent stack.
///
/// This is similar to `Stack` from the rpds crate, but it's faster
/// and uses less memory.
#[derive(Debug, Clone, Default)]
pub(crate) struct Stack<'b, T> {
    head: Option<&'b Node<'b, T>>,
}

impl<T: PartialEq> PartialEq for Stack<'_, T> {
    fn eq(&self, other: &Self) -> bool {
        let mut lhs = self.head;
        let mut rhs = other.head;
        loop {
            match (lhs, rhs) {
                (None, None) => return true,
                (Some(lhs_node), Some(rhs_node)) => {
                    // Optimisation: in a persistent stack, we often
                    // end up with shared tails. If both tails are the
                    // same pointer, it's definitely equal.
                    if std::ptr::eq(lhs_node, rhs_node) {
                        return true;
                    }

                    if lhs_node.val != rhs_node.val {
                        return false;
                    }
                    lhs = lhs_node.next;
                    rhs = rhs_node.next;
                }
                _ => return false,
            }
        }
    }
}

impl<T: Eq> Eq for Stack<'_, T> {}

impl<'b, T> Stack<'b, T> {
    pub(crate) fn new() -> Self {
        Self { head: None }
    }

    pub(crate) fn peek(&self) -> Option<&T> {
        self.head.map(|n| &n.val)
    }

    pub(crate) fn pop(&self) -> Option<Self> {
        self.head.map(|n| Self { head: n.next })
    }

    pub(crate) fn push(&self, v: T, alloc: &'b Bump) -> Self {
        Self {
            head: Some(alloc.alloc(Node {
                val: v,
                next: self.head,
            })),
        }
    }

    // O(n)
    pub(crate) fn size(&self) -> usize {
        std::iter::successors(self.head, |&n| n.next).count()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.head.is_none()
    }
}