-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathACE.cpp
More file actions
634 lines (548 loc) · 20.1 KB
/
ACE.cpp
File metadata and controls
634 lines (548 loc) · 20.1 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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
/*
* © 2013. https://github.com/0xcb All rights reserved.
*
*
* Usage example:
*
* // Create the ACE object:
* ACE* Ace = new ACE();
*
* // Add hundreds or thousands of patterns from byte arrays:
* Ace->AddPattern(new ACEPattern(NEEDLE, NEEDLE_SIZE));
* Ace->AddPattern(new ACEPattern(ANOTHER_NEEDLE, NEEDLE_SIZE));
*
* // Compile the trie:
* Ace->Compile();
*
* // Search a buffer for instances of all patterns in the trie:
* Ace->Search(HAYSTACK, HAYSTACK_SIZE);
*
* // Iterate patterns in the trie to find matches:
* for(int i = 0; i < Ace->patterns.size(); i++)
* if(Ace->patterns[i]->hits)
* ; // A pattern was matched! Do something here.
*
*/
//#pragma once
#pragma intrinsic(memset, memcpy)
#include <vector>
#include <queue>
#include <tuple>
//#include "ACE.h"
#include "ACEPattern.h"
#define BOOL bool
using std::vector;
using std::queue;
using std::tuple;
using std::make_tuple;
using std::get;
class ACE
{
typedef unsigned char byte;
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned long ulong;
typedef vector<ACEPattern*> PatternList;
private:
struct INode;
struct StateNode;
struct ListNode;
static const int ALPHABET_SIZE = 256;
StateNode* _root;
public:
PatternList patterns;
vector<std::string> results;
private:
/*
* Ordering is significant: STATE is TRUE, LIST is FALSE.
*/
enum NodeType : byte
{
NODE_TYPE_LIST = 0,
NODE_TYPE_STATE = 1
};
/*
* Inlined casting functions are used in place of function-style casts because
* the Visual Studio compiler disallows them in some sections of code.
*/
__forceinline static StateNode* STATE(INode* node) { return (StateNode*)node; }
__forceinline static ListNode* LIST(INode* node) { return (ListNode*)node; }
/*
* INode is the underlying type for StateNodes and ListNodes, but also contains
* a number of type-agnostic methods that abstract away the internal differences
* between the two behind a shared interface.
*/
#pragma region INode
struct INode
{
NodeType type;
INode* nextNode[ALPHABET_SIZE];
__forceinline BOOL IsStateNode() { return type; }
__forceinline BOOL IsListNode() { return !type; }
__forceinline bool IsTerminal(ushort index) { return IsStateNode() || LIST(this)->size == index; }
/*
* Type-agnostic methods abstract away the complexity of designing the core
* trie construction, fail links, and search loop for multiple node types.
* These methods are included in the base class rather than invoked
* polymorphically because:
*
* a) The IsTerminal case cannot be handled by polymorphism alone (a
* ListNode qualifies as terminal at its final index).
*
* b) The methods are inlined for performance reasons, which the
* compiler can only do for virtual methods when the type of the
* derived class is known at compile time (here it isn't).
*/
#pragma region Type-agnostic methods
/*
* Whether this node has a child with the appropriate byte value.
*/
__forceinline BOOL HasChild(byte value, ushort index)
{
if(IsTerminal(index))
return BOOL(nextNode[value]);
else
return LIST(this)->nodes[index + 1]->value == value;
}
/*
* Only called when a next is guaranteed to exist. No safety check included.
* Deprecated in favor of the version below.
*/
//__forceinline INode* GetChild(byte value, ushort& index)
//{
// if(IsTerminal(index))
// {
// if(LIST(nextNode[value])->IsListNode())
// index = 0;
// return nextNode[value];
// }
// else
// {
// index++;
// return this;
// }
//}
/*
* This version returns NULL if no child node exists for the given byte.
*/
__forceinline INode* GetChild(byte value, ushort& index)
{
if(IsTerminal(index))
{
if(BOOL(nextNode[value]))
{
if(LIST(nextNode[value])->IsListNode())
index = 0;
return nextNode[value];
}
return NULL;
}
else
{
if(LIST(this)->nodes[index + 1]->value == value)
{
index++;
return this;
}
return NULL;
}
}
/*
* Get the byte represented by this node. Only call on valid indices (no safety check).
*/
__forceinline byte GetValue(ushort index)
{
if(IsStateNode())
return STATE(this)->value;
else
return LIST(this)->nodes[index]->value;
}
/*
* Get the fail link for this node. Modifies the value of index to track ListNode offset.
*/
__forceinline INode* GetFailNode(ushort& index)
{
if(IsStateNode())
{
// _root is a special case: NULL fail.
if(!STATE(this)->failNode)
return NULL;
if(STATE(this)->failNode->IsListNode())
index = STATE(this)->index;
return STATE(this)->failNode;
}
else
{
auto temp = LIST(this)->nodes[index];
index = temp->index;
return temp->failNode;
}
}
/*
* Assign the fail link for this node.
*/
__forceinline void SetFailNode(ushort nIndex, INode* fail, ushort fIndex)
{
if(IsStateNode())
{
STATE(this)->index = fIndex;
STATE(this)->failNode = fail;
}
else
{
LIST(this)->nodes[nIndex]->index = fIndex;
LIST(this)->nodes[nIndex]->failNode = fail;
}
}
/*
* The list of patterns matched by reaching this node.
*/
__forceinline PatternList* GetMatches(ushort index)
{
if(IsStateNode())
return STATE(this)->matches;
else
return LIST(this)->nodes[index]->matches;
}
/*
* If the node already has a PatternList, a new one is not created.
*/
__forceinline PatternList* CreateMatches(ushort index)
{
auto matches = GetMatches(index);
if(!matches)
{
matches = new PatternList();
if(IsStateNode())
STATE(this)->matches = matches;
else
LIST(this)->nodes[index]->matches = matches;
}
return matches;
}
/*
* Used to copy matches depth-ward in the trie while establishing fail links.
*/
__forceinline void CopyMatches(ushort nIndex, INode* copy, ushort cIndex)
{
auto list = copy->GetMatches(cIndex);
if(!list)
return;
PatternList* matches = CreateMatches(nIndex);
for(uint i = 0; i < list->size(); i++)
matches->push_back((*list)[i]);
}
/*
* The number of child nodes descending from this node. Not optimal (could be
* cached) but also not used in performance-critical areas.
*/
uint GetChildCount()
{
uint count = 0;
for(uint i = 0; i < ALPHABET_SIZE; i++)
if(nextNode[i])
count++;
return count;
}
#pragma endregion
INode()
{
memset(nextNode, 0, sizeof(INode*) * ALPHABET_SIZE);
}
virtual ~INode()
{
// Twiddling thumbs.
}
};
#pragma endregion
/*
* StateNodes are the standard node type seen in other Aho-Corasick
* implementations. They contain only one state.
*/
#pragma region StateNode
struct StateNode : public INode
{
byte value;
INode* failNode;
ushort index;
PatternList* matches;
StateNode(byte val)
{
type = NODE_TYPE_STATE;
value = val;
index = 0;
matches = NULL;
}
~StateNode()
{
if(matches)
delete matches;
}
};
#pragma endregion
/*
* ListNodes contain a series of nodes with only one state transition each. This
* is possible because only a very small percentage of nodes have more than one
* state transition, and allows us to save a significant amount of memory over
* standard StateNodes (alphabet size * pointer size per state, or 2kB per state
* on 64-bit).
*/
#pragma region ListNode
struct ListNode : public INode
{
/*
* NodeEntry is the ListNode equivalent of a single state.
*/
#pragma region NodeEntry
struct NodeEntry
{
byte value;
INode* failNode;
ushort index;
PatternList* matches;
NodeEntry()
{
index = 0;
}
~NodeEntry()
{
if(matches)
delete matches;
}
};
#pragma endregion
// Size is cached to avoid the overhead of repeated calls to the size()
// method in the Search loop.
ushort size;
vector<NodeEntry*> nodes;
/*
* Add a new state transition from a byte value.
*/
void AddValue(byte value)
{
auto entry = new NodeEntry;
entry->value = value;
entry->matches = NULL;
nodes.push_back(entry);
size = nodes.size() - 1;
}
/*
* Split an existing list into two lists and connect them. Return a
* pointer to the new list.
*/
INode* Split(ushort index)
{
// There is no bounds check on index because it is impossible to
// overflow with the current code.
auto list = new ListNode(nodes[index]);
for(ushort i = index + 1; i <= size; i++)
list->nodes.push_back(nodes[i]);
nodes.erase(nodes.begin() + index, nodes.end());
memcpy(list->nextNode, nextNode, ALPHABET_SIZE * sizeof(INode*));
memset(nextNode, 0, ALPHABET_SIZE * sizeof(INode*));
nextNode[list->nodes[0]->value] = list;
list->size = list->nodes.size() - 1;
size = nodes.size() - 1;
return list;
}
/*
* Is the list composed of a single NodeEntry?
*/
__forceinline bool IsSingleState()
{
return !LIST(this)->size;
}
/*
* Reduce the ListNode to a StateNode with values from the ListNode's
* first NodeEntry. Only called if IsSingleState is true.
*/
StateNode* ReduceToState(INode* parent)
{
auto entry = LIST(this)->nodes[0];
auto state = new StateNode(entry->value);
if(entry->matches)
state->matches = new PatternList(*entry->matches);
parent->nextNode[entry->value] = state;
memcpy(state->nextNode, nextNode, ALPHABET_SIZE * sizeof(INode*));
delete this;
return state;
}
ListNode(byte value)
{
type = NODE_TYPE_LIST;
AddValue(value);
}
ListNode(NodeEntry* entry)
{
type = NODE_TYPE_LIST;
nodes.push_back(entry);
}
~ListNode()
{
size++;
for(uint i = 0; i < size; i++)
delete nodes[i];
}
};
#pragma endregion
void CompressVectors(INode* node)
{
if(node->IsStateNode())
{
if(STATE(node)->matches)
STATE(node)->matches->shrink_to_fit();
}
else
{
LIST(node)->nodes.shrink_to_fit();
uint size = LIST(node)->size + 1;
for(uint i = 0; i < size; i++)
if(LIST(node)->nodes[i]->matches)
LIST(node)->nodes[i]->matches->shrink_to_fit();
}
for(uint i = 0; i < ALPHABET_SIZE; i++)
if(node->nextNode[i])
CompressVectors(node->nextNode[i]);
}
public:
ACE()
{
_root = new StateNode((byte)NULL);
_root->failNode = NULL;
}
void AddPattern(ACEPattern* pattern)
{
patterns.push_back(pattern);
}
void Compile()
{
/*
* Create the trie using ListNodes as the default. If branching occurs,
* split the ListNode appropriately.
*/
#pragma region Construct the trie
uint size = patterns.size();
for(uint i = 0; i < size; i++)
{
INode* node = _root;
ushort index = 0;
for(uint j = 0; j < patterns[i]->length; j++)
{
byte next = patterns[i]->pattern[j];
if(!node->HasChild(next, index))
{
// Necessary because _root is a StateNode.
if(node->IsStateNode())
node->nextNode[next] = new ListNode(next);
else
{
BOOL isListEnd = index == LIST(node)->size;
BOOL hasChildren = node->GetChildCount();
if(isListEnd && !hasChildren)
LIST(node)->AddValue(next);
else
{
if(!isListEnd)
LIST(node)->Split(index + 1);
node->nextNode[next] = new ListNode(next);
}
}
}
node = node->GetChild(next, index);
}
node->CreateMatches(index)->push_back(patterns[i]);
}
#pragma endregion
/*
* Fail links are more complicated with ListNodes, but most of the
* thorniness has been abstracted into type-agnostic methods in INode.
*/
#pragma region Create failure links
queue<tuple<INode*, ushort, INode*, ushort>> nodeQueue;
nodeQueue.push(make_tuple(_root, 0, STATE(NULL), 0));
while(!nodeQueue.empty())
{
auto data = nodeQueue.front();
auto node = get<0>(data);
auto nIndex = get<1>(data);
auto parent = get<2>(data);
auto fIndex = get<3>(data);
auto value = node->GetValue(nIndex);
auto fail = !parent ? NULL : parent == _root ? _root : parent->GetFailNode(fIndex);
// Surely there's a cleaner way to exclude _root.
if(fail)
{
// All non-root nodes are ListNodes at the time they are evaluated here. If
// they have only one state, we reduce them to a StateNode.
if(LIST(node)->IsSingleState())
node = LIST(node)->ReduceToState(parent);
while(!fail->HasChild(value, fIndex) && (fail = fail->GetFailNode(fIndex)));
node->SetFailNode(nIndex, parent == _root || !fail ? _root : fail->GetChild(value, fIndex), fIndex);
// Copy fail link matches depth-ward in the trie.
fail = node->GetFailNode(fIndex = nIndex);
node->CopyMatches(nIndex, fail, fIndex);
}
// Queue children. A "terminal" node is either a StateNode or the last entry
// in a ListNode.
if(node->IsTerminal(nIndex))
for(uint i = 0; i < ALPHABET_SIZE; i++)
{
if(node->nextNode[i])
nodeQueue.push(make_tuple(node->nextNode[i], 0, node, nIndex));
}
else
nodeQueue.push(make_tuple(node, nIndex + 1, node, nIndex));
nodeQueue.pop();
}
#pragma endregion
// Recurse through all node vectors and free excess space. Not that it amounts
// to much.
CompressVectors(_root);
}
/*
* The abstracted INode methods leave us with a very compact search loop.
*/
void Search(byte* buffer, uint length)
{
results.clear();
INode* node = _root;
ushort index = 0;
for(uint i = 0; i < length; i++)
{
byte next = buffer[i];
INode* temp;
while(!(temp = node->GetChild(next, index)) && (node = node->GetFailNode(index)));
node = node ? temp : _root;
auto matches = node->GetMatches(index);
if(matches)
{
uint size = matches->size();
for(uint j = 0; j < size; j++)
{
auto matched = (*matches)[j];
/*
if(!matched->hits)
matched->hits = new vector<ulong>;
matched->hits->push_back(i - (matched->length - 1));
*/
results.push_back(std::string((const char*)matched->pattern, matched->length));
}
}
}
}
private:
void DeleteNodes(INode* node)
{
for(uint i = 0; i < ALPHABET_SIZE; i++)
if(node->nextNode[i])
DeleteNodes(node->nextNode[i]);
delete node;
}
public:
~ACE()
{
DeleteNodes(_root);
for(uint i = 0; i < patterns.size(); i++)
delete patterns[i];
}
};