Skip to content

Commit 10411e3

Browse files
authored
Merge pull request #84 from G-Research/83-find_matches_as_indexes-returns-bogus-values
Handle empty patterns more reasonably
2 parents 7bcfe13 + f86ec64 commit 10411e3

File tree

87 files changed

+96
-32
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+96
-32
lines changed
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
20.5 KB
Binary file not shown.
Binary file not shown.

CHANGELOG.md

+7-1

Cargo.lock

+5-5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "ahocorasick_rs"
3-
version = "0.18.0"
3+
version = "0.19.0"
44
edition = "2021"
55
authors = ["G-Research <[email protected]>", "Itamar Turner-Trauring <[email protected]>"]
66
description = "Search a string for multiple substrings at once"

justfile

+4-1
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ install-dev-dependencies:
1919

2020
setup: venv install-dev-dependencies
2121

22-
test:
22+
lint:
2323
flake8 tests/
2424
black --check tests/
25+
mypy --strict tests
26+
27+
test:
2528
pytest tests/
2629

2730
# Prepare for benchmarking; will only work on Linux:

rust-toolchain.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[toolchain]
2-
channel = "1.72"
2+
channel = "1.72.1"
33
components = ["rustfmt", "clippy"]

src/lib.rs

+39-23
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
use std::sync::{Arc, Mutex};
1+
use std::{sync::{
2+
Arc, Mutex,
3+
}, cell::Cell};
24

35
use aho_corasick::{
46
AhoCorasick, AhoCorasickBuilder, AhoCorasickKind, Match, MatchError, MatchKind,
@@ -14,7 +16,9 @@ use pyo3::{
1416
///
1517
/// Takes three arguments:
1618
///
17-
/// * ``patterns``: A list of strings, the patterns to match against.
19+
/// * ``patterns``: A list of strings, the patterns to match against. Empty
20+
/// patterns are not supported and will result in a ``ValueError`` exception
21+
/// being raised.
1822
/// * ``matchkind``: Defaults to ``"MATCHKING_STANDARD"``.
1923
/// * ``store_patterns``: If ``True``, keep a reference to the patterns, which
2024
/// will speed up ``find_matches_as_strings()`` but will use more memory. If
@@ -177,27 +181,39 @@ impl PyAhoCorasick {
177181
None
178182
};
179183

180-
let result = Ok(Self {
181-
ac_impl: AhoCorasickBuilder::new()
182-
.kind(implementation.map(|i| i.into()))
183-
.match_kind(matchkind.into())
184-
.build(
185-
first_few_patterns
186-
.into_iter()
187-
.chain(patterns_iter)
188-
.chunks(10 * 1024)
189-
.into_iter()
190-
.flat_map(|chunk| {
191-
let result = chunk.filter_map(|s| s.extract::<String>().ok());
192-
// Release the GIL in case some other thread wants to do work:
193-
py.allow_threads(|| ());
194-
result
195-
}),
196-
)
197-
// TODO make sure this error is menaingful to Python users
198-
.map_err(|e| PyValueError::new_err(e.to_string()))?,
199-
patterns,
200-
});
184+
let has_empty_patterns = Cell::new(false);
185+
let ac_impl = AhoCorasickBuilder::new()
186+
.kind(implementation.map(|i| i.into()))
187+
.match_kind(matchkind.into())
188+
.build(
189+
first_few_patterns
190+
.into_iter()
191+
.chain(patterns_iter)
192+
.chunks(10 * 1024)
193+
.into_iter()
194+
.flat_map(|chunk| {
195+
let result =
196+
chunk
197+
.filter_map(|s| s.extract::<String>().ok())
198+
.inspect(|s| {
199+
if s.is_empty() {
200+
has_empty_patterns.set(true);
201+
}
202+
});
203+
// Release the GIL in case some other thread wants to do work:
204+
py.allow_threads(|| ());
205+
result
206+
}),
207+
) // TODO make sure this error is menaingful to Python users
208+
.map_err(|e| PyValueError::new_err(e.to_string()))?;
209+
210+
if has_empty_patterns.get() {
211+
return Err(PyValueError::new_err(
212+
"You passed in an empty string as a pattern",
213+
));
214+
}
215+
216+
let result = Ok(Self { ac_impl, patterns });
201217
if let Ok(mut guard) = patterns_error.lock() {
202218
if let Some(err) = guard.take() {
203219
return Err(err);

tests/test_ac.py

+39
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,45 @@ def test_unicode_extensive(
155155
assert ac.find_matches_as_strings(haystack) == [pattern]
156156

157157

158+
@pytest.mark.parametrize("bad_patterns", [[""], ["", "xx"], ["xx", ""]])
159+
@pytest.mark.parametrize("store_patterns", [True, False])
160+
def test_empty_patterns_are_not_legal(
161+
bad_patterns: list[str], store_patterns: bool
162+
) -> None:
163+
"""
164+
Passing in an empty pattern suggests a bug in user code, and the outputs
165+
are bad when you do have that, so raise an error.
166+
"""
167+
with pytest.raises(ValueError) as e:
168+
AhoCorasick(bad_patterns, store_patterns=store_patterns)
169+
assert "You passed in an empty string as a pattern" in str(e.value)
170+
171+
172+
@given(st.text(min_size=1), st.text(), st.sampled_from([True, False, None]))
173+
def test_unicode_totally_random(
174+
pattern: str, haystack: str, store_patterns: Optional[bool]
175+
) -> None:
176+
"""
177+
Catch more edge cases of patterns and haystacks.
178+
"""
179+
if store_patterns is None:
180+
ac = AhoCorasick([pattern])
181+
else:
182+
ac = AhoCorasick([pattern], store_patterns=store_patterns)
183+
184+
index_matches = ac.find_matches_as_indexes(haystack)
185+
string_matches = ac.find_matches_as_strings(haystack)
186+
187+
expected_index = haystack.find(pattern)
188+
if expected_index == -1:
189+
assert index_matches == []
190+
assert string_matches == []
191+
else:
192+
assert index_matches[0][1] == expected_index
193+
assert [haystack[s:e] for (_, s, e) in index_matches][0] == pattern
194+
assert string_matches[0] == pattern
195+
196+
158197
def test_matchkind() -> None:
159198
"""
160199
Different matchkinds give different results.

0 commit comments

Comments
 (0)