Repository navigation
Expand file tree
/
Copy pathpattern.rs
More file actions
62 lines (55 loc) · 1.61 KB
/
Copy pathpattern.rs
File metadata and controls
62 lines (55 loc) · 1.61 KB
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
pub struct SinglePattern {
dfa: &'static [usize],
length: usize,
}
impl SinglePattern {
pub const fn prebuilt(dfa: &'static [usize], length: usize) -> SinglePattern {
SinglePattern {
dfa, length
}
}
pub fn len(&self) -> usize {
self.length
}
#[inline(always)]
pub fn match_against(&self, haystack: &[u8]) -> Option<usize> {
let mut i = 0;
let mut j = 0;
while i < haystack.len() && j < self.length {
j = self.dfa[haystack[i] as usize * self.length + j];
i += 1;
};
if j == self.length {
Some(i - self.length)
} else {
None
}
}
}
// Can't use pub const fn constructor due to Copy trait, so allow directly creating struct publicly for now.
pub struct TrieNode<V: 'static + Copy> {
pub value: Option<V>,
pub children: [Option<&'static TrieNode<V>>; 256],
}
pub struct TrieNodeMatch<V: 'static + Copy> {
pub end: usize,
pub value: V,
}
impl<V: 'static + Copy> TrieNode<V> {
#[inline(always)]
pub fn longest_matching_prefix(&self, text: &[u8]) -> Option<TrieNodeMatch<V>> {
let mut node: &TrieNode<V> = self;
let mut value: Option<TrieNodeMatch<V>> = None;
for (i, &c) in text.iter().enumerate() {
match node.children[c as usize] {
Some(child) => node = child,
None => break,
};
match node.value {
Some(v) => value = Some(TrieNodeMatch { end: i, value: v }),
None => {}
};
};
value
}
}