Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Aho_Corasick.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
44# ifndef AHO_CORASICK_H
45# define AHO_CORASICK_H
46
47# include <string>
48# include <string_view>
49# include <utility>
50# include <array>
51
52# include <ah-errors.H>
53# include <tpl_array.H>
54
55namespace Aleph
56{
70 {
71 public:
77 struct Match
78 {
79 size_t position = 0;
80 size_t pattern_id = 0;
86 bool operator==(const Match & other) const noexcept
87 {
88 return position == other.position and pattern_id == other.pattern_id;
89 }
90 };
91
92 private:
93 struct Node
94 {
95 std::array<int, 256> next;
96 int fail = 0;
97 int out_link = -1;
99
101 {
102 next.fill(-1);
103 }
104 };
105
108 bool built_ = false;
109
110 size_t create_node()
111 {
112 nodes_.append(Node{});
113 return nodes_.size() - 1;
114 }
115
116 public:
119 {
120 nodes_.append(Node{});
121 }
122
127 Aho_Corasick(const Aho_Corasick & other) = default;
128
143 {
144 swap(other);
145 }
146
152 Aho_Corasick & operator = (const Aho_Corasick & other) = default;
153
161 {
162 swap(other);
163 return *this;
164 }
165
170 void swap(Aho_Corasick & other) noexcept
171 {
172 nodes_.swap(other.nodes_);
173 patterns_.swap(other.patterns_);
174 std::swap(built_, other.built_);
175 }
176
178 void clear()
179 {
180 nodes_.empty();
182 nodes_.append(Node{});
183 built_ = false;
184 }
185
197 size_t add_pattern(std::string pattern)
198 {
200 << "Aho_Corasick::add_pattern(): pattern cannot be empty";
201
202 size_t state = 0;
203 for (const unsigned char c: pattern)
204 {
205 int next_state = nodes_[state].next[c];
206 if (next_state == -1)
207 {
208 const size_t new_state = create_node();
209 nodes_[state].next[c] = static_cast<int>(new_state);
210 next_state = static_cast<int>(new_state);
211 }
212
213 state = static_cast<size_t>(next_state);
214 }
215
216 const size_t id = patterns_.size();
217 patterns_.append(std::move(pattern));
218 nodes_[state].output.append(id);
219
220 built_ = false;
221 return id;
222 }
223
236 void build()
237 {
238 Array<size_t> queue;
239 size_t head = 0;
240
241 nodes_[0].fail = 0;
242 nodes_[0].out_link = -1;
243
244 for (size_t c = 0; c < 256; ++c)
245 if (const int next_state = nodes_[0].next[c]; next_state != -1)
246 {
247 const auto child = static_cast<size_t>(next_state);
248 nodes_[child].fail = 0;
249 nodes_[child].out_link = -1;
250 queue.append(child);
251 }
252
253 while (head < queue.size())
254 {
255 const size_t state = queue[head++];
256
257 for (size_t c = 0; c < 256; ++c)
258 {
259 const int next_state = nodes_[state].next[c];
260 if (next_state == -1)
261 continue;
262
263 const auto child = static_cast<size_t>(next_state);
264 auto fail_to = static_cast<size_t>(nodes_[state].fail);
265
266 while (fail_to != 0 and nodes_[fail_to].next[c] == -1)
267 fail_to = static_cast<size_t>(nodes_[fail_to].fail);
268
269 if (const int candidate = nodes_[fail_to].next[c]; candidate != -1)
270 fail_to = static_cast<size_t>(candidate);
271
272 nodes_[child].fail = static_cast<int>(fail_to);
273 nodes_[child].out_link =
274 nodes_[fail_to].output.is_empty() ?
275 nodes_[fail_to].out_link : static_cast<int>(fail_to);
276
277 queue.append(child);
278 }
279 }
280
281 built_ = true;
282 }
283
295 [[nodiscard]] Array<Match> search(const std::string_view text) const
296 {
298 << "Aho_Corasick::search(): call build() before search()";
299
300 Array<Match> matches;
301 size_t state = 0;
302
303 for (size_t i = 0; i < text.size(); ++i)
304 {
305 const unsigned char c = static_cast<unsigned char>(text[i]);
306
307 while (state != 0 and nodes_[state].next[c] == -1)
308 state = static_cast<size_t>(nodes_[state].fail);
309
310 if (const int next_state = nodes_[state].next[c]; next_state != -1)
311 state = static_cast<size_t>(next_state);
312 else
313 state = 0;
314
315 size_t out_state = state;
316 while (true)
317 {
318 const Array<size_t> & output = nodes_[out_state].output;
319 for (size_t k = 0; k < output.size(); ++k)
320 {
321 const size_t id = output[k];
322 matches.append(Match{i + 1 - patterns_[id].size(), id});
323 }
324
325 const int next_out = nodes_[out_state].out_link;
326 if (next_out == -1)
327 break;
328 out_state = static_cast<size_t>(next_out);
329 }
330 }
331
332 return matches;
333 }
334
343 [[nodiscard]] bool contains_any(const std::string_view text) const
344 {
346 << "Aho_Corasick::contains_any(): call build() before search()";
347
348 size_t state = 0;
349 for (size_t i = 0; i < text.size(); ++i)
350 {
351 const unsigned char c = static_cast<unsigned char>(text[i]);
352
353 while (state != 0 and nodes_[state].next[c] == -1)
354 state = static_cast<size_t>(nodes_[state].fail);
355
356 if (const int next_state = nodes_[state].next[c]; next_state != -1)
357 state = static_cast<size_t>(next_state);
358 else
359 state = 0;
360
361 if (not nodes_[state].output.is_empty())
362 return true;
363
364 if (nodes_[state].out_link != -1)
365 return true;
366 }
367
368 return false;
369 }
370
375 [[nodiscard]] size_t pattern_count() const noexcept
376 {
377 return patterns_.size();
378 }
379
384 [[nodiscard]] bool is_built() const noexcept
385 {
386 return built_;
387 }
388
397 [[nodiscard]] const std::string &pattern(const size_t id) const
398 {
400 << "Aho_Corasick::pattern(): id out of range";
401 return patterns_[id];
402 }
403 };
404} // namespace Aleph
405
406# endif // AHO_CORASICK_H
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
Aho-Corasick multi-pattern automaton.
const std::string & pattern(const size_t id) const
Return the pattern text by id.
void swap(Aho_Corasick &other) noexcept
Exchange in O(1) the patterns and the automaton of this one and another.
bool contains_any(const std::string_view text) const
Return true if at least one pattern appears in the text.
void clear()
Clear all patterns and reset to an empty automaton.
size_t pattern_count() const noexcept
Return the number of inserted patterns.
Aho_Corasick & operator=(const Aho_Corasick &other)=default
Copy the patterns and the automaton of another one.
bool is_built() const noexcept
Return whether build() has been executed since last insertion.
Aho_Corasick()
Build an empty automaton (root only).
void build()
Build failure links and transition completion.
Array< Node > nodes_
size_t add_pattern(std::string pattern)
Add one pattern to the automaton.
Aho_Corasick(Aho_Corasick &&other)
Take the patterns and the automaton of another one, which is left empty, with the root only,...
Array< Match > search(const std::string_view text) const
Search all patterns in a text.
Aho_Corasick(const Aho_Corasick &other)=default
Copy the patterns and the automaton of another one.
Array< std::string > patterns_
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void empty() noexcept
Empties the container.
Definition tpl_array.H:426
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
One match occurrence in the searched text.
bool operator==(const Match &other) const noexcept
Equality operator for Match.
size_t pattern_id
Insertion-order ID of the pattern.
size_t position
0-based start index of the match.
std::array< int, 256 > next
static int * k
Dynamic array container with automatic resizing.
ofstream output
Definition writeHeap.C:215