fast_regexp 0.3.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: dcf136e08ca05af9856cf9e90133827b753e854d04abf8cc654933c7310caceb
4
+ data.tar.gz: 4b73e1bec598c355f11407f1d5efb5c24d46ae17616b9e23ea8277e4991c2b35
5
+ SHA512:
6
+ metadata.gz: f90d8a0454353ad3bc7f92efbb73644d1b12208a4998bf11eed769d17ddf88c319df2027a7637ca5b6fe997464712f8ae866a40c6cd2abe1f71abd3511e993ff
7
+ data.tar.gz: cdf46976b1d3f6bab3565deb9c479a2a9dc22fe9eeb06514b6811c1ddea5f31beb6e5f2e18af4b4bc4d705b49af18a58f8ab68d1bc535768bf7b7d8fceaf9223
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dmytro Horoshko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # fast_regexp
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/fast_regexp.svg)](https://badge.fury.io/rb/fast_regexp)
4
+ [![Test](https://github.com/jetpks/fast_regexp/workflows/CI/badge.svg)](https://github.com/jetpks/fast_regexp/actions)
5
+
6
+ Ruby bindings for [rust/regex](https://docs.rs/regex/latest/regex/) library.
7
+
8
+ ## Installation
9
+
10
+ Install [Rust](https://www.rust-lang.org/) via [rustup](https://rustup.rs/) or in any other way.
11
+
12
+ Add as a dependency:
13
+
14
+ ```ruby
15
+ # In your Gemfile
16
+ gem "fast_regexp"
17
+
18
+ # Or without Bundler
19
+ gem install fast_regexp
20
+ ```
21
+
22
+ Include in your code:
23
+
24
+ ```ruby
25
+ require "fast_regexp"
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ Regular expressions should be pre-compiled before use:
31
+
32
+ ```ruby
33
+ re = Fast::Regexp.new('p.t{2}ern*')
34
+ # => #<Fast::Regexp:...>
35
+ ```
36
+
37
+ > [!TIP]
38
+ > Note the use of *single quotes* when passing the regular expression as
39
+ > a string to `rust/regex` so that the backslashes aren't interpreted as escapes.
40
+
41
+ You can also build from an existing Ruby `Regexp` — trailing flags (`/i`,
42
+ `/x`, `/m`) are translated to inline form for the rust engine:
43
+
44
+ ```ruby
45
+ Fast::Regexp.new(/foo/i).pattern # => "(?i)foo"
46
+ Fast::Regexp.new(/foo.bar/m).match?("foo\nbar") # => true (Ruby's /m = dotall)
47
+ ```
48
+
49
+ ### Matching
50
+
51
+ `#match` returns a `Fast::Regexp::MatchData` on a hit and `nil` on no match —
52
+ matching Ruby's `Regexp#match` shape:
53
+
54
+ ```ruby
55
+ m = Fast::Regexp.new('(\w+):(\d+)').match("ruby:123, rust:456")
56
+ m[0] # => "ruby:123" (whole match)
57
+ m[1] # => "ruby"
58
+ m[2] # => "123"
59
+ m.pre_match # => ""
60
+ m.post_match # => ", rust:456"
61
+ m.captures # => ["ruby", "123"]
62
+ m.to_a # => ["ruby:123", "ruby", "123"]
63
+ m.byteoffset(0) # => [0, 8]
64
+
65
+ Fast::Regexp.new('\d+').match("abc") # => nil
66
+ ```
67
+
68
+ Named captures use rust/regex's `(?P<name>...)` syntax:
69
+
70
+ ```ruby
71
+ m = Fast::Regexp.new('(?P<word>\w+):(?P<num>\d+)').match("ruby:123")
72
+ m[:word] # => "ruby"
73
+ m["num"] # => "123"
74
+ m.named_captures # => { "word" => "ruby", "num" => "123" }
75
+ ```
76
+
77
+ `#match?`, `#===`, and `#=~` are also available:
78
+
79
+ ```ruby
80
+ re = Fast::Regexp.new('\d+')
81
+ re.match?("123") # => true
82
+ re === "abc 42" # => true (works in case/when)
83
+ re =~ "abc 42" # => 4 (byte offset of first match)
84
+ ```
85
+
86
+ ### Scanning
87
+
88
+ ```ruby
89
+ Fast::Regexp.new('\w+:\d+').scan("ruby:123, rust:456")
90
+ # => ["ruby:123", "rust:456"]
91
+
92
+ Fast::Regexp.new('(\w+):(\d+)').scan("ruby:123, rust:456")
93
+ # => [["ruby", "123"], ["rust", "456"]]
94
+ ```
95
+
96
+ For per-match positions and pre/post-match access, use `#scan_matches`:
97
+
98
+ ```ruby
99
+ Fast::Regexp.new('(\w+):(\d+)').scan_matches("ruby:123, rust:456").map { |m| m.byteoffset(0) }
100
+ # => [[0, 8], [10, 18]]
101
+ ```
102
+
103
+ ### Substitution
104
+
105
+ `#sub` and `#gsub` use rust/regex's native replacement template — `$1`,
106
+ `${name}`, and `$$` for a literal `$`:
107
+
108
+ ```ruby
109
+ re = Fast::Regexp.new('(\w+):(\d+)')
110
+ re.sub("ruby:123 rust:456", '$2-$1') # => "123-ruby rust:456"
111
+ re.gsub("ruby:123 rust:456", '$2-$1') # => "123-ruby 456-rust"
112
+ ```
113
+
114
+ Block form receives a `MatchData`:
115
+
116
+ ```ruby
117
+ Fast::Regexp.new('\d+').gsub("a1 b22 c333") { |m| "<#{m[0].size}>" }
118
+ # => "a<1> b<2> c<3>"
119
+ ```
120
+
121
+ Pass `literal: true` to disable `$`-expansion entirely.
122
+
123
+ ### Other
124
+
125
+ ```ruby
126
+ Fast::Regexp.new('\w+:\d+').pattern # => "\\w+:\\d+"
127
+ Fast::Regexp.new('(?P<n>\w+)').names # => ["n"]
128
+ Fast::Regexp.new('(a)(b)').captures_count # => 2
129
+ ```
130
+
131
+ > [!WARNING]
132
+ > `rust/regex` regular expression syntax differs from Ruby's built-in
133
+ > [`Regexp`](https://docs.ruby-lang.org/en/3.4/Regexp.html) library, see the
134
+ > [official syntax page](https://docs.rs/regex/latest/regex/index.html#syntax) for more
135
+ > details.
136
+
137
+ ### Searching simultaneously
138
+
139
+ `Fast::Regexp::Set` represents a collection of
140
+ regular expressions that can be searched for simultaneously. Calling `Fast::Regexp::Set#match` will return an array containing the indices of all the patterns that matched.
141
+
142
+ ```ruby
143
+ set = Fast::Regexp::Set.new(["abc", "def", "ghi", "xyz"])
144
+
145
+ set.match("abcdefghi") # => [0, 1, 2]
146
+ set.match("ghidefabc") # => [0, 1, 2]
147
+ ```
148
+
149
+ > [!NOTE]
150
+ > Matches arrive in the order the constituent patterns were declared,
151
+ > not the order they appear in the haystack.
152
+
153
+ To check whether at least one pattern from the set matches the haystack:
154
+
155
+ ```ruby
156
+ Fast::Regexp::Set.new(["abc", "def"]).match?("abc")
157
+ # => true
158
+
159
+ Fast::Regexp::Set.new(["abc", "def"]).match?("123")
160
+ # => false
161
+ ```
162
+
163
+ Inspect original patterns:
164
+
165
+ ```ruby
166
+ Fast::Regexp::Set.new(["abc", "def"]).patterns
167
+ # => ["abc", "def"]
168
+ ```
169
+
170
+ ## Encoding
171
+
172
+ Currently, `fast_regexp` expects the haystack to be an UTF-8 string.
173
+
174
+ It also supports parsing of strings with invalid UTF-8 characters by default. It's achieved via using `regex::bytes` instead of plain `regex` under the hood, so any byte sequence can be matched. The output match is encoded as UTF-8 string.
175
+
176
+ In case unicode awarness of matchers should be disabled, both `Fast::Regexp` and `Fast::Regexp::Set` support `unicode: false` option:
177
+
178
+ ```ruby
179
+ Fast::Regexp.new('\w+').match('ю٤夏')
180
+ # => ["ю٤夏"]
181
+
182
+ Fast::Regexp.new('\w+', unicode: false).match('ю٤夏')
183
+ # => []
184
+
185
+ Fast::Regexp::Set.new(['\w', '\d', '\s']).match("ю٤\u2000")
186
+ # => [0, 1, 2]
187
+
188
+ Fast::Regexp::Set.new(['\w', '\d', '\s'], unicode: false).match("ю٤\u2000")
189
+ # => []
190
+ ```
191
+
192
+ ## Development
193
+
194
+ ```sh
195
+ bin/setup # install deps
196
+ bin/console # interactive prompt to play around
197
+ rake compile # (re)compile extension
198
+ rake spec # run tests
199
+ ```
200
+
201
+ ## Contributing
202
+
203
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jetpks/fast_regexp.
204
+
205
+ ## Credits
206
+
207
+ `fast_regexp` is a fork of
208
+ [`rust_regexp`](https://github.com/ocvit/rust_regexp) by Dmytro Horoshko —
209
+ huge thanks for the original bindings and the clean magnus integration that
210
+ made this work easy to extend. This fork rebrands the gem, reshapes the
211
+ public API (`Fast::Regexp`, real `MatchData`, `sub`/`gsub`, `===`/`=~`,
212
+ `Regexp`-constructor coercion), and releases the GVL around regex execution
213
+ for thread/fiber-friendly matching.
214
+
215
+ ## License
216
+
217
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,283 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "aho-corasick"
7
+ version = "1.1.4"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
10
+ dependencies = [
11
+ "memchr",
12
+ ]
13
+
14
+ [[package]]
15
+ name = "bindgen"
16
+ version = "0.72.1"
17
+ source = "registry+https://github.com/rust-lang/crates.io-index"
18
+ checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
19
+ dependencies = [
20
+ "bitflags",
21
+ "cexpr",
22
+ "clang-sys",
23
+ "itertools",
24
+ "proc-macro2",
25
+ "quote",
26
+ "regex",
27
+ "rustc-hash",
28
+ "shlex",
29
+ "syn",
30
+ ]
31
+
32
+ [[package]]
33
+ name = "bitflags"
34
+ version = "2.11.1"
35
+ source = "registry+https://github.com/rust-lang/crates.io-index"
36
+ checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
37
+
38
+ [[package]]
39
+ name = "cexpr"
40
+ version = "0.6.0"
41
+ source = "registry+https://github.com/rust-lang/crates.io-index"
42
+ checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
43
+ dependencies = [
44
+ "nom",
45
+ ]
46
+
47
+ [[package]]
48
+ name = "cfg-if"
49
+ version = "1.0.4"
50
+ source = "registry+https://github.com/rust-lang/crates.io-index"
51
+ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
52
+
53
+ [[package]]
54
+ name = "clang-sys"
55
+ version = "1.8.1"
56
+ source = "registry+https://github.com/rust-lang/crates.io-index"
57
+ checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
58
+ dependencies = [
59
+ "glob",
60
+ "libc",
61
+ "libloading",
62
+ ]
63
+
64
+ [[package]]
65
+ name = "either"
66
+ version = "1.15.0"
67
+ source = "registry+https://github.com/rust-lang/crates.io-index"
68
+ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
69
+
70
+ [[package]]
71
+ name = "fast_regexp"
72
+ version = "0.1.0"
73
+ dependencies = [
74
+ "magnus",
75
+ "rb-sys",
76
+ "regex",
77
+ ]
78
+
79
+ [[package]]
80
+ name = "glob"
81
+ version = "0.3.3"
82
+ source = "registry+https://github.com/rust-lang/crates.io-index"
83
+ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
84
+
85
+ [[package]]
86
+ name = "itertools"
87
+ version = "0.13.0"
88
+ source = "registry+https://github.com/rust-lang/crates.io-index"
89
+ checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
90
+ dependencies = [
91
+ "either",
92
+ ]
93
+
94
+ [[package]]
95
+ name = "lazy_static"
96
+ version = "1.5.0"
97
+ source = "registry+https://github.com/rust-lang/crates.io-index"
98
+ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
99
+
100
+ [[package]]
101
+ name = "libc"
102
+ version = "0.2.186"
103
+ source = "registry+https://github.com/rust-lang/crates.io-index"
104
+ checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
105
+
106
+ [[package]]
107
+ name = "libloading"
108
+ version = "0.8.9"
109
+ source = "registry+https://github.com/rust-lang/crates.io-index"
110
+ checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
111
+ dependencies = [
112
+ "cfg-if",
113
+ "windows-link",
114
+ ]
115
+
116
+ [[package]]
117
+ name = "magnus"
118
+ version = "0.8.2"
119
+ source = "registry+https://github.com/rust-lang/crates.io-index"
120
+ checksum = "3b36a5b126bbe97eb0d02d07acfeb327036c6319fd816139a49824a83b7f9012"
121
+ dependencies = [
122
+ "magnus-macros",
123
+ "rb-sys",
124
+ "rb-sys-env",
125
+ "seq-macro",
126
+ ]
127
+
128
+ [[package]]
129
+ name = "magnus-macros"
130
+ version = "0.8.0"
131
+ source = "registry+https://github.com/rust-lang/crates.io-index"
132
+ checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
133
+ dependencies = [
134
+ "proc-macro2",
135
+ "quote",
136
+ "syn",
137
+ ]
138
+
139
+ [[package]]
140
+ name = "memchr"
141
+ version = "2.8.0"
142
+ source = "registry+https://github.com/rust-lang/crates.io-index"
143
+ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
144
+
145
+ [[package]]
146
+ name = "minimal-lexical"
147
+ version = "0.2.1"
148
+ source = "registry+https://github.com/rust-lang/crates.io-index"
149
+ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
150
+
151
+ [[package]]
152
+ name = "nom"
153
+ version = "7.1.3"
154
+ source = "registry+https://github.com/rust-lang/crates.io-index"
155
+ checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
156
+ dependencies = [
157
+ "memchr",
158
+ "minimal-lexical",
159
+ ]
160
+
161
+ [[package]]
162
+ name = "proc-macro2"
163
+ version = "1.0.106"
164
+ source = "registry+https://github.com/rust-lang/crates.io-index"
165
+ checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
166
+ dependencies = [
167
+ "unicode-ident",
168
+ ]
169
+
170
+ [[package]]
171
+ name = "quote"
172
+ version = "1.0.45"
173
+ source = "registry+https://github.com/rust-lang/crates.io-index"
174
+ checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
175
+ dependencies = [
176
+ "proc-macro2",
177
+ ]
178
+
179
+ [[package]]
180
+ name = "rb-sys"
181
+ version = "0.9.128"
182
+ source = "registry+https://github.com/rust-lang/crates.io-index"
183
+ checksum = "45ca28513560e56cfb79a62b1fce363c73af170a182024ce880c77ee9429920a"
184
+ dependencies = [
185
+ "rb-sys-build",
186
+ ]
187
+
188
+ [[package]]
189
+ name = "rb-sys-build"
190
+ version = "0.9.128"
191
+ source = "registry+https://github.com/rust-lang/crates.io-index"
192
+ checksum = "ce04b2c55eff3a21aaa623fcc655d94373238e72cac6b3e1a3641ff31649f99a"
193
+ dependencies = [
194
+ "bindgen",
195
+ "lazy_static",
196
+ "proc-macro2",
197
+ "quote",
198
+ "regex",
199
+ "shell-words",
200
+ "syn",
201
+ ]
202
+
203
+ [[package]]
204
+ name = "rb-sys-env"
205
+ version = "0.2.3"
206
+ source = "registry+https://github.com/rust-lang/crates.io-index"
207
+ checksum = "cca7ad6a7e21e72151d56fe2495a259b5670e204c3adac41ee7ef676ea08117a"
208
+
209
+ [[package]]
210
+ name = "regex"
211
+ version = "1.12.3"
212
+ source = "registry+https://github.com/rust-lang/crates.io-index"
213
+ checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
214
+ dependencies = [
215
+ "aho-corasick",
216
+ "memchr",
217
+ "regex-automata",
218
+ "regex-syntax",
219
+ ]
220
+
221
+ [[package]]
222
+ name = "regex-automata"
223
+ version = "0.4.14"
224
+ source = "registry+https://github.com/rust-lang/crates.io-index"
225
+ checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
226
+ dependencies = [
227
+ "aho-corasick",
228
+ "memchr",
229
+ "regex-syntax",
230
+ ]
231
+
232
+ [[package]]
233
+ name = "regex-syntax"
234
+ version = "0.8.10"
235
+ source = "registry+https://github.com/rust-lang/crates.io-index"
236
+ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
237
+
238
+ [[package]]
239
+ name = "rustc-hash"
240
+ version = "2.1.2"
241
+ source = "registry+https://github.com/rust-lang/crates.io-index"
242
+ checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
243
+
244
+ [[package]]
245
+ name = "seq-macro"
246
+ version = "0.3.6"
247
+ source = "registry+https://github.com/rust-lang/crates.io-index"
248
+ checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
249
+
250
+ [[package]]
251
+ name = "shell-words"
252
+ version = "1.1.1"
253
+ source = "registry+https://github.com/rust-lang/crates.io-index"
254
+ checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
255
+
256
+ [[package]]
257
+ name = "shlex"
258
+ version = "1.3.0"
259
+ source = "registry+https://github.com/rust-lang/crates.io-index"
260
+ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
261
+
262
+ [[package]]
263
+ name = "syn"
264
+ version = "2.0.117"
265
+ source = "registry+https://github.com/rust-lang/crates.io-index"
266
+ checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
267
+ dependencies = [
268
+ "proc-macro2",
269
+ "quote",
270
+ "unicode-ident",
271
+ ]
272
+
273
+ [[package]]
274
+ name = "unicode-ident"
275
+ version = "1.0.24"
276
+ source = "registry+https://github.com/rust-lang/crates.io-index"
277
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
278
+
279
+ [[package]]
280
+ name = "windows-link"
281
+ version = "0.2.1"
282
+ source = "registry+https://github.com/rust-lang/crates.io-index"
283
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
@@ -0,0 +1,12 @@
1
+ [package]
2
+ name = "fast_regexp"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+
6
+ [lib]
7
+ crate-type = ["cdylib"]
8
+
9
+ [dependencies]
10
+ magnus = "0.8"
11
+ regex = "1"
12
+ rb-sys = "0.9"
@@ -0,0 +1,4 @@
1
+ require "mkmf"
2
+ require "rb_sys/mkmf"
3
+
4
+ create_rust_makefile("fast_regexp/fast_regexp")
@@ -0,0 +1,542 @@
1
+ use magnus::{
2
+ function, method,
3
+ scan_args::{get_kwargs, scan_args},
4
+ value::ReprValue,
5
+ Error, Module, Object, RArray, RHash, RString, Ruby, Symbol, TryConvert, Value,
6
+ };
7
+ use regex::bytes::{NoExpand, Regex, RegexBuilder, RegexSet, RegexSetBuilder};
8
+ use std::collections::HashMap;
9
+ use std::ffi::c_void;
10
+ use std::ptr;
11
+ use std::sync::Arc;
12
+
13
+ /// Skip GVL release for haystacks smaller than this — the release/reacquire
14
+ /// overhead (~µs) dwarfs the cost of a regex match on a tiny string.
15
+ const GVL_RELEASE_THRESHOLD: usize = 1024;
16
+
17
+ /// Run `func` with the GVL released so other Ruby threads (and the fiber
18
+ /// scheduler on its host thread) can make progress during a long regex match.
19
+ ///
20
+ /// The callback runs on the same OS thread — `Send` is not required, and the
21
+ /// borrow checker enforces that any references stay valid for the call.
22
+ fn without_gvl<F, R>(func: F) -> R
23
+ where
24
+ F: FnOnce() -> R,
25
+ {
26
+ struct Pack<F, R> {
27
+ func: Option<F>,
28
+ result: Option<R>,
29
+ }
30
+
31
+ unsafe extern "C" fn trampoline<F, R>(data: *mut c_void) -> *mut c_void
32
+ where
33
+ F: FnOnce() -> R,
34
+ {
35
+ let pack = &mut *(data as *mut Pack<F, R>);
36
+ let func = pack.func.take().expect("trampoline called twice");
37
+ pack.result = Some(func());
38
+ ptr::null_mut()
39
+ }
40
+
41
+ let mut pack: Pack<F, R> = Pack {
42
+ func: Some(func),
43
+ result: None,
44
+ };
45
+ unsafe {
46
+ rb_sys::rb_thread_call_without_gvl(
47
+ Some(trampoline::<F, R>),
48
+ &mut pack as *mut _ as *mut c_void,
49
+ None,
50
+ ptr::null_mut(),
51
+ );
52
+ }
53
+ pack.result.take().expect("callback did not run")
54
+ }
55
+
56
+ fn run_regex<F, R>(haystack_len: usize, func: F) -> R
57
+ where
58
+ F: FnOnce() -> R,
59
+ {
60
+ if haystack_len >= GVL_RELEASE_THRESHOLD {
61
+ without_gvl(func)
62
+ } else {
63
+ func()
64
+ }
65
+ }
66
+
67
+ fn haystack_bytes(haystack: &RString) -> Vec<u8> {
68
+ // Copy out of the Ruby heap so the bytes are safe to read after the GVL is
69
+ // released (Ruby 4's compacting GC can otherwise move the string).
70
+ unsafe { haystack.as_slice() }.to_vec()
71
+ }
72
+
73
+ fn utf8_string(ruby: &Ruby, bytes: &[u8]) -> RString {
74
+ ruby.enc_str_new(bytes, ruby.utf8_encoding())
75
+ }
76
+
77
+ fn arg_error(message: impl Into<String>) -> Error {
78
+ Error::new(
79
+ Ruby::get().unwrap().exception_arg_error(),
80
+ message.into(),
81
+ )
82
+ }
83
+
84
+ fn type_error(message: impl Into<String>) -> Error {
85
+ Error::new(
86
+ Ruby::get().unwrap().exception_type_error(),
87
+ message.into(),
88
+ )
89
+ }
90
+
91
+ type CaptureOffset = Option<(usize, usize)>;
92
+
93
+ /// Inner state shared between a compiled regex and any [`FastMatchData`] it
94
+ /// produces — wrapped in `Arc` so positions, names, and haystack bytes can be
95
+ /// shared cheaply across many matches (e.g. from `#scan_matches`).
96
+ struct RegexInner {
97
+ regex: Regex,
98
+ /// `name -> capture index`. Empty when the pattern has no named captures.
99
+ names: HashMap<String, usize>,
100
+ /// Ordered list of capture-group names (None for unnamed groups), matching
101
+ /// the indices produced by `regex.captures_iter()`.
102
+ name_index: Vec<Option<String>>,
103
+ }
104
+
105
+ impl RegexInner {
106
+ fn from_pattern(pattern: &str, unicode: bool) -> Result<Self, Error> {
107
+ let regex = RegexBuilder::new(pattern)
108
+ .unicode(unicode)
109
+ .build()
110
+ .map_err(|e| arg_error(e.to_string()))?;
111
+
112
+ let name_index: Vec<Option<String>> =
113
+ regex.capture_names().map(|n| n.map(String::from)).collect();
114
+ let mut names = HashMap::new();
115
+ for (idx, name) in name_index.iter().enumerate() {
116
+ if let Some(n) = name {
117
+ names.insert(n.clone(), idx);
118
+ }
119
+ }
120
+
121
+ Ok(Self {
122
+ regex,
123
+ names,
124
+ name_index,
125
+ })
126
+ }
127
+ }
128
+
129
+ #[magnus::wrap(class = "Fast::Regexp", free_immediately, size)]
130
+ pub struct FastRegexp(Arc<RegexInner>);
131
+
132
+ impl FastRegexp {
133
+ pub fn new(args: &[Value]) -> Result<Self, Error> {
134
+ let args = scan_args::<(String,), (), (), (), RHash, ()>(args)?;
135
+ let kwargs = get_kwargs::<_, (), (Option<bool>,), ()>(args.keywords, &[], &["unicode"])?;
136
+
137
+ let pattern = args.required.0;
138
+ let (unicode,) = kwargs.optional;
139
+ let unicode = unicode.unwrap_or(true);
140
+
141
+ Ok(Self(Arc::new(RegexInner::from_pattern(&pattern, unicode)?)))
142
+ }
143
+
144
+ fn build_match_data(
145
+ &self,
146
+ haystack: Arc<Vec<u8>>,
147
+ offsets: Vec<CaptureOffset>,
148
+ ) -> FastMatchData {
149
+ FastMatchData {
150
+ haystack,
151
+ captures: offsets,
152
+ inner: self.0.clone(),
153
+ }
154
+ }
155
+
156
+ pub fn rmatch(&self, haystack: RString) -> Option<FastMatchData> {
157
+ let regex = &self.0.regex;
158
+ let bytes = haystack_bytes(&haystack);
159
+
160
+ let offsets = run_regex(bytes.len(), || {
161
+ regex.captures(&bytes).map(|caps| {
162
+ (0..regex.captures_len())
163
+ .map(|i| caps.get(i).map(|m| (m.start(), m.end())))
164
+ .collect::<Vec<_>>()
165
+ })
166
+ })?;
167
+
168
+ Some(self.build_match_data(Arc::new(bytes), offsets))
169
+ }
170
+
171
+ pub fn scan(ruby: &Ruby, rb_self: &Self, haystack: RString) -> Result<RArray, Error> {
172
+ let regex = &rb_self.0.regex;
173
+ let bytes = haystack_bytes(&haystack);
174
+
175
+ if regex.captures_len() == 1 {
176
+ let ranges: Vec<(usize, usize)> = run_regex(bytes.len(), || {
177
+ regex
178
+ .find_iter(&bytes)
179
+ .map(|m| (m.start(), m.end()))
180
+ .collect()
181
+ });
182
+ let result = ruby.ary_new_capa(ranges.len());
183
+ for (s, e) in ranges {
184
+ result.push(utf8_string(ruby, &bytes[s..e]))?;
185
+ }
186
+ Ok(result)
187
+ } else {
188
+ let groups: Vec<Vec<CaptureOffset>> = run_regex(bytes.len(), || {
189
+ regex
190
+ .captures_iter(&bytes)
191
+ .map(|caps| {
192
+ caps.iter()
193
+ .skip(1)
194
+ .map(|c| c.map(|m| (m.start(), m.end())))
195
+ .collect()
196
+ })
197
+ .collect()
198
+ });
199
+ let result = ruby.ary_new_capa(groups.len());
200
+ for group_ranges in groups {
201
+ let group = ruby.ary_new_capa(group_ranges.len());
202
+ for range in group_ranges {
203
+ match range {
204
+ Some((s, e)) => group.push(utf8_string(ruby, &bytes[s..e]))?,
205
+ None => group.push(())?,
206
+ }
207
+ }
208
+ result.push(group)?;
209
+ }
210
+ Ok(result)
211
+ }
212
+ }
213
+
214
+ pub fn scan_matches(ruby: &Ruby, rb_self: &Self, haystack: RString) -> Result<RArray, Error> {
215
+ let regex = &rb_self.0.regex;
216
+ let bytes = haystack_bytes(&haystack);
217
+ let n_groups = regex.captures_len();
218
+
219
+ let all: Vec<Vec<CaptureOffset>> = run_regex(bytes.len(), || {
220
+ regex
221
+ .captures_iter(&bytes)
222
+ .map(|caps| {
223
+ (0..n_groups)
224
+ .map(|i| caps.get(i).map(|m| (m.start(), m.end())))
225
+ .collect()
226
+ })
227
+ .collect()
228
+ });
229
+
230
+ let shared = Arc::new(bytes);
231
+ let result = ruby.ary_new_capa(all.len());
232
+ for offsets in all {
233
+ result.push(rb_self.build_match_data(shared.clone(), offsets))?;
234
+ }
235
+ Ok(result)
236
+ }
237
+
238
+ pub fn is_match(&self, haystack: RString) -> bool {
239
+ let regex = &self.0.regex;
240
+ let bytes = haystack_bytes(&haystack);
241
+ run_regex(bytes.len(), || regex.is_match(&bytes))
242
+ }
243
+
244
+ pub fn sub_str(
245
+ ruby: &Ruby,
246
+ rb_self: &Self,
247
+ haystack: RString,
248
+ replacement: RString,
249
+ literal: bool,
250
+ ) -> RString {
251
+ let regex = &rb_self.0.regex;
252
+ let bytes = haystack_bytes(&haystack);
253
+ let repl = haystack_bytes(&replacement);
254
+ let out = run_regex(bytes.len(), || -> Vec<u8> {
255
+ if literal {
256
+ regex.replace(&bytes, NoExpand(&repl)).into_owned()
257
+ } else {
258
+ regex.replace(&bytes, &repl[..]).into_owned()
259
+ }
260
+ });
261
+ utf8_string(ruby, &out)
262
+ }
263
+
264
+ pub fn gsub_str(
265
+ ruby: &Ruby,
266
+ rb_self: &Self,
267
+ haystack: RString,
268
+ replacement: RString,
269
+ literal: bool,
270
+ ) -> RString {
271
+ let regex = &rb_self.0.regex;
272
+ let bytes = haystack_bytes(&haystack);
273
+ let repl = haystack_bytes(&replacement);
274
+ let out = run_regex(bytes.len(), || -> Vec<u8> {
275
+ if literal {
276
+ regex.replace_all(&bytes, NoExpand(&repl)).into_owned()
277
+ } else {
278
+ regex.replace_all(&bytes, &repl[..]).into_owned()
279
+ }
280
+ });
281
+ utf8_string(ruby, &out)
282
+ }
283
+
284
+ pub fn pattern(&self) -> &str {
285
+ self.0.regex.as_str()
286
+ }
287
+
288
+ pub fn captures_count(&self) -> usize {
289
+ // Excludes the implicit whole-match group, matching Regexp's behavior.
290
+ self.0.regex.captures_len() - 1
291
+ }
292
+
293
+ pub fn names(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
294
+ let arr = ruby.ary_new();
295
+ for name in rb_self.0.name_index.iter().skip(1).flatten() {
296
+ arr.push(name.as_str())?;
297
+ }
298
+ Ok(arr)
299
+ }
300
+ }
301
+
302
+ #[magnus::wrap(class = "Fast::Regexp::MatchData", free_immediately, size)]
303
+ pub struct FastMatchData {
304
+ haystack: Arc<Vec<u8>>,
305
+ /// Index 0 is the whole match. Subsequent entries are capture groups in
306
+ /// order; `None` indicates a group that did not participate.
307
+ captures: Vec<CaptureOffset>,
308
+ inner: Arc<RegexInner>,
309
+ }
310
+
311
+ impl FastMatchData {
312
+ fn slice(&self, ruby: &Ruby, range: (usize, usize)) -> RString {
313
+ utf8_string(ruby, &self.haystack[range.0..range.1])
314
+ }
315
+
316
+ fn capture_index(&self, idx: i64) -> Option<usize> {
317
+ let len = self.captures.len() as i64;
318
+ let real = if idx < 0 { len + idx } else { idx };
319
+ if real < 0 || real >= len {
320
+ None
321
+ } else {
322
+ Some(real as usize)
323
+ }
324
+ }
325
+
326
+ /// Returns `Some(Some(range))` for a participating group, `Some(None)` for
327
+ /// a known-but-non-participating group, `None` for an out-of-range index
328
+ /// or an unknown capture name.
329
+ fn resolve(&self, key: Value) -> Result<Option<CaptureOffset>, Error> {
330
+ if let Ok(i) = <i64 as TryConvert>::try_convert(key) {
331
+ return Ok(self.capture_index(i).map(|i| self.captures[i]));
332
+ }
333
+ if let Ok(sym) = <Symbol as TryConvert>::try_convert(key) {
334
+ let name = sym.name()?.into_owned();
335
+ return Ok(self.inner.names.get(&name).map(|&i| self.captures[i]));
336
+ }
337
+ if let Ok(name) = <String as TryConvert>::try_convert(key) {
338
+ return Ok(self.inner.names.get(&name).map(|&i| self.captures[i]));
339
+ }
340
+ Err(type_error(
341
+ "no implicit conversion of capture key into Integer, String, or Symbol",
342
+ ))
343
+ }
344
+
345
+ fn whole(&self) -> (usize, usize) {
346
+ self.captures[0].expect("whole match is always present")
347
+ }
348
+
349
+ pub fn aref(ruby: &Ruby, rb_self: &Self, key: Value) -> Result<Value, Error> {
350
+ match rb_self.resolve(key)? {
351
+ Some(Some(range)) => Ok(rb_self.slice(ruby, range).as_value()),
352
+ _ => Ok(ruby.qnil().as_value()),
353
+ }
354
+ }
355
+
356
+ pub fn to_a(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
357
+ let arr = ruby.ary_new_capa(rb_self.captures.len());
358
+ for cap in &rb_self.captures {
359
+ match cap {
360
+ Some(r) => arr.push(rb_self.slice(ruby, *r))?,
361
+ None => arr.push(())?,
362
+ }
363
+ }
364
+ Ok(arr)
365
+ }
366
+
367
+ pub fn captures(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
368
+ let arr = ruby.ary_new_capa(rb_self.captures.len() - 1);
369
+ for cap in rb_self.captures.iter().skip(1) {
370
+ match cap {
371
+ Some(r) => arr.push(rb_self.slice(ruby, *r))?,
372
+ None => arr.push(())?,
373
+ }
374
+ }
375
+ Ok(arr)
376
+ }
377
+
378
+ pub fn named_captures(ruby: &Ruby, rb_self: &Self) -> Result<RHash, Error> {
379
+ let hash = ruby.hash_new();
380
+ // Iterate in declaration order so the hash preserves regex order.
381
+ for (idx, name) in rb_self.inner.name_index.iter().enumerate() {
382
+ if let Some(name) = name {
383
+ let value: Value = match rb_self.captures[idx] {
384
+ Some(r) => rb_self.slice(ruby, r).as_value(),
385
+ None => ruby.qnil().as_value(),
386
+ };
387
+ hash.aset(name.as_str(), value)?;
388
+ }
389
+ }
390
+ Ok(hash)
391
+ }
392
+
393
+ pub fn names(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
394
+ let arr = ruby.ary_new();
395
+ for name in rb_self.inner.name_index.iter().skip(1).flatten() {
396
+ arr.push(name.as_str())?;
397
+ }
398
+ Ok(arr)
399
+ }
400
+
401
+ pub fn size(&self) -> usize {
402
+ self.captures.len()
403
+ }
404
+
405
+ pub fn pre_match(ruby: &Ruby, rb_self: &Self) -> RString {
406
+ let (s, _) = rb_self.whole();
407
+ utf8_string(ruby, &rb_self.haystack[..s])
408
+ }
409
+
410
+ pub fn post_match(ruby: &Ruby, rb_self: &Self) -> RString {
411
+ let (_, e) = rb_self.whole();
412
+ utf8_string(ruby, &rb_self.haystack[e..])
413
+ }
414
+
415
+ pub fn whole_match(ruby: &Ruby, rb_self: &Self) -> RString {
416
+ rb_self.slice(ruby, rb_self.whole())
417
+ }
418
+
419
+ pub fn string(ruby: &Ruby, rb_self: &Self) -> RString {
420
+ let s = utf8_string(ruby, &rb_self.haystack);
421
+ s.freeze();
422
+ s
423
+ }
424
+
425
+ pub fn byteoffset(ruby: &Ruby, rb_self: &Self, key: Value) -> Result<Value, Error> {
426
+ let resolved = rb_self.resolve(key)?;
427
+ let arr = ruby.ary_new_capa(2);
428
+ match resolved {
429
+ Some(Some((s, e))) => {
430
+ arr.push(s)?;
431
+ arr.push(e)?;
432
+ }
433
+ Some(None) | None => {
434
+ arr.push(())?;
435
+ arr.push(())?;
436
+ }
437
+ }
438
+ Ok(arr.as_value())
439
+ }
440
+
441
+ pub fn byte_begin(ruby: &Ruby, rb_self: &Self, key: Value) -> Result<Value, Error> {
442
+ Ok(match rb_self.resolve(key)? {
443
+ Some(Some((s, _))) => ruby.integer_from_u64(s as u64).as_value(),
444
+ _ => ruby.qnil().as_value(),
445
+ })
446
+ }
447
+
448
+ pub fn byte_end(ruby: &Ruby, rb_self: &Self, key: Value) -> Result<Value, Error> {
449
+ Ok(match rb_self.resolve(key)? {
450
+ Some(Some((_, e))) => ruby.integer_from_u64(e as u64).as_value(),
451
+ _ => ruby.qnil().as_value(),
452
+ })
453
+ }
454
+
455
+ pub fn inspect(ruby: &Ruby, rb_self: &Self) -> RString {
456
+ let (s, e) = rb_self.whole();
457
+ let matched = String::from_utf8_lossy(&rb_self.haystack[s..e]);
458
+ ruby.str_new(&format!("#<Fast::Regexp::MatchData {:?}>", matched))
459
+ }
460
+ }
461
+
462
+ #[magnus::wrap(class = "Fast::Regexp::Set", free_immediately, size)]
463
+ pub struct FastRegexpSet(RegexSet);
464
+
465
+ impl FastRegexpSet {
466
+ pub fn new(args: &[Value]) -> Result<Self, Error> {
467
+ let args = scan_args::<(Vec<String>,), (), (), (), RHash, ()>(args)?;
468
+ let kwargs = get_kwargs::<_, (), (Option<bool>,), ()>(args.keywords, &[], &["unicode"])?;
469
+
470
+ let patterns = args.required.0;
471
+ let (unicode,) = kwargs.optional;
472
+ let unicode = unicode.unwrap_or(true);
473
+
474
+ let set = RegexSetBuilder::new(patterns)
475
+ .unicode(unicode)
476
+ .build()
477
+ .map_err(|e| arg_error(e.to_string()))?;
478
+
479
+ Ok(Self(set))
480
+ }
481
+
482
+ pub fn matches(&self, haystack: RString) -> Vec<usize> {
483
+ let set = &self.0;
484
+ let bytes = haystack_bytes(&haystack);
485
+ run_regex(bytes.len(), || set.matches(&bytes).iter().collect())
486
+ }
487
+
488
+ pub fn is_match(&self, haystack: RString) -> bool {
489
+ let set = &self.0;
490
+ let bytes = haystack_bytes(&haystack);
491
+ run_regex(bytes.len(), || set.is_match(&bytes))
492
+ }
493
+
494
+ pub fn patterns(&self) -> Vec<String> {
495
+ self.0.patterns().into()
496
+ }
497
+ }
498
+
499
+ #[magnus::init]
500
+ pub fn init(ruby: &Ruby) -> Result<(), Error> {
501
+ let object_class = ruby.class_object();
502
+ let fast_module = ruby.define_module("Fast")?;
503
+ let regexp_class = fast_module.define_class("Regexp", object_class)?;
504
+
505
+ regexp_class.define_singleton_method("_native_new", function!(FastRegexp::new, -1))?;
506
+ regexp_class.define_method("_native_match", method!(FastRegexp::rmatch, 1))?;
507
+ regexp_class.define_method("match?", method!(FastRegexp::is_match, 1))?;
508
+ regexp_class.define_method("scan", method!(FastRegexp::scan, 1))?;
509
+ regexp_class.define_method("scan_matches", method!(FastRegexp::scan_matches, 1))?;
510
+ regexp_class.define_method("pattern", method!(FastRegexp::pattern, 0))?;
511
+ regexp_class.define_method("captures_count", method!(FastRegexp::captures_count, 0))?;
512
+ regexp_class.define_method("names", method!(FastRegexp::names, 0))?;
513
+ regexp_class.define_method("_native_sub", method!(FastRegexp::sub_str, 3))?;
514
+ regexp_class.define_method("_native_gsub", method!(FastRegexp::gsub_str, 3))?;
515
+
516
+ let match_data_class = regexp_class.define_class("MatchData", object_class)?;
517
+ match_data_class.define_method("[]", method!(FastMatchData::aref, 1))?;
518
+ match_data_class.define_method("to_a", method!(FastMatchData::to_a, 0))?;
519
+ match_data_class.define_method("captures", method!(FastMatchData::captures, 0))?;
520
+ match_data_class.define_method("named_captures", method!(FastMatchData::named_captures, 0))?;
521
+ match_data_class.define_method("names", method!(FastMatchData::names, 0))?;
522
+ match_data_class.define_method("size", method!(FastMatchData::size, 0))?;
523
+ match_data_class.define_method("length", method!(FastMatchData::size, 0))?;
524
+ match_data_class.define_method("pre_match", method!(FastMatchData::pre_match, 0))?;
525
+ match_data_class.define_method("post_match", method!(FastMatchData::post_match, 0))?;
526
+ match_data_class.define_method("match", method!(FastMatchData::whole_match, 0))?;
527
+ match_data_class.define_method("to_s", method!(FastMatchData::whole_match, 0))?;
528
+ match_data_class.define_method("string", method!(FastMatchData::string, 0))?;
529
+ match_data_class.define_method("byteoffset", method!(FastMatchData::byteoffset, 1))?;
530
+ match_data_class.define_method("byte_begin", method!(FastMatchData::byte_begin, 1))?;
531
+ match_data_class.define_method("byte_end", method!(FastMatchData::byte_end, 1))?;
532
+ match_data_class.define_method("inspect", method!(FastMatchData::inspect, 0))?;
533
+
534
+ let regexp_set_class = regexp_class.define_class("Set", object_class)?;
535
+
536
+ regexp_set_class.define_singleton_method("new", function!(FastRegexpSet::new, -1))?;
537
+ regexp_set_class.define_method("match", method!(FastRegexpSet::matches, 1))?;
538
+ regexp_set_class.define_method("match?", method!(FastRegexpSet::is_match, 1))?;
539
+ regexp_set_class.define_method("patterns", method!(FastRegexpSet::patterns, 0))?;
540
+
541
+ Ok(())
542
+ }
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fast
4
+ class Regexp
5
+ VERSION = "0.3.0"
6
+ end
7
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "fast_regexp/version"
4
+ require_relative "fast_regexp/fast_regexp"
5
+
6
+ # Ruby-side conveniences on top of the Rust extension. The native class only
7
+ # exposes raw primitives (`_native_new`, `_native_match`, `_native_sub`,
8
+ # `_native_gsub`); everything user-facing lives here so the API can grow
9
+ # without touching FFI.
10
+ module Fast
11
+ class Regexp
12
+ RUBY_FLAG_MAP = {
13
+ ::Regexp::IGNORECASE => "i",
14
+ ::Regexp::EXTENDED => "x",
15
+ ::Regexp::MULTILINE => "s" # Ruby's /m = dotall; in rust/regex that is (?s).
16
+ }.freeze
17
+
18
+ class << self
19
+ # Accept either a pattern string or an existing `::Regexp`. When given a
20
+ # Regexp the flags (`/i`, `/x`, `/m`) are translated into a leading
21
+ # inline group so the rust/regex engine sees them. Unsupported features
22
+ # (lookaround, backrefs) still raise from the engine with a clear
23
+ # message.
24
+ def new(pattern, **opts)
25
+ pattern = translate_regexp(pattern) if pattern.is_a?(::Regexp)
26
+ _native_new(pattern, **opts)
27
+ end
28
+
29
+ private
30
+
31
+ def translate_regexp(regexp)
32
+ flags = RUBY_FLAG_MAP.each_with_object(+"") do |(bit, char), acc|
33
+ acc << char if (regexp.options & bit) != 0
34
+ end
35
+ flags.empty? ? regexp.source : "(?#{flags})#{regexp.source}"
36
+ end
37
+ end
38
+
39
+ # Returns a `Fast::Regexp::MatchData` on hit, `nil` on miss — matching
40
+ # Ruby's `Regexp#match` shape so the old `[]`-truthy-but-empty trap is
41
+ # gone.
42
+ def match(haystack)
43
+ _native_match(coerce_string(haystack))
44
+ end
45
+
46
+ # Case-equality. Enables `case/when` and RSpec's
47
+ # `expect(str).to match(re)`.
48
+ def ===(other)
49
+ return false unless other.respond_to?(:to_str)
50
+ match?(other.to_str)
51
+ end
52
+
53
+ # Returns the byte offset of the first match, or nil. Matches the
54
+ # semantics of `Regexp#=~` except positions are in **bytes** (rust/regex
55
+ # is byte-based).
56
+ def =~(other)
57
+ return nil unless other.respond_to?(:to_str)
58
+ m = match(other.to_str)
59
+ m && m.byte_begin(0)
60
+ end
61
+
62
+ # `sub(haystack, replacement)` or `sub(haystack) { |m| ... }`.
63
+ #
64
+ # The string form uses rust/regex's native replacement template: `$1`,
65
+ # `${name}`, `$$` for a literal `$`. To pass a replacement string that
66
+ # contains `$` literally, pass `literal: true`.
67
+ def sub(haystack, replacement = nil, literal: false, &block)
68
+ haystack = coerce_string(haystack)
69
+ if block
70
+ raise ArgumentError, "wrong number of arguments (given 2, expected 1 with block)" if replacement
71
+ m = match(haystack)
72
+ return haystack.dup unless m
73
+ "#{m.pre_match}#{block.call(m)}#{m.post_match}"
74
+ else
75
+ raise ArgumentError, "wrong number of arguments (given 1, expected 2)" if replacement.nil?
76
+ _native_sub(haystack, coerce_string(replacement), literal)
77
+ end
78
+ end
79
+
80
+ # `gsub(haystack, replacement)` or `gsub(haystack) { |m| ... }`. See
81
+ # `#sub` for the template syntax.
82
+ def gsub(haystack, replacement = nil, literal: false, &block)
83
+ haystack = coerce_string(haystack)
84
+ if block
85
+ raise ArgumentError, "wrong number of arguments (given 2, expected 1 with block)" if replacement
86
+ gsub_with_block(haystack, &block)
87
+ else
88
+ raise ArgumentError, "wrong number of arguments (given 1, expected 2)" if replacement.nil?
89
+ _native_gsub(haystack, coerce_string(replacement), literal)
90
+ end
91
+ end
92
+
93
+ def inspect
94
+ "#<Fast::Regexp #{pattern.inspect}>"
95
+ end
96
+
97
+ alias_method :to_s, :pattern
98
+
99
+ private
100
+
101
+ def gsub_with_block(haystack)
102
+ matches = scan_matches(haystack)
103
+ return haystack.dup if matches.empty?
104
+
105
+ out = String.new(encoding: Encoding::UTF_8)
106
+ cursor = 0
107
+ matches.each do |m|
108
+ bs, be = m.byteoffset(0)
109
+ out << haystack.byteslice(cursor, bs - cursor) if bs > cursor
110
+ out << yield(m).to_s
111
+ cursor = be
112
+ end
113
+ out << haystack.byteslice(cursor, haystack.bytesize - cursor) if cursor < haystack.bytesize
114
+ out
115
+ end
116
+
117
+ def coerce_string(value)
118
+ return value if value.is_a?(String)
119
+ return value.to_str if value.respond_to?(:to_str)
120
+ raise TypeError, "no implicit conversion of #{value.class} into String"
121
+ end
122
+
123
+ class MatchData
124
+ include Enumerable
125
+
126
+ def each(&block)
127
+ to_a.each(&block)
128
+ end
129
+
130
+ def values_at(*indices)
131
+ indices.map { |i| self[i] }
132
+ end
133
+
134
+ def ==(other)
135
+ other.is_a?(MatchData) && to_a == other.to_a && string == other.string
136
+ end
137
+ alias_method :eql?, :==
138
+
139
+ def hash
140
+ [to_a, string].hash
141
+ end
142
+ end
143
+ end
144
+ end
metadata ADDED
@@ -0,0 +1,54 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fast_regexp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Eric Jacobs
8
+ - Dmytro Horoshko
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 1980-01-02 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'Ruby bindings to rust/regex with a Fast::Regexp API: MatchData, sub/gsub,
14
+ ===, =~, named captures, and GVL release for thread/fiber-friendly matching.'
15
+ email:
16
+ - eric@ebj.dev
17
+ executables: []
18
+ extensions:
19
+ - ext/fast_regexp/extconf.rb
20
+ extra_rdoc_files: []
21
+ files:
22
+ - LICENSE.txt
23
+ - README.md
24
+ - ext/fast_regexp/Cargo.lock
25
+ - ext/fast_regexp/Cargo.toml
26
+ - ext/fast_regexp/extconf.rb
27
+ - ext/fast_regexp/src/lib.rs
28
+ - lib/fast_regexp.rb
29
+ - lib/fast_regexp/version.rb
30
+ homepage: https://github.com/jetpks/fast_regexp
31
+ licenses:
32
+ - MIT
33
+ metadata:
34
+ bug_tracker_uri: https://github.com/jetpks/fast_regexp/issues
35
+ homepage_uri: https://github.com/jetpks/fast_regexp
36
+ source_code_uri: https://github.com/jetpks/fast_regexp
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 3.1.0
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 4.0.10
52
+ specification_version: 4
53
+ summary: Fast regex for Ruby, backed by rust/regex
54
+ test_files: []