daachorse 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +24 -0
- data/Cargo.lock +290 -0
- data/Cargo.toml +8 -0
- data/LICENSE-APACHE +176 -0
- data/LICENSE-MIT +25 -0
- data/README.md +186 -0
- data/ext/daachorse/Cargo.toml +18 -0
- data/ext/daachorse/build.rs +5 -0
- data/ext/daachorse/extconf.rb +6 -0
- data/ext/daachorse/src/lib.rs +427 -0
- data/lib/daachorse/version.rb +5 -0
- data/lib/daachorse.rb +79 -0
- data/sig/daachorse.rbs +32 -0
- metadata +76 -0
data/README.md
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# daachorse
|
|
2
|
+
|
|
3
|
+
Fast multi-pattern string search for Ruby, backed by
|
|
4
|
+
[daachorse](https://github.com/daac-tools/daachorse), a compact double-array
|
|
5
|
+
Aho-Corasick automaton written in Rust.
|
|
6
|
+
|
|
7
|
+
- Hundreds of thousands of patterns in a few tens of megabytes.
|
|
8
|
+
- Standard, leftmost-longest and leftmost-first match semantics.
|
|
9
|
+
- Optional ASCII case-insensitive matching.
|
|
10
|
+
- `dump` / `load` so a built automaton can be saved to a file or shared
|
|
11
|
+
between processes and loaded in milliseconds instead of rebuilt.
|
|
12
|
+
- Precompiled native gems for Linux (glibc and musl, x86_64 and aarch64) and
|
|
13
|
+
macOS (x86_64 and arm64), Ruby 3.3 to 4.0. Other platforms compile from
|
|
14
|
+
source and need a Rust toolchain.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
bundle add daachorse
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
require "daachorse"
|
|
26
|
+
|
|
27
|
+
automaton = Daachorse::Automaton.new(%w[he she his hers], match_kind: :leftmost_longest)
|
|
28
|
+
|
|
29
|
+
automaton.find_all("ushers") # => [[1, 4, 1]]
|
|
30
|
+
automaton.find_all_flat("ushers") # => [1, 4, 1]
|
|
31
|
+
automaton.match?("this") # => true
|
|
32
|
+
|
|
33
|
+
automaton.each_match("she said his") do |start, finish, value|
|
|
34
|
+
# start/finish are byte offsets, value is the pattern's index
|
|
35
|
+
end
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Values and offsets
|
|
39
|
+
|
|
40
|
+
The value reported for a match is the index of the pattern in the array given
|
|
41
|
+
to `Automaton.new`. If the same pattern appears more than once, the first
|
|
42
|
+
index wins. Patterns must be non-empty strings; an empty pattern raises
|
|
43
|
+
`ArgumentError`.
|
|
44
|
+
|
|
45
|
+
Patterns and texts are compared as raw bytes, whatever their encoding. Every
|
|
46
|
+
offset is a byte offset, so use `String#byteslice` to extract a match:
|
|
47
|
+
|
|
48
|
+
```ruby
|
|
49
|
+
text = "привет, мир"
|
|
50
|
+
start, finish, = Daachorse::Automaton.new(["мир"]).find_all(text).first
|
|
51
|
+
text.byteslice(start, finish - start) # => "мир"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Match kinds
|
|
55
|
+
|
|
56
|
+
| `match_kind:` | Reports |
|
|
57
|
+
|---------------------|-------------------------------------------------------------------------------------------------------------------|
|
|
58
|
+
| `:standard` (default) | Non-overlapping matches in standard Aho-Corasick order: the match that ends first, then the search continues after it. |
|
|
59
|
+
| `:leftmost_longest` | The match that starts leftmost; among those, the longest pattern. |
|
|
60
|
+
| `:leftmost_first` | The match that starts leftmost; among those, the pattern that comes first in the array. |
|
|
61
|
+
|
|
62
|
+
```ruby
|
|
63
|
+
patterns = %w[ab a abcd]
|
|
64
|
+
Daachorse::Automaton.new(patterns).find_all("abcd") # => [[0, 1, 1]]
|
|
65
|
+
Daachorse::Automaton.new(patterns, match_kind: :leftmost_longest).find_all("abcd") # => [[0, 4, 2]]
|
|
66
|
+
Daachorse::Automaton.new(patterns, match_kind: :leftmost_first).find_all("abcd") # => [[0, 2, 0]]
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Only `:standard` automata can report every occurrence, overlaps included:
|
|
70
|
+
|
|
71
|
+
```ruby
|
|
72
|
+
Daachorse::Automaton.new(patterns).find_overlapping("abcd")
|
|
73
|
+
# => [[0, 1, 1], [0, 2, 0], [0, 4, 2]]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Calling `each_overlapping` or `find_overlapping` on a leftmost automaton raises
|
|
77
|
+
`Daachorse::Error`.
|
|
78
|
+
|
|
79
|
+
### Case-insensitive matching
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
automaton = Daachorse::Automaton.new(%w[ruby], ascii_case_insensitive: true)
|
|
83
|
+
automaton.find_all("Ruby RUBY ruby") # => [[0, 4, 0], [5, 9, 0], [10, 14, 0]]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Only the ASCII letters `A`–`Z` are folded. Other bytes, including every byte of
|
|
87
|
+
a multi-byte UTF-8 character, are compared exactly, so offsets stay valid for
|
|
88
|
+
the original text and `"É"` does not match `"é"`.
|
|
89
|
+
|
|
90
|
+
### Methods
|
|
91
|
+
|
|
92
|
+
| Method | Returns |
|
|
93
|
+
|-------------------------------|-------------------------------------------------------------------------|
|
|
94
|
+
| `each_match(text) { \|start, finish, value\| }` | `self`; an `Enumerator` without a block. No array is allocated per match. |
|
|
95
|
+
| `find_all(text)` | `[[start, finish, value], ...]` |
|
|
96
|
+
| `find_all_flat(text)` | `[start, finish, value, start, finish, value, ...]` |
|
|
97
|
+
| `match?(text)` | `true` if any pattern occurs |
|
|
98
|
+
| `each_overlapping(text)`, `find_overlapping(text)` | every occurrence (`:standard` only) |
|
|
99
|
+
| `dump` | binary `String` |
|
|
100
|
+
| `Automaton.load(bytes)` | a new `Automaton` |
|
|
101
|
+
| `match_kind`, `ascii_case_insensitive?` | the build options |
|
|
102
|
+
| `heap_bytes` | bytes of heap memory held by the automaton |
|
|
103
|
+
| `num_states` | number of automaton states |
|
|
104
|
+
|
|
105
|
+
## Serialization
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
File.binwrite("patterns.daac", automaton.dump)
|
|
109
|
+
automaton = Daachorse::Automaton.load(File.binread("patterns.daac"))
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
A dump is an 8-byte header followed by daachorse's own serialization:
|
|
113
|
+
|
|
114
|
+
| Bytes | Content |
|
|
115
|
+
|-------|----------------------------------------------------------------------|
|
|
116
|
+
| 0–3 | magic `DAAC` |
|
|
117
|
+
| 4 | dump format version, currently `1` |
|
|
118
|
+
| 5 | flags; bit 0 set means ASCII case-insensitive |
|
|
119
|
+
| 6 | match kind: 0 standard, 1 leftmost-longest, 2 leftmost-first |
|
|
120
|
+
| 7 | reserved, always 0 |
|
|
121
|
+
| 8– | `DoubleArrayAhoCorasick::serialize` output of the bundled daachorse |
|
|
122
|
+
|
|
123
|
+
`load` rejects a wrong magic, an unknown format version, unknown flags, an
|
|
124
|
+
unknown or inconsistent match kind, truncated data and trailing bytes with
|
|
125
|
+
`Daachorse::FormatError`. The automaton itself is read with daachorse's
|
|
126
|
+
checked `deserialize`, which guarantees memory safety for any input. It does
|
|
127
|
+
not prove that the data is a well-formed automaton: crafted bytes can still
|
|
128
|
+
produce wrong matches or a search that never ends. Load only dumps you
|
|
129
|
+
produced yourself.
|
|
130
|
+
|
|
131
|
+
The format version is bumped whenever the header or the bundled daachorse
|
|
132
|
+
serialization changes, so a dump written by one version of this gem can be
|
|
133
|
+
loaded by any version that reports the same format version.
|
|
134
|
+
|
|
135
|
+
## Threads and the GVL
|
|
136
|
+
|
|
137
|
+
`Automaton.new` copies the patterns and then builds the automaton with the GVL
|
|
138
|
+
released, so other Ruby threads keep running during a long build.
|
|
139
|
+
`find_all`, `find_all_flat` and `find_overlapping` copy texts of 16 KiB or more
|
|
140
|
+
and search the copy with the GVL released. Shorter texts are searched in
|
|
141
|
+
place, because releasing the GVL costs more than the search.
|
|
142
|
+
|
|
143
|
+
`each_match` and `each_overlapping` keep the GVL, since they call the block for
|
|
144
|
+
every match. They search a private copy of the text, so a block may safely
|
|
145
|
+
modify the string it is iterating over.
|
|
146
|
+
|
|
147
|
+
An automaton is immutable after it is built and can be shared between threads.
|
|
148
|
+
|
|
149
|
+
## Benchmarks
|
|
150
|
+
|
|
151
|
+
Measured by the author on an Apple M1 Max, macOS, Ruby 3.4.9, release build of
|
|
152
|
+
this gem, with 200,000 random ASCII patterns of 4 to 16 characters drawn from
|
|
153
|
+
`a`–`z`, space, `-` and `.` (2.0 MB of pattern text), `:leftmost_longest`:
|
|
154
|
+
|
|
155
|
+
| Measurement | Value |
|
|
156
|
+
|-------------------------------------|-------------|
|
|
157
|
+
| Build | 0.45 s |
|
|
158
|
+
| `heap_bytes` | 18.5 MB |
|
|
159
|
+
| States | 1,402,017 |
|
|
160
|
+
| Dump size | 18.5 MB |
|
|
161
|
+
| `dump` | 9 ms |
|
|
162
|
+
| `load` (best of 5) | 7 ms |
|
|
163
|
+
| Process RSS growth after `load` only | 18.6 MB |
|
|
164
|
+
| `find_all` over 1 MB of random text | 25 ms |
|
|
165
|
+
|
|
166
|
+
Building needs far more memory than the finished automaton (the process RSS
|
|
167
|
+
grew by about 190 MB during the build above), which is one reason to build
|
|
168
|
+
once and `load` the dump everywhere else.
|
|
169
|
+
|
|
170
|
+
## Development
|
|
171
|
+
|
|
172
|
+
```sh
|
|
173
|
+
bundle install
|
|
174
|
+
bundle exec rake compile test
|
|
175
|
+
cargo fmt --all -- --check
|
|
176
|
+
cargo clippy --all-targets -- -D warnings
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
Licensed under either of
|
|
182
|
+
|
|
183
|
+
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
|
|
184
|
+
- MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
185
|
+
|
|
186
|
+
at your option, the same terms as daachorse itself.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "daachorse"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
authors = ["FoundRole <argus@foundrole.com>"]
|
|
6
|
+
license = "MIT OR Apache-2.0"
|
|
7
|
+
publish = false
|
|
8
|
+
|
|
9
|
+
[lib]
|
|
10
|
+
crate-type = ["cdylib"]
|
|
11
|
+
|
|
12
|
+
[dependencies]
|
|
13
|
+
daachorse = "=5.1.0"
|
|
14
|
+
magnus = "0.8"
|
|
15
|
+
rb-sys = { version = "0.9.130", features = ["stable-api-compiled-fallback"] }
|
|
16
|
+
|
|
17
|
+
[build-dependencies]
|
|
18
|
+
rb-sys-env = "0.2.3"
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
//! Ruby bindings for the [daachorse](https://crates.io/crates/daachorse) double-array
|
|
2
|
+
//! Aho-Corasick automaton.
|
|
3
|
+
|
|
4
|
+
use std::borrow::Cow;
|
|
5
|
+
use std::collections::HashSet;
|
|
6
|
+
use std::ffi::c_void;
|
|
7
|
+
use std::panic::{self, AssertUnwindSafe};
|
|
8
|
+
|
|
9
|
+
use daachorse::{DoubleArrayAhoCorasick, DoubleArrayAhoCorasickBuilder, MatchKind};
|
|
10
|
+
use magnus::{
|
|
11
|
+
function, method, prelude::*, value::Lazy, Error, ExceptionClass, RArray, RModule, RString,
|
|
12
|
+
Ruby,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/// Magic bytes at the start of every dump.
|
|
16
|
+
const MAGIC: &[u8; 4] = b"DAAC";
|
|
17
|
+
/// Version of the dump layout. Bumped whenever the header or the bundled daachorse
|
|
18
|
+
/// serialization changes incompatibly.
|
|
19
|
+
const FORMAT_VERSION: u8 = 1;
|
|
20
|
+
const HEADER_LEN: usize = 8;
|
|
21
|
+
const FLAG_ASCII_CASE_INSENSITIVE: u8 = 0b0000_0001;
|
|
22
|
+
const KNOWN_FLAGS: u8 = FLAG_ASCII_CASE_INSENSITIVE;
|
|
23
|
+
|
|
24
|
+
/// Haystacks at least this long are searched with the GVL released.
|
|
25
|
+
const NOGVL_TEXT_BYTES: usize = 16 * 1024;
|
|
26
|
+
|
|
27
|
+
const U32_BYTES: usize = 4;
|
|
28
|
+
const STATE_BYTES: usize = 12;
|
|
29
|
+
const LEFTMOST_STATE_BYTES: usize = 8;
|
|
30
|
+
const FAIL_BYTES: usize = 4;
|
|
31
|
+
const OUTPUT_BYTES: usize = 12;
|
|
32
|
+
|
|
33
|
+
static ERROR: Lazy<ExceptionClass> = Lazy::new(|ruby| error_class(ruby, "Error"));
|
|
34
|
+
static FORMAT_ERROR: Lazy<ExceptionClass> = Lazy::new(|ruby| error_class(ruby, "FormatError"));
|
|
35
|
+
|
|
36
|
+
fn error_class(ruby: &Ruby, name: &str) -> ExceptionClass {
|
|
37
|
+
ruby.class_object()
|
|
38
|
+
.const_get::<_, RModule>("Daachorse")
|
|
39
|
+
.and_then(|module| module.const_get(name))
|
|
40
|
+
.expect("Daachorse error classes are defined before the extension is loaded")
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
fn error(ruby: &Ruby, message: impl Into<Cow<'static, str>>) -> Error {
|
|
44
|
+
Error::new(ruby.get_inner(&ERROR), message)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
fn format_error(ruby: &Ruby, message: impl Into<Cow<'static, str>>) -> Error {
|
|
48
|
+
Error::new(ruby.get_inner(&FORMAT_ERROR), message)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
fn match_kind_from_id(id: u8) -> Option<MatchKind> {
|
|
52
|
+
match id {
|
|
53
|
+
0 => Some(MatchKind::Standard),
|
|
54
|
+
1 => Some(MatchKind::LeftmostLongest),
|
|
55
|
+
2 => Some(MatchKind::LeftmostFirst),
|
|
56
|
+
_ => None,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
fn match_kind_id(kind: MatchKind) -> u8 {
|
|
61
|
+
match kind {
|
|
62
|
+
MatchKind::Standard => 0,
|
|
63
|
+
MatchKind::LeftmostLongest => 1,
|
|
64
|
+
MatchKind::LeftmostFirst => 2,
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/// Runs `work` without holding the GVL. `work` must not touch any Ruby object.
|
|
69
|
+
fn without_gvl<F, R>(work: F) -> R
|
|
70
|
+
where
|
|
71
|
+
F: FnOnce() -> R,
|
|
72
|
+
{
|
|
73
|
+
struct Call<F, R> {
|
|
74
|
+
work: Option<F>,
|
|
75
|
+
result: Option<std::thread::Result<R>>,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
unsafe extern "C" fn trampoline<F, R>(data: *mut c_void) -> *mut c_void
|
|
79
|
+
where
|
|
80
|
+
F: FnOnce() -> R,
|
|
81
|
+
{
|
|
82
|
+
let call = unsafe { &mut *(data as *mut Call<F, R>) };
|
|
83
|
+
if let Some(work) = call.work.take() {
|
|
84
|
+
call.result = Some(panic::catch_unwind(AssertUnwindSafe(work)));
|
|
85
|
+
}
|
|
86
|
+
std::ptr::null_mut()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let mut call = Call {
|
|
90
|
+
work: Some(work),
|
|
91
|
+
result: None,
|
|
92
|
+
};
|
|
93
|
+
unsafe {
|
|
94
|
+
rb_sys::rb_thread_call_without_gvl(
|
|
95
|
+
Some(trampoline::<F, R>),
|
|
96
|
+
&mut call as *mut Call<F, R> as *mut c_void,
|
|
97
|
+
None,
|
|
98
|
+
std::ptr::null_mut(),
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
match call.result {
|
|
102
|
+
Some(Ok(value)) => value,
|
|
103
|
+
Some(Err(payload)) => panic::resume_unwind(payload),
|
|
104
|
+
None => unreachable!("the trampoline always runs"),
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// Reads the match kind byte out of a daachorse 5.1 serialization that
|
|
109
|
+
/// `DoubleArrayAhoCorasick::deserialize` already accepted.
|
|
110
|
+
fn serialized_match_kind(body: &[u8]) -> Option<u8> {
|
|
111
|
+
let mut offset = 0usize;
|
|
112
|
+
for element_bytes in [STATE_BYTES, LEFTMOST_STATE_BYTES, FAIL_BYTES, OUTPUT_BYTES] {
|
|
113
|
+
let len_bytes = body.get(offset..offset.checked_add(U32_BYTES)?)?;
|
|
114
|
+
let len = u32::from_le_bytes(len_bytes.try_into().ok()?) as usize;
|
|
115
|
+
offset = offset
|
|
116
|
+
.checked_add(U32_BYTES)?
|
|
117
|
+
.checked_add(len.checked_mul(element_bytes)?)?;
|
|
118
|
+
}
|
|
119
|
+
body.get(offset).copied()
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
#[derive(magnus::TypedData)]
|
|
123
|
+
#[magnus(class = "Daachorse::Automaton", free_immediately, size)]
|
|
124
|
+
struct Automaton {
|
|
125
|
+
pma: DoubleArrayAhoCorasick<u32>,
|
|
126
|
+
match_kind: MatchKind,
|
|
127
|
+
ascii_case_insensitive: bool,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
impl Automaton {
|
|
131
|
+
fn build(
|
|
132
|
+
ruby: &Ruby,
|
|
133
|
+
patterns: RArray,
|
|
134
|
+
kind_id: u8,
|
|
135
|
+
ascii_case_insensitive: bool,
|
|
136
|
+
) -> Result<Self, Error> {
|
|
137
|
+
let match_kind = match_kind_from_id(kind_id)
|
|
138
|
+
.ok_or_else(|| Error::new(ruby.exception_arg_error(), "unknown match kind"))?;
|
|
139
|
+
let mut entries: Vec<(Vec<u8>, u32)> = Vec::with_capacity(patterns.len());
|
|
140
|
+
for (index, item) in patterns.into_iter().enumerate() {
|
|
141
|
+
let pattern = RString::try_convert(item)?;
|
|
142
|
+
let bytes = unsafe { pattern.as_slice() };
|
|
143
|
+
if bytes.is_empty() {
|
|
144
|
+
return Err(Error::new(
|
|
145
|
+
ruby.exception_arg_error(),
|
|
146
|
+
format!("empty pattern at index {index}"),
|
|
147
|
+
));
|
|
148
|
+
}
|
|
149
|
+
let value = u32::try_from(index)
|
|
150
|
+
.map_err(|_| error(ruby, "too many patterns (limit is 2**32)"))?;
|
|
151
|
+
let bytes = if ascii_case_insensitive {
|
|
152
|
+
bytes.to_ascii_lowercase()
|
|
153
|
+
} else {
|
|
154
|
+
bytes.to_vec()
|
|
155
|
+
};
|
|
156
|
+
entries.push((bytes, value));
|
|
157
|
+
}
|
|
158
|
+
if entries.is_empty() {
|
|
159
|
+
return Err(Error::new(
|
|
160
|
+
ruby.exception_arg_error(),
|
|
161
|
+
"at least one pattern is required",
|
|
162
|
+
));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let built = without_gvl(move || {
|
|
166
|
+
let mut seen: HashSet<&[u8]> = HashSet::with_capacity(entries.len());
|
|
167
|
+
let unique = entries
|
|
168
|
+
.iter()
|
|
169
|
+
.filter(|(bytes, _)| seen.insert(bytes.as_slice()))
|
|
170
|
+
.map(|(bytes, value)| (bytes.as_slice(), *value));
|
|
171
|
+
DoubleArrayAhoCorasickBuilder::new()
|
|
172
|
+
.match_kind(match_kind)
|
|
173
|
+
.build_with_values(unique)
|
|
174
|
+
.map_err(|failure| failure.to_string())
|
|
175
|
+
});
|
|
176
|
+
let pma = built.map_err(|message| error(ruby, format!("build failed: {message}")))?;
|
|
177
|
+
Ok(Self {
|
|
178
|
+
pma,
|
|
179
|
+
match_kind,
|
|
180
|
+
ascii_case_insensitive,
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
fn load(ruby: &Ruby, source: RString) -> Result<Self, Error> {
|
|
185
|
+
let bytes = unsafe { source.as_slice() };
|
|
186
|
+
if bytes.len() < HEADER_LEN || &bytes[..MAGIC.len()] != MAGIC {
|
|
187
|
+
return Err(format_error(ruby, "not a daachorse automaton dump"));
|
|
188
|
+
}
|
|
189
|
+
let version = bytes[4];
|
|
190
|
+
if version != FORMAT_VERSION {
|
|
191
|
+
return Err(format_error(
|
|
192
|
+
ruby,
|
|
193
|
+
format!("unsupported dump format version {version} (expected {FORMAT_VERSION})"),
|
|
194
|
+
));
|
|
195
|
+
}
|
|
196
|
+
let flags = bytes[5];
|
|
197
|
+
if flags & !KNOWN_FLAGS != 0 {
|
|
198
|
+
return Err(format_error(ruby, format!("unknown flags {flags:#010b}")));
|
|
199
|
+
}
|
|
200
|
+
let kind_id = bytes[6];
|
|
201
|
+
let match_kind = match_kind_from_id(kind_id)
|
|
202
|
+
.ok_or_else(|| format_error(ruby, format!("unknown match kind {kind_id}")))?;
|
|
203
|
+
if bytes[7] != 0 {
|
|
204
|
+
return Err(format_error(ruby, "reserved header byte is not zero"));
|
|
205
|
+
}
|
|
206
|
+
let body = &bytes[HEADER_LEN..];
|
|
207
|
+
let (pma, rest) = DoubleArrayAhoCorasick::<u32>::deserialize(body)
|
|
208
|
+
.map_err(|failure| format_error(ruby, format!("invalid automaton: {failure}")))?;
|
|
209
|
+
if !rest.is_empty() {
|
|
210
|
+
return Err(format_error(ruby, "trailing bytes after the automaton"));
|
|
211
|
+
}
|
|
212
|
+
if serialized_match_kind(body) != Some(kind_id) {
|
|
213
|
+
return Err(format_error(
|
|
214
|
+
ruby,
|
|
215
|
+
"match kind in the header does not match the automaton",
|
|
216
|
+
));
|
|
217
|
+
}
|
|
218
|
+
Ok(Self {
|
|
219
|
+
pma,
|
|
220
|
+
match_kind,
|
|
221
|
+
ascii_case_insensitive: flags & FLAG_ASCII_CASE_INSENSITIVE != 0,
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
fn dump(ruby: &Ruby, rb_self: &Self) -> RString {
|
|
226
|
+
let body = rb_self.pma.serialize();
|
|
227
|
+
let mut bytes = Vec::with_capacity(HEADER_LEN + body.len());
|
|
228
|
+
bytes.extend_from_slice(MAGIC);
|
|
229
|
+
bytes.push(FORMAT_VERSION);
|
|
230
|
+
bytes.push(if rb_self.ascii_case_insensitive {
|
|
231
|
+
FLAG_ASCII_CASE_INSENSITIVE
|
|
232
|
+
} else {
|
|
233
|
+
0
|
|
234
|
+
});
|
|
235
|
+
bytes.push(match_kind_id(rb_self.match_kind));
|
|
236
|
+
bytes.push(0);
|
|
237
|
+
bytes.extend_from_slice(&body);
|
|
238
|
+
ruby.str_from_slice(&bytes)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
fn haystack<'a>(&self, text: &'a [u8]) -> Cow<'a, [u8]> {
|
|
242
|
+
if self.ascii_case_insensitive {
|
|
243
|
+
Cow::Owned(text.to_ascii_lowercase())
|
|
244
|
+
} else {
|
|
245
|
+
Cow::Borrowed(text)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
fn try_each<E>(
|
|
250
|
+
&self,
|
|
251
|
+
haystack: &[u8],
|
|
252
|
+
mut visit: impl FnMut(usize, usize, u32) -> Result<(), E>,
|
|
253
|
+
) -> Result<(), E> {
|
|
254
|
+
if self.match_kind == MatchKind::Standard {
|
|
255
|
+
for hit in self.pma.find_iter(haystack) {
|
|
256
|
+
visit(hit.start(), hit.end(), hit.value())?;
|
|
257
|
+
}
|
|
258
|
+
} else {
|
|
259
|
+
for hit in self.pma.leftmost_find_iter(haystack) {
|
|
260
|
+
visit(hit.start(), hit.end(), hit.value())?;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
Ok(())
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
fn try_each_overlapping<E>(
|
|
267
|
+
&self,
|
|
268
|
+
haystack: &[u8],
|
|
269
|
+
mut visit: impl FnMut(usize, usize, u32) -> Result<(), E>,
|
|
270
|
+
) -> Result<(), E> {
|
|
271
|
+
for hit in self.pma.find_overlapping_iter(haystack) {
|
|
272
|
+
visit(hit.start(), hit.end(), hit.value())?;
|
|
273
|
+
}
|
|
274
|
+
Ok(())
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
fn collect(&self, text: &[u8], overlapping: bool) -> Vec<(usize, usize, u32)> {
|
|
278
|
+
let haystack = self.haystack(text);
|
|
279
|
+
let mut hits = Vec::new();
|
|
280
|
+
let push = |start, end, value| {
|
|
281
|
+
hits.push((start, end, value));
|
|
282
|
+
Ok::<(), ()>(())
|
|
283
|
+
};
|
|
284
|
+
let _ = if overlapping {
|
|
285
|
+
self.try_each_overlapping(&haystack, push)
|
|
286
|
+
} else {
|
|
287
|
+
self.try_each(&haystack, push)
|
|
288
|
+
};
|
|
289
|
+
hits
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/// Collects matches, releasing the GVL for long texts. The text is copied first
|
|
293
|
+
/// so that no Ruby memory is read while other threads run.
|
|
294
|
+
fn collect_from(&self, text: RString, overlapping: bool) -> Vec<(usize, usize, u32)> {
|
|
295
|
+
let bytes = unsafe { text.as_slice() };
|
|
296
|
+
if bytes.len() < NOGVL_TEXT_BYTES {
|
|
297
|
+
return self.collect(bytes, overlapping);
|
|
298
|
+
}
|
|
299
|
+
let owned = bytes.to_vec();
|
|
300
|
+
without_gvl(|| self.collect(&owned, overlapping))
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
fn require_standard(&self, ruby: &Ruby) -> Result<(), Error> {
|
|
304
|
+
if self.match_kind == MatchKind::Standard {
|
|
305
|
+
Ok(())
|
|
306
|
+
} else {
|
|
307
|
+
Err(error(
|
|
308
|
+
ruby,
|
|
309
|
+
"overlapping search requires match_kind: :standard",
|
|
310
|
+
))
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
fn yield_matches(
|
|
315
|
+
ruby: &Ruby,
|
|
316
|
+
rb_self: &Self,
|
|
317
|
+
text: RString,
|
|
318
|
+
overlapping: bool,
|
|
319
|
+
) -> Result<(), Error> {
|
|
320
|
+
let owned = unsafe { text.as_slice() }.to_vec();
|
|
321
|
+
let haystack = rb_self.haystack(&owned);
|
|
322
|
+
let visit = |start: usize, end: usize, value: u32| {
|
|
323
|
+
ruby.yield_values::<_, magnus::Value>((start, end, value))
|
|
324
|
+
.map(|_| ())
|
|
325
|
+
};
|
|
326
|
+
if overlapping {
|
|
327
|
+
rb_self.try_each_overlapping(&haystack, visit)
|
|
328
|
+
} else {
|
|
329
|
+
rb_self.try_each(&haystack, visit)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
fn each_match(ruby: &Ruby, rb_self: &Self, text: RString) -> Result<(), Error> {
|
|
334
|
+
Self::yield_matches(ruby, rb_self, text, false)
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
fn each_overlapping(ruby: &Ruby, rb_self: &Self, text: RString) -> Result<(), Error> {
|
|
338
|
+
rb_self.require_standard(ruby)?;
|
|
339
|
+
Self::yield_matches(ruby, rb_self, text, true)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
fn nested(ruby: &Ruby, hits: Vec<(usize, usize, u32)>) -> RArray {
|
|
343
|
+
let result = ruby.ary_new_capa(hits.len());
|
|
344
|
+
for (start, end, value) in hits {
|
|
345
|
+
let _ = result.push(ruby.ary_new_from_values(&[
|
|
346
|
+
ruby.integer_from_u64(start as u64).as_value(),
|
|
347
|
+
ruby.integer_from_u64(end as u64).as_value(),
|
|
348
|
+
ruby.integer_from_u64(u64::from(value)).as_value(),
|
|
349
|
+
]));
|
|
350
|
+
}
|
|
351
|
+
result
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
fn find_all(ruby: &Ruby, rb_self: &Self, text: RString) -> RArray {
|
|
355
|
+
Self::nested(ruby, rb_self.collect_from(text, false))
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
fn find_all_flat(ruby: &Ruby, rb_self: &Self, text: RString) -> RArray {
|
|
359
|
+
let hits = rb_self.collect_from(text, false);
|
|
360
|
+
let result = ruby.ary_new_capa(hits.len() * 3);
|
|
361
|
+
for (start, end, value) in hits {
|
|
362
|
+
let _ = result.push(start);
|
|
363
|
+
let _ = result.push(end);
|
|
364
|
+
let _ = result.push(value);
|
|
365
|
+
}
|
|
366
|
+
result
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
fn find_overlapping(ruby: &Ruby, rb_self: &Self, text: RString) -> Result<RArray, Error> {
|
|
370
|
+
rb_self.require_standard(ruby)?;
|
|
371
|
+
Ok(Self::nested(ruby, rb_self.collect_from(text, true)))
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
fn is_match(rb_self: &Self, text: RString) -> bool {
|
|
375
|
+
let bytes = unsafe { text.as_slice() };
|
|
376
|
+
let haystack = rb_self.haystack(bytes);
|
|
377
|
+
rb_self
|
|
378
|
+
.try_each(&haystack, |_, _, _| Err::<(), ()>(()))
|
|
379
|
+
.is_err()
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
fn match_kind_id(rb_self: &Self) -> u8 {
|
|
383
|
+
match_kind_id(rb_self.match_kind)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
fn ascii_case_insensitive(rb_self: &Self) -> bool {
|
|
387
|
+
rb_self.ascii_case_insensitive
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
fn heap_bytes(rb_self: &Self) -> usize {
|
|
391
|
+
rb_self.pma.heap_bytes()
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
fn num_states(rb_self: &Self) -> usize {
|
|
395
|
+
rb_self.pma.num_states()
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
impl magnus::DataTypeFunctions for Automaton {
|
|
400
|
+
fn size(&self) -> usize {
|
|
401
|
+
std::mem::size_of::<Self>() + self.pma.heap_bytes()
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
#[magnus::init]
|
|
406
|
+
fn init(ruby: &Ruby) -> Result<(), Error> {
|
|
407
|
+
let module = ruby.define_module("Daachorse")?;
|
|
408
|
+
let class = module.define_class("Automaton", ruby.class_object())?;
|
|
409
|
+
class.undef_default_alloc_func();
|
|
410
|
+
class.define_singleton_method("_build", function!(Automaton::build, 3))?;
|
|
411
|
+
class.define_singleton_method("_load", function!(Automaton::load, 1))?;
|
|
412
|
+
class.define_method("dump", method!(Automaton::dump, 0))?;
|
|
413
|
+
class.define_method("_each_match", method!(Automaton::each_match, 1))?;
|
|
414
|
+
class.define_method("_each_overlapping", method!(Automaton::each_overlapping, 1))?;
|
|
415
|
+
class.define_method("find_all", method!(Automaton::find_all, 1))?;
|
|
416
|
+
class.define_method("find_all_flat", method!(Automaton::find_all_flat, 1))?;
|
|
417
|
+
class.define_method("find_overlapping", method!(Automaton::find_overlapping, 1))?;
|
|
418
|
+
class.define_method("match?", method!(Automaton::is_match, 1))?;
|
|
419
|
+
class.define_method("_match_kind_id", method!(Automaton::match_kind_id, 0))?;
|
|
420
|
+
class.define_method(
|
|
421
|
+
"ascii_case_insensitive?",
|
|
422
|
+
method!(Automaton::ascii_case_insensitive, 0),
|
|
423
|
+
)?;
|
|
424
|
+
class.define_method("heap_bytes", method!(Automaton::heap_bytes, 0))?;
|
|
425
|
+
class.define_method("num_states", method!(Automaton::num_states, 0))?;
|
|
426
|
+
Ok(())
|
|
427
|
+
}
|