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
use core::slice;

use crate::endian::Native;
use crate::error::ErrorKind;
use crate::slice::{binary_search_by, BinarySearch, Slice};
use crate::stack::Stack;
use crate::{Buf, Error, Ref, ZeroCopy};

use super::{prefix, Flavor, LinksRef, StackEntry};

pub(super) struct Walk<'a, 'buf, T, F: Flavor, S: Stack<StackEntry<'buf, T, F>>>
where
    T: ZeroCopy,
{
    // Buffer being walked.
    buf: &'buf Buf,
    // State of the current walker.
    state: WalkState<'a, 'buf, T, F>,
    // A stack which indicates the links who's children we should visit next,
    // and an index corresponding to the child to visit.
    stack: S,
}

impl<'a, 'buf, T, F: Flavor, S> Walk<'a, 'buf, T, F, S>
where
    T: ZeroCopy,
    S: Stack<StackEntry<'buf, T, F>>,
{
    pub(super) fn find(buf: &'buf Buf, links: LinksRef<T, F>, prefix: &'a [u8]) -> Self {
        Self {
            buf,
            state: WalkState::Find(links, prefix),
            stack: S::new(),
        }
    }

    pub(super) fn poll(&mut self) -> Result<Option<(&'buf [u8], &'buf T)>, Error> {
        'outer: loop {
            match self.state {
                WalkState::Find(this, &[]) => {
                    let iter = self.buf.load(this.values)?.iter();

                    if !self.stack.try_push((this, 0, &[])) {
                        return Err(Error::new(ErrorKind::StackOverflow {
                            capacity: S::CAPACITY,
                        }));
                    }

                    self.state = WalkState::Values(&[], iter);
                    continue;
                }
                WalkState::Find(this, string) => {
                    let mut this = this;
                    let mut string = string;
                    let mut len = 0;

                    let node = 'node: loop {
                        let search = binary_search_by(self.buf, this.children, |c| {
                            Ok(self.buf.load(c.string)?.cmp(string))
                        })?;

                        match search {
                            BinarySearch::Found(n) => {
                                break 'node self.buf.load(this.children.get_unchecked(n))?;
                            }
                            BinarySearch::Missing(n) => {
                                // For missing nodes, we need to find any
                                // neighbor for which the current string is a
                                // prefix. So unless `n` is out of bounds we
                                // look at the prior or current index `n`.
                                //
                                // Note that thanks to structural invariants,
                                // only one node may be a matching prefix.
                                let iter = n
                                    .checked_sub(1)
                                    .into_iter()
                                    .chain((n < this.children.len()).then_some(n));

                                for n in iter {
                                    let child = self.buf.load(this.children.get_unchecked(n))?;

                                    // Find common prefix and split nodes if necessary.
                                    let prefix = prefix(self.buf.load(child.string)?, string);

                                    if prefix == 0 {
                                        continue;
                                    }

                                    if prefix != string.len() {
                                        len += prefix;
                                        string = &string[prefix..];
                                        this = child.links;
                                        continue 'node;
                                    }

                                    break 'node child;
                                }

                                // Falling through here indicates that we have
                                // not found anything. Assigning the stack state
                                // with an empty stack will cause the iterator
                                // to continuously return `None`.
                                self.state = WalkState::Stack;
                                continue 'outer;
                            }
                        };
                    };

                    let prefix = prefix_string(node.string, len)?;
                    let prefix = self.buf.load(prefix)?;

                    if !self.stack.try_push((node.links, 0, prefix)) {
                        return Err(Error::new(ErrorKind::StackOverflow {
                            capacity: S::CAPACITY,
                        }));
                    }

                    self.state =
                        WalkState::Values(prefix, self.buf.load(node.links.values)?.iter());
                }
                WalkState::Values(prefix, ref mut values) => {
                    let Some(value) = values.next() else {
                        self.state = WalkState::Stack;
                        continue;
                    };

                    return Ok(Some((prefix, value)));
                }
                WalkState::Stack => loop {
                    let Some((links, index, prefix)) = self.stack.pop() else {
                        break 'outer;
                    };

                    let Some(node) = links.children.get(index) else {
                        continue;
                    };

                    let node = self.buf.load(node)?;

                    let new_prefix = prefix_string(node.string, prefix.len())?;
                    let new_prefix = self.buf.load(new_prefix)?;

                    self.state =
                        WalkState::Values(new_prefix, self.buf.load(node.links.values)?.iter());

                    if !self.stack.try_push((links, index + 1, prefix)) {
                        return Err(Error::new(ErrorKind::StackOverflow {
                            capacity: S::CAPACITY,
                        }));
                    }

                    if !self.stack.try_push((node.links, 0, new_prefix)) {
                        return Err(Error::new(ErrorKind::StackOverflow {
                            capacity: S::CAPACITY,
                        }));
                    }

                    continue 'outer;
                },
            }
        }

        Ok(None)
    }
}

/// Calculate a prefix string based on an existing string in the trie.
///
/// We use the fact that during construction the trie must have been provided a
/// complete string reference, so any substring that we constructed must be
/// prefixed with its complete counterpart.
fn prefix_string<S>(string: S, prefix_len: usize) -> Result<Ref<[u8], Native, usize>, Error>
where
    S: Slice<Item = u8>,
{
    // NB: All of these operations have to be checked, since they are preformed
    // over untrusted data and we'd like to avoid a panic.

    let string_offset = string.offset();
    let string_len = string.len();

    let Some(real_start) = string_offset.checked_sub(prefix_len) else {
        return Err(Error::new(ErrorKind::Underflow {
            at: string_offset,
            len: prefix_len,
        }));
    };

    let Some(real_end) = string_offset.checked_add(string_len) else {
        return Err(Error::new(ErrorKind::Overflow {
            at: string_offset,
            len: string_len,
        }));
    };

    Ref::try_with_metadata(real_start, real_end - real_start)
}

enum WalkState<'a, 'buf, T, F: Flavor>
where
    T: ZeroCopy,
{
    // Initial state where we need to lookup the specified prefix in the trie.
    Find(LinksRef<T, F>, &'a [u8]),
    // Values are being yielded.
    Values(&'buf [u8], slice::Iter<'buf, T>),
    // Stack traversal.
    Stack,
}