-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathac.go
454 lines (362 loc) · 9.4 KB
/
ac.go
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Package ac provides an implementation of the Aho-Corasick string matching
// algorithm. Throughout this code []byte is referred to
// as a blice.
//
// http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm
//
// Copyright (c) 2013 CloudFlare, Inc.
//
// Originally from https://github.com/cloudflare/ahocorasick
package ac
import (
"container/list"
)
const maxchar = 256
// A node in the trie structure used to implement Aho-Corasick
type node struct {
root bool // true if this is the root
output bool // True means this node represents a blice that should
// be output when matching
b string // The path at this node
index int // index into original dictionary if output is true
counter int // Set to the value of the Matcher.counter when a
// match is output to prevent duplicate output
// The use of fixed size arrays is space-inefficient but fast for
// lookups.
child [maxchar]*node // A non-nil entry in this array means that the
// index represents a byte value which can be
// appended to the current node. Blices in the
// trie are built up byte by byte through these
// child node pointers.
fails [maxchar]*node // Where to fail to (by following the fail
// pointers) for each possible byte
suffix *node // Pointer to the longest possible strict suffix of
// this node
fail *node // Pointer to the next node which is in the dictionary
// which can be reached from here following suffixes. Called fail
// because it is used to fallback in the trie when a match fails.
}
// Matcher contains a list of blices to match against
type Matcher struct {
counter int // Counts the number of matches done, and is used to
// prevent output of multiple matches of the same string
trie []node // preallocated block of memory containing all the
// nodes
extent int // offset into trie that is currently free
root *node // Points to trie[0]
}
// findBlice looks for a blice in the trie starting from the root and
// returns a pointer to the node representing the end of the blice. If
// the blice is not found it returns nil.
func (m *Matcher) findBlice(b string) *node {
n := &m.trie[0]
for n != nil && len(b) > 0 {
n = n.child[int(b[0])]
b = b[1:]
}
return n
}
// getFreeNode: gets a free node structure from the Matcher's trie
// pool and updates the extent to point to the next free node.
func (m *Matcher) getFreeNode() *node {
m.extent++
if m.extent == 1 {
m.root = &m.trie[0]
m.root.root = true
}
return &m.trie[m.extent-1]
}
// buildTrie builds the fundamental trie structure from a set of
// blices.
func (m *Matcher) buildTrie(dictionary [][]byte) {
// Work out the maximum size for the trie (all dictionary entries
// are distinct plus the root). This is used to preallocate memory
// for it.
max := 1
for _, blice := range dictionary {
max += len(blice)
}
m.trie = make([]node, max)
// Calling this an ignoring its argument simply allocated
// m.trie[0] which will be the root element
m.getFreeNode()
// This loop builds the nodes in the trie by following through
// each dictionary entry building the children pointers.
for _, blice := range dictionary {
n := m.root
for i, b := range blice {
c := n.child[int(b)]
if c == nil {
c = m.getFreeNode()
n.child[int(b)] = c
c.b = string(blice[0 : i+1])
// Nodes directly under the root node will have the
// root as their fail point as there are no suffixes
// possible.
if i == 0 {
c.fail = m.root
}
c.suffix = m.root
}
n = c
}
// The last value of n points to the node representing a
// dictionary entry
n.output = true
n.index = len(blice)
}
l := new(list.List)
l.PushBack(m.root)
for l.Len() > 0 {
n := l.Remove(l.Front()).(*node)
for i := 0; i < maxchar; i++ {
c := n.child[i]
if c != nil {
l.PushBack(c)
for j := 1; j < len(c.b); j++ {
c.fail = m.findBlice(c.b[j:])
if c.fail != nil {
break
}
}
if c.fail == nil {
c.fail = m.root
}
for j := 1; j < len(c.b); j++ {
s := m.findBlice(c.b[j:])
if s != nil && s.output {
c.suffix = s
break
}
}
}
}
}
for i := 0; i < m.extent; i++ {
for c := 0; c < maxchar; c++ {
n := &m.trie[i]
for n.child[c] == nil && !n.root {
n = n.fail
}
m.trie[i].fails[c] = n
}
}
m.trie = m.trie[:m.extent]
}
// buildTrieString builds the fundamental trie structure from a []string
func (m *Matcher) buildTrieString(dictionary []string) {
// Work out the maximum size for the trie (all dictionary entries
// are distinct plus the root). This is used to preallocate memory
// for it.
max := 1
for _, blice := range dictionary {
max += len(blice)
}
m.trie = make([]node, max)
// Calling this an ignoring its argument simply allocated
// m.trie[0] which will be the root element
m.getFreeNode()
// This loop builds the nodes in the trie by following through
// each dictionary entry building the children pointers.
for _, blice := range dictionary {
n := m.root
for i := 0; i < len(blice); i++ {
b := int(blice[i])
c := n.child[b]
if c == nil {
c = m.getFreeNode()
n.child[b] = c
c.b = blice[0 : i+1]
// Nodes directly under the root node will have the
// root as their fail point as there are no suffixes
// possible.
if i == 0 {
c.fail = m.root
}
c.suffix = m.root
}
n = c
}
// The last value of n points to the node representing a
// dictionary entry
n.output = true
n.index = len(blice)
}
l := new(list.List)
l.PushBack(m.root)
for l.Len() > 0 {
n := l.Remove(l.Front()).(*node)
for i := 0; i < maxchar; i++ {
c := n.child[i]
if c != nil {
l.PushBack(c)
for j := 1; j < len(c.b); j++ {
c.fail = m.findBlice(c.b[j:])
if c.fail != nil {
break
}
}
if c.fail == nil {
c.fail = m.root
}
for j := 1; j < len(c.b); j++ {
s := m.findBlice(c.b[j:])
if s != nil && s.output {
c.suffix = s
break
}
}
}
}
}
for i := 0; i < m.extent; i++ {
for c := 0; c < maxchar; c++ {
n := &m.trie[i]
for n.child[c] == nil && !n.root {
n = n.fail
}
m.trie[i].fails[c] = n
}
}
m.trie = m.trie[:m.extent]
}
// Compile creates a new Matcher using a list of []byte
func Compile(dictionary [][]byte) (*Matcher, error) {
m := new(Matcher)
m.buildTrie(dictionary)
// no error for now
return m, nil
}
// MustCompile returns a Matcher or panics
func MustCompile(dictionary [][]byte) *Matcher {
m, err := Compile(dictionary)
if err != nil {
panic(err)
}
return m
}
// CompileString creates a new Matcher used to match against a set
// of strings (this is a helper to make initialization easy)
func CompileString(dictionary []string) (*Matcher, error) {
m := new(Matcher)
m.buildTrieString(dictionary)
return m, nil
}
// MustCompileString returns a Matcher or panics
func MustCompileString(dictionary []string) *Matcher {
m, err := CompileString(dictionary)
if err != nil {
panic(err)
}
return m
}
// FindAll searches in for blices and returns all the blices found
// in the original dictionary
func (m *Matcher) FindAll(in []byte) [][]byte {
m.counter++
var hits [][]byte
n := m.root
for idx, b := range in {
c := int(b)
if !n.root && n.child[c] == nil {
n = n.fails[c]
}
if n.child[c] != nil {
f := n.child[c]
n = f
if f.output && f.counter != m.counter {
hits = append(hits, in[idx-f.index+1:idx+1])
f.counter = m.counter
}
for !f.suffix.root {
f = f.suffix
if f.counter != m.counter {
hits = append(hits, in[idx-f.index+1:idx+1])
f.counter = m.counter
} else {
// There's no point working our way up the
// suffixes if it's been done before for this call
// to Match. The matches are already in hits.
break
}
}
}
}
return hits
}
// FindAllString searches in for blices and returns all the blices (as strings) found as
// in the original dictionary
func (m *Matcher) FindAllString(in string) []string {
m.counter++
var hits []string
n := m.root
slen := len(in)
for idx := 0; idx < slen; idx++ {
c := int(in[idx])
if !n.root && n.child[c] == nil {
n = n.fails[c]
}
if n.child[c] != nil {
f := n.child[c]
n = f
if f.output && f.counter != m.counter {
hits = append(hits, in[idx-f.index+1:idx+1])
f.counter = m.counter
}
for !f.suffix.root {
f = f.suffix
if f.counter != m.counter {
hits = append(hits, in[idx-f.index+1:idx+1])
f.counter = m.counter
} else {
// There's no point working our way up the
// suffixes if it's been done before for this call
// to Match. The matches are already in hits.
break
}
}
}
}
return hits
}
// Match returns true if the input slice contains any subslices
func (m *Matcher) Match(in []byte) bool {
n := m.root
for _, b := range in {
c := int(b)
if !n.root && n.child[c] == nil {
n = n.fails[c]
}
if n.child[c] != nil {
n = n.child[c]
if n.output {
return true
}
for !n.suffix.root {
return true
}
}
}
return false
}
// MatchString returns true if the input slice contains any subslices
func (m *Matcher) MatchString(in string) bool {
n := m.root
slen := len(in)
for idx := 0; idx < slen; idx++ {
c := int(in[idx])
if !n.root && n.child[c] == nil {
n = n.fails[c]
}
if n.child[c] != nil {
n = n.child[c]
if n.output {
return true
}
for !n.suffix.root {
return true
}
}
}
return false
}