Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FindSubstring<&[u8]>: make use of memchr::memmem #1375

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ default = ["std"]
docsrs = []

[dependencies.memchr]
version = "2.3"
version = "2.4"
default-features = false

[dev-dependencies]
Expand Down
30 changes: 1 addition & 29 deletions src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1032,35 +1032,7 @@ pub trait FindSubstring<T> {

impl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {
fn find_substring(&self, substr: &'b [u8]) -> Option<usize> {
if substr.len() > self.len() {
return None;
}

let (&substr_first, substr_rest) = match substr.split_first() {
Some(split) => split,
// an empty substring is found at position 0
// This matches the behavior of str.find("").
None => return Some(0),
};

if substr_rest.is_empty() {
return memchr::memchr(substr_first, self);
}

let mut offset = 0;
let haystack = &self[..self.len() - substr_rest.len()];

while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {
offset += position;
let next_offset = offset + 1;
if &self[next_offset..][..substr_rest.len()] == substr_rest {
return Some(offset);
}

offset = next_offset;
}

None
memchr::memmem::find(&self, substr)
}
}

Expand Down