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
use std::ops::Deref;

use crate::graph::{Graph, Disambiguate, Range, Fork, NodeId};

#[derive(PartialEq, Clone, Hash)]
pub struct Rope {
    pub pattern: Pattern,
    pub then: NodeId,
    pub miss: Miss,
}

#[derive(PartialEq, Clone, Hash)]
pub struct Pattern(pub Vec<Range>);

impl Deref for Pattern {
    type Target = [Range];

    fn deref(&self) -> &[Range] {
        &self.0
    }
}

/// Because Ropes could potentially fail a match mid-pattern,
/// a regular `Option` is not sufficient here.
#[derive(PartialEq, Clone, Copy, Hash)]
pub enum Miss {
    /// Same as Option::None, error on fail
    None,
    /// Jump to id if first byte does not match, fail on partial match
    First(NodeId),
    /// Jump to id on partial or empty match
    Any(NodeId),
}

impl Miss {
    pub fn is_none(&self) -> bool {
        matches!(self, Miss::None)
    }

    pub fn first(self) -> Option<NodeId> {
        match self {
            Miss::First(id) | Miss::Any(id) => Some(id),
            _ => None,
        }
    }

    pub fn take_first(&mut self) -> Option<NodeId> {
        match *self {
            Miss::First(id) => {
                *self = Miss::None;

                Some(id)
            },
            Miss::Any(id) => Some(id),
            Miss::None => None,
        }
    }
}

impl From<Option<NodeId>> for Miss {
    fn from(miss: Option<NodeId>) -> Self {
        match miss {
            Some(id) => Miss::First(id),
            None => Miss::None,
        }
    }
}

impl From<NodeId> for Miss {
    fn from(id: NodeId) -> Self {
        Miss::First(id)
    }
}

impl Rope {
    pub fn new<P>(pattern: P, then: NodeId) -> Self
    where
        P: Into<Pattern>,
    {
        Rope {
            pattern: pattern.into(),
            then,
            miss: Miss::None,
        }
    }

    pub fn miss<M>(mut self, miss: M) -> Self
    where
        M: Into<Miss>,
    {
        self.miss = miss.into();
        self
    }

    pub fn miss_any(mut self, miss: NodeId) -> Self {
        self.miss = Miss::Any(miss);
        self
    }

    pub fn into_fork<T>(mut self, graph: &mut Graph<T>) -> Fork
    where
        T: Disambiguate,
    {
        let first = self.pattern.0.remove(0);
        let miss = self.miss.take_first();

        // The new fork will lead to a new rope,
        // or the old target if no new rope was created
        let then = match self.pattern.len() {
            0 => self.then,
            _ => graph.push(self),
        };

        Fork::new().branch(first, then).miss(miss)
    }

    pub fn prefix(&self, other: &Self) -> Option<(Pattern, Miss)> {
        let count = self.pattern
            .iter()
            .zip(other.pattern.iter())
            .take_while(|(a, b)| a == b)
            .count();

        let pattern = match count {
            0 => return None,
            n => self.pattern[..n].into(),
        };
        let miss = match (self.miss, other.miss) {
            (Miss::None, miss) => miss,
            (miss, Miss::None) => miss,
            _ => return None,
        };

        Some((pattern, miss))
    }

    pub fn split_at<T>(mut self, at: usize, graph: &mut Graph<T>) -> Option<Rope>
    where
        T: Disambiguate,
    {
        match at {
            0 => return None,
            n if n == self.pattern.len() => return Some(self),
            _ => (),
        }

        let (this, next) = self.pattern.split_at(at);

        let next_miss = match self.miss {
            Miss::Any(_) => self.miss,
            _ => Miss::None,
        };

        let next = graph.push(Rope {
            pattern: next.into(),
            miss: next_miss,
            then: self.then,
        });

        self.pattern = this.into();
        self.then = next;

        Some(self)
    }

    pub fn remainder<T>(mut self, at: usize, graph: &mut Graph<T>) -> NodeId
    where
        T: Disambiguate,
    {
        self.pattern = self.pattern[at..].into();

        match self.pattern.len() {
            0 => self.then,
            _ => graph.push(self),
        }
    }

    pub fn shake<T>(&self, graph: &Graph<T>, filter: &mut [bool]) {
        if let Some(id) = self.miss.first() {
            if !filter[id.get()] {
                filter[id.get()] = true;
                graph[id].shake(graph, filter);
            }
        }

        if !filter[self.then.get()] {
            filter[self.then.get()] = true;
            graph[self.then].shake(graph, filter);
        }
    }
}

impl Pattern {
    pub fn to_bytes(&self) -> Option<Vec<u8>> {
        let mut out = Vec::with_capacity(self.len());

        for range in self.iter() {
            out.push(range.as_byte()?);
        }

        Some(out)
    }
}

impl<T> From<&[T]> for Pattern
where
    T: Into<Range> + Copy,
{
    fn from(slice: &[T]) -> Self {
        Pattern(slice.iter().copied().map(Into::into).collect())
    }
}

impl<T> From<Vec<T>> for Pattern
where
    T: Into<Range>,
{
    fn from(vec: Vec<T>) -> Self {
        Pattern(vec.into_iter().map(Into::into).collect())
    }
}

impl From<&str> for Pattern {
    fn from(slice: &str) -> Self {
        slice.as_bytes().into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::Node;
    use pretty_assertions::assert_eq;

    #[test]
    fn into_fork() {
        let mut graph = Graph::new();

        let leaf = graph.push(Node::Leaf("LEAF"));
        let rope = Rope::new("foobar", leaf);

        let fork = rope.into_fork(&mut graph);

        assert_eq!(leaf, NodeId::new(1));
        assert_eq!(fork, Fork::new().branch(b'f', NodeId::new(2)));
        assert_eq!(graph[NodeId::new(2)], Rope::new("oobar", leaf));
    }

    #[test]
    fn into_fork_one_byte() {
        let mut graph = Graph::new();

        let leaf = graph.push(Node::Leaf("LEAF"));
        let rope = Rope::new("!", leaf);

        let fork = rope.into_fork(&mut graph);

        assert_eq!(leaf, NodeId::new(1));
        assert_eq!(fork, Fork::new().branch(b'!', NodeId::new(1)));
    }

    #[test]
    fn into_fork_miss_any() {
        let mut graph = Graph::new();

        let leaf = graph.push(Node::Leaf("LEAF"));
        let rope = Rope::new("42", leaf).miss_any(NodeId::new(42));

        let fork = rope.into_fork(&mut graph);

        assert_eq!(leaf, NodeId::new(1));
        assert_eq!(fork, Fork::new().branch(b'4', NodeId::new(2)).miss(NodeId::new(42)));
        assert_eq!(graph[NodeId::new(2)], Rope::new("2", leaf).miss_any(NodeId::new(42)));
    }

    #[test]
    fn into_fork_miss_first() {
        let mut graph = Graph::new();

        let leaf = graph.push(Node::Leaf("LEAF"));
        let rope = Rope::new("42", leaf).miss(Miss::First(NodeId::new(42)));

        let fork = rope.into_fork(&mut graph);

        assert_eq!(leaf, NodeId::new(1));
        assert_eq!(fork, Fork::new().branch(b'4', NodeId::new(2)).miss(NodeId::new(42)));
        assert_eq!(graph[NodeId::new(2)], Rope::new("2", leaf));
    }

    #[test]
    fn split_at() {
        let mut graph = Graph::new();

        let leaf = graph.push(Node::Leaf("LEAF"));
        let rope = Rope::new("foobar", leaf);

        assert_eq!(rope.clone().split_at(6, &mut graph).unwrap(), rope);

        let split = rope.split_at(3, &mut graph).unwrap();
        let expected_id = NodeId::new(leaf.get() + 1);

        assert_eq!(split, Rope::new("foo", expected_id));
        assert_eq!(graph[expected_id], Rope::new("bar", leaf));
    }

    #[test]
    fn pattern_to_bytes() {
        let pat = Pattern::from("foobar");

        assert_eq!(pat.to_bytes().unwrap(), b"foobar");

        let ranges = Pattern::from(vec![0..=0, 42..=42, b'{'..=b'}']);

        assert_eq!(ranges.to_bytes(), None);
    }
}