2019-12-26 00:17:57 -05:00
|
|
|
pub struct SinglePattern {
|
2020-01-31 07:15:35 -05:00
|
|
|
dfa: &'static [usize],
|
|
|
|
length: usize,
|
2019-12-26 00:17:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl SinglePattern {
|
2020-01-31 07:15:35 -05:00
|
|
|
pub const fn prebuilt(dfa: &'static [usize], length: usize) -> SinglePattern {
|
|
|
|
SinglePattern {
|
|
|
|
dfa, length
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-25 09:25:07 -05:00
|
|
|
pub fn len(&self) -> usize {
|
2020-01-31 07:15:35 -05:00
|
|
|
self.length
|
2020-01-25 09:25:07 -05:00
|
|
|
}
|
|
|
|
|
2020-01-31 07:15:35 -05:00
|
|
|
#[inline(always)]
|
2019-12-26 00:17:57 -05:00
|
|
|
pub fn match_against(&self, haystack: &[u8]) -> Option<usize> {
|
2020-01-31 07:15:35 -05:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-12-26 00:17:57 -05:00
|
|
|
|
2020-01-31 07:15:35 -05:00
|
|
|
// 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,
|
|
|
|
}
|
2019-12-26 00:17:57 -05:00
|
|
|
|
2020-01-31 07:15:35 -05:00
|
|
|
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 => {}
|
2019-12-26 00:17:57 -05:00
|
|
|
};
|
|
|
|
};
|
2020-01-31 07:15:35 -05:00
|
|
|
value
|
2019-12-26 00:17:57 -05:00
|
|
|
}
|
|
|
|
}
|
2020-01-31 07:15:35 -05:00
|
|
|
|