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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::build_helper::{BuildHelper, Profile};
use crate::charwise::{CharwiseDoubleArrayAhoCorasick, CodeMapper, MatchKind, State};
use crate::errors::{DaachorseError, Result};
use crate::nfa_builder::NfaBuilder;
use crate::nfa_builder::DEAD_STATE_ID;
use crate::utils::FromU32;
use crate::DEAD_STATE_IDX;
// Specialized [`NfaBuilder`] handling labels of `char`.
type CharwiseNfaBuilder<V> = NfaBuilder<char, V>;
/// Builder for [`CharwiseDoubleArrayAhoCorasick`].
pub struct CharwiseDoubleArrayAhoCorasickBuilder {
states: Vec<State>,
mapper: CodeMapper,
match_kind: MatchKind,
corpus: Vec<String>,
}
impl Default for CharwiseDoubleArrayAhoCorasickBuilder {
fn default() -> Self {
Self::new()
}
}
impl CharwiseDoubleArrayAhoCorasickBuilder {
/// Creates a new [`CharwiseDoubleArrayAhoCorasickBuilder`].
///
/// # Examples
///
/// ```
/// use daachorse::CharwiseDoubleArrayAhoCorasickBuilder;
///
/// let patterns = vec!["全世界", "世界", "に"];
///
/// let builder = CharwiseDoubleArrayAhoCorasickBuilder::new();
/// let pma = builder.build(patterns).unwrap();
///
/// let mut it = pma.find_iter("全世界中に");
///
/// let m = it.next().unwrap();
/// assert_eq!((0, 9, 0), (m.start(), m.end(), m.value()));
///
/// let m = it.next().unwrap();
/// assert_eq!((12, 15, 2), (m.start(), m.end(), m.value()));
///
/// assert_eq!(None, it.next());
/// ```
#[must_use]
pub fn new() -> Self {
Self {
states: vec![],
mapper: CodeMapper::default(),
match_kind: MatchKind::Standard,
corpus: vec![],
}
}
/// Specifies [`MatchKind`] to build.
///
/// # Arguments
///
/// * `kind` - Match kind.
#[must_use]
pub const fn match_kind(mut self, kind: MatchKind) -> Self {
self.match_kind = kind;
self
}
/// Specifies a corpus of sample documents for the profile-guided layout optimization.
///
/// States frequently accessed in scanning the corpus are packed densely at small indices
/// so that matching on documents similar to the corpus becomes more cache-efficient.
/// The corpus never changes match results, only the memory layout of the automaton.
///
/// Since the states accessed in scanning the corpus are placed by scanning all the blocks
/// of the double array, the construction time can increase, especially when the corpus
/// covers most states of a large pattern set.
///
/// # Arguments
///
/// * `haystacks` - Sample documents to be scanned.
///
/// # Examples
///
/// ```
/// use daachorse::CharwiseDoubleArrayAhoCorasickBuilder;
///
/// let patterns = vec!["全世界", "世界", "に"];
/// let pma = CharwiseDoubleArrayAhoCorasickBuilder::new()
/// .corpus(["全世界中に"])
/// .build(patterns)
/// .unwrap();
///
/// let mut it = pma.find_iter("全世界中に");
///
/// let m = it.next().unwrap();
/// assert_eq!((0, 9, 0), (m.start(), m.end(), m.value()));
///
/// let m = it.next().unwrap();
/// assert_eq!((12, 15, 2), (m.start(), m.end(), m.value()));
///
/// assert_eq!(None, it.next());
/// ```
#[must_use]
pub fn corpus<I, P>(mut self, haystacks: I) -> Self
where
I: IntoIterator<Item = P>,
P: AsRef<str>,
{
self.corpus = haystacks
.into_iter()
.map(|h| h.as_ref().to_string())
.collect();
self
}
/// Builds and returns a new [`CharwiseDoubleArrayAhoCorasick`] from input patterns. The value
/// `i` is automatically associated with `patterns[i]`.
///
/// # Arguments
///
/// * `patterns` - List of patterns.
///
/// # Errors
///
/// [`DaachorseError`] is returned when
/// - the conversion from the index `i` to the specified type `V` fails,
/// - the scale of `patterns` exceeds the expected one, or
/// - the scale of the resulting automaton exceeds the expected one.
///
/// # Examples
///
/// ```
/// use daachorse::CharwiseDoubleArrayAhoCorasickBuilder;
///
/// let patterns = vec!["全世界", "世界", "に"];
/// let pma = CharwiseDoubleArrayAhoCorasickBuilder::new()
/// .build(patterns)
/// .unwrap();
///
/// let mut it = pma.find_iter("全世界中に");
///
/// let m = it.next().unwrap();
/// assert_eq!((0, 9, 0), (m.start(), m.end(), m.value()));
///
/// let m = it.next().unwrap();
/// assert_eq!((12, 15, 2), (m.start(), m.end(), m.value()));
///
/// assert_eq!(None, it.next());
/// ```
pub fn build<I, P, V>(self, patterns: I) -> Result<CharwiseDoubleArrayAhoCorasick<V>>
where
I: IntoIterator<Item = P>,
P: AsRef<str>,
V: Copy + TryFrom<usize>,
{
// The following code implicitly replaces large indices with 0,
// but build_with_values() returns an error variant for such iterators.
let patvals: Vec<_> = patterns
.into_iter()
.enumerate()
.map(|(i, p)| V::try_from(i).map(|i| (p, i)))
.collect::<Result<_, _>>()
.map_err(|_| DaachorseError::invalid_conversion("index", "V"))?;
self.build_with_values(patvals)
}
/// Builds and returns a new [`CharwiseDoubleArrayAhoCorasick`] from input pattern-value pairs.
///
/// # Arguments
///
/// * `patvals` - List of pattern-value pairs.
///
/// # Errors
///
/// [`DaachorseError`] is returned when
/// - the scale of `patvals` exceeds the expected one, or
/// - the scale of the resulting automaton exceeds the expected one.
///
/// # Examples
///
/// ```
/// use daachorse::CharwiseDoubleArrayAhoCorasickBuilder;
///
/// let patvals = vec![("全世界", 0), ("世界", 10), ("に", 100)];
/// let pma = CharwiseDoubleArrayAhoCorasickBuilder::new()
/// .build_with_values(patvals)
/// .unwrap();
///
/// let mut it = pma.find_iter("全世界中に");
///
/// let m = it.next().unwrap();
/// assert_eq!((0, 9, 0), (m.start(), m.end(), m.value()));
///
/// let m = it.next().unwrap();
/// assert_eq!((12, 15, 100), (m.start(), m.end(), m.value()));
///
/// assert_eq!(None, it.next());
/// ```
pub fn build_with_values<I, P, V>(
mut self,
patvals: I,
) -> Result<CharwiseDoubleArrayAhoCorasick<V>>
where
I: IntoIterator<Item = (P, V)>,
P: AsRef<str>,
V: Copy,
{
let nfa = self.build_original_nfa_and_mapper(patvals)?;
let profile = if self.corpus.is_empty() {
Profile::default()
} else {
self.profile_corpus(&nfa)
};
self.build_double_array(&nfa, &profile)?;
// -1 is for dead state
let num_states = u32::try_from(nfa.states.len() - 1)
.map_err(|_| DaachorseError::automaton_scale("num_states", u32::MAX))?;
Ok(CharwiseDoubleArrayAhoCorasick {
states: self.states,
mapper: self.mapper,
outputs: nfa.outputs,
match_kind: self.match_kind,
num_states,
})
}
fn build_original_nfa_and_mapper<I, P, V>(
&mut self,
patvals: I,
) -> Result<CharwiseNfaBuilder<V>>
where
I: IntoIterator<Item = (P, V)>,
P: AsRef<str>,
V: Copy,
{
let mut nfa = CharwiseNfaBuilder::new(self.match_kind);
let mut freqs = vec![];
{
let mut chars = vec![];
for (pattern, value) in patvals {
chars.clear();
pattern.as_ref().chars().for_each(|c| chars.push(c));
nfa.add(&chars, value)?;
for &c in &chars {
let c = usize::from_u32(u32::from(c));
if freqs.len() <= c {
freqs.resize(c + 1, 0);
}
freqs[c] += 1;
}
}
}
self.mapper = CodeMapper::new(&freqs);
let q = match self.match_kind {
MatchKind::Standard => nfa.build_fails(),
MatchKind::LeftmostLongest | MatchKind::LeftmostFirst => nfa.build_fails_leftmost(),
};
nfa.build_outputs(&q);
Ok(nfa)
}
fn profile_corpus<V>(&self, nfa: &CharwiseNfaBuilder<V>) -> Profile
where
V: Copy,
{
let mut profile = Profile::default();
profile.resize(nfa.states.len());
let mut chars = vec![];
for haystack in &self.corpus {
chars.clear();
chars.extend(haystack.chars());
// The character-wise version has no dense root table, and characters not in the
// mapper reset the state to the root without accessing the double array.
nfa.profile_haystack(&chars, &mut profile, false, |c| {
self.mapper.get(c).is_some()
});
}
profile
}
fn build_double_array<V>(
&mut self,
nfa: &CharwiseNfaBuilder<V>,
profile: &Profile,
) -> Result<()>
where
V: Copy,
{
let block_len = self.mapper.block_len();
let groups = nfa.sibling_groups(profile, |c| self.mapper.get(c).unwrap());
let helper = BuildHelper::new(&groups, nfa.states.len(), block_len, false)?;
self.states
.resize(usize::from_u32(helper.num_elements()), State::default());
for group in &groups {
let parent_idx = helper.idx_map[usize::from_u32(group.parent)];
for &(_, child_id) in &group.children {
self.states[usize::from_u32(helper.idx_map[usize::from_u32(child_id)])]
.set_check(parent_idx);
}
// BuildHelper::new() assigns a BASE value to every group.
self.states[usize::from_u32(parent_idx)]
.set_base(helper.bases[usize::from_u32(group.parent)].unwrap());
}
self.set_fails_and_outputs(nfa, &helper.idx_map);
Ok(())
}
fn set_fails_and_outputs<V>(&mut self, nfa: &CharwiseNfaBuilder<V>, state_id_map: &[u32]) {
for (i, s) in nfa.states.iter().enumerate() {
if i == usize::from_u32(DEAD_STATE_ID) {
continue;
}
let idx = usize::from_u32(state_id_map[i]);
debug_assert_ne!(idx, usize::from_u32(DEAD_STATE_IDX));
self.states[idx].set_output_pos(s.output_pos.get());
let fail_id = s.fail.get();
if fail_id == DEAD_STATE_ID {
self.states[idx].set_fail(DEAD_STATE_IDX);
} else {
let fail_idx = state_id_map[usize::from_u32(fail_id)];
debug_assert_ne!(fail_idx, DEAD_STATE_IDX);
self.states[idx].set_fail(fail_idx);
}
}
}
}