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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use core::num::NonZeroU32;
use alloc::vec::Vec;
use crate::charwise::{CharwiseDoubleArrayAhoCorasick, CodeMapper, MatchKind, State};
use crate::charwise::{DEAD_STATE_IDX, ROOT_STATE_IDX};
use crate::errors::{DaachorseError, Result};
use crate::nfa_builder::NfaBuilder;
use crate::nfa_builder::{DEAD_STATE_ID, ROOT_STATE_ID};
use crate::utils::FromU32;
use crate::BuildHelper;
// 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,
block_len: u32,
num_free_blocks: u32,
}
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,
block_len: 0,
num_free_blocks: 16,
}
}
/// 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 the number of last blocks to search bases.
///
/// The smaller the number is, the faster the construction time will be; however, the memory
/// efficiency can be degraded.
///
/// # Arguments
///
/// * `n` - The number of last blocks.
///
/// # Panics
///
/// `n` must be greater than or equal to 1.
#[must_use]
pub const fn num_free_blocks(mut self, n: u32) -> Self {
assert!(n >= 1);
self.num_free_blocks = n;
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
/// - `patterns` is empty,
/// - `patterns` contains entries of length zero,
/// - `patterns` contains duplicate entries,
/// - 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
/// - `patvals` is empty,
/// - `patvals` contains patterns of length zero,
/// - `patvals` contains duplicate patterns,
/// - 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)?;
self.build_double_array(&nfa)?;
// -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);
if nfa.len == 0 {
return Err(DaachorseError::invalid_argument("patvals.len()", ">=", 1));
}
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 build_double_array<V>(&mut self, nfa: &CharwiseNfaBuilder<V>) -> Result<()> {
let mut helper = self.init_array()?;
let mut state_id_map = vec![DEAD_STATE_IDX; nfa.states.len()];
state_id_map[usize::from_u32(ROOT_STATE_ID)] = ROOT_STATE_IDX;
// Arranges base & check values
let mut stack = vec![ROOT_STATE_ID];
let mut mapped = vec![];
while let Some(state_id) = stack.pop() {
debug_assert_ne!(state_id, DEAD_STATE_ID);
let state = &nfa.states[usize::from_u32(state_id)];
let state_idx = state_id_map[usize::from_u32(state_id)];
debug_assert_ne!(state_idx, DEAD_STATE_IDX);
let s = &state.borrow();
if s.edges.is_empty() {
continue;
}
mapped.clear();
for (&label, &child_id) in &s.edges {
mapped.push((self.mapper.get(label).unwrap(), child_id));
}
mapped.sort_by_key(|x| x.0);
let base = self.find_base(&mapped, &helper);
if self.states.len() <= usize::from_u32(base.get()) {
self.extend_array(&mut helper)?;
}
for &(c, child_id) in &mapped {
let child_idx = base.get() ^ c;
helper.use_index(child_idx);
self.states[usize::from_u32(child_idx)].set_check(state_idx);
state_id_map[usize::from_u32(child_id)] = child_idx;
stack.push(child_id);
}
self.states[usize::from_u32(state_idx)].set_base(base);
}
// Sets fail & output_pos values
for (i, state) 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));
let s = &state.borrow();
self.states[idx].set_output_pos(s.output_pos);
let fail_id = s.fail;
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);
}
}
self.states.shrink_to_fit();
Ok(())
}
fn init_array(&mut self) -> Result<BuildHelper> {
self.block_len = self.mapper.alphabet_size().next_power_of_two().max(2);
self.states
.resize(usize::from_u32(self.block_len), State::default());
let mut helper = BuildHelper::new(self.block_len, self.num_free_blocks)?;
helper.push_block().unwrap();
helper.use_index(ROOT_STATE_IDX);
helper.use_index(DEAD_STATE_IDX);
Ok(helper)
}
#[inline(always)]
fn find_base(&self, edges: &[(u32, u32)], helper: &BuildHelper) -> NonZeroU32 {
debug_assert!(!edges.is_empty());
for idx in helper.vacant_iter() {
let base = idx ^ edges[0].0;
if let Some(base) = Self::verify_base(base, edges, helper) {
return base;
}
}
// len() is not 0 since states has at least block_len items.
// The following value is always larger than or equal to len() since block_len is
// alphabet_size().next_power_of_two().
NonZeroU32::new(u32::try_from(self.states.len()).unwrap() ^ edges[0].0).unwrap()
}
#[inline(always)]
fn verify_base(base: u32, edges: &[(u32, u32)], helper: &BuildHelper) -> Option<NonZeroU32> {
for &(c, _) in edges {
let idx = base ^ c;
if helper.is_used_index(idx) {
return None;
}
}
NonZeroU32::new(base)
}
#[inline(always)]
fn extend_array(&mut self, helper: &mut BuildHelper) -> Result<()> {
if self.states.len() > usize::from_u32(u32::MAX - self.block_len) {
return Err(DaachorseError::automaton_scale("states.len()", u32::MAX));
}
helper.push_block()?;
self.states.resize(
self.states.len() + usize::from_u32(self.block_len),
State::default(),
);
Ok(())
}
}