Skip to main content

tldr_cli/commands/remaining/difftastic/
stack.rs

1use bumpalo::Bump;
2
3#[derive(Debug, Clone, Default, PartialEq, Eq)]
4struct Node<'b, T> {
5    val: T,
6    next: Option<&'b Node<'b, T>>,
7}
8
9/// A persistent stack.
10///
11/// This is similar to `Stack` from the rpds crate, but it's faster
12/// and uses less memory.
13#[derive(Debug, Clone, Default, PartialEq, Eq)]
14pub struct Stack<'b, T> {
15    head: Option<&'b Node<'b, T>>,
16}
17
18impl<'b, T> Stack<'b, T> {
19    pub fn new() -> Self {
20        Self { head: None }
21    }
22
23    pub fn peek(&self) -> Option<&T> {
24        self.head.map(|n| &n.val)
25    }
26
27    pub fn pop(&self) -> Option<Self> {
28        self.head.map(|n| Self { head: n.next })
29    }
30
31    pub fn push(&self, v: T, alloc: &'b Bump) -> Self {
32        Self {
33            head: Some(alloc.alloc(Node {
34                val: v,
35                next: self.head,
36            })),
37        }
38    }
39
40    // O(n)
41    pub fn size(&self) -> usize {
42        std::iter::successors(self.head, |&n| n.next).count()
43    }
44
45    pub fn is_empty(&self) -> bool {
46        self.head.is_none()
47    }
48}