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

use memchr #27

Merged
merged 2 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ license = "MIT OR Apache-2.0"
keywords = ["router"]
categories = ["web-programming::http-server", "web-programming"]

[features]
default = []
memchr = ["dep:memchr"]

[dependencies]
memchr = { version = "2.6.4", optional = true }
smartcow = "0.2.1"
smartstring = "1.0.1"

Expand Down
23 changes: 20 additions & 3 deletions src/route_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,23 @@ impl RouteSpec {
}
match peek.peek() {
None | Some(Segment::Slash) => {
#[cfg(feature = "memchr")]
let capture = memchr::memchr(b'/', path.as_bytes())
.map(|index| &path[..index])
.unwrap_or(path);
#[cfg(not(feature = "memchr"))]
let capture = path.split('/').next()?;

captures.push(capture);
&path[capture.len()..]
}

Some(Segment::Dot) => {
#[cfg(feature = "memchr")]
let index = memchr::memchr2(b'.', b'/', path.as_bytes())?;
#[cfg(not(feature = "memchr"))]
let index = path.find(|c| c == '.' || c == '/')?;

if path.chars().nth(index) == Some('.') {
captures.push(&path[..index]);
&path[index..] // we leave the dot so it can be matched by the Segment::Dot
Expand Down Expand Up @@ -154,10 +164,17 @@ impl FromStr for RouteSpec {
fn from_str(source: &str) -> Result<Self, Self::Err> {
let mut last_index = 0;
let source_trimmed = source.trim_start_matches('/').trim_end_matches('/');
let segments = source_trimmed
#[cfg(feature = "memchr")]
let index_iter = memchr::memchr2_iter(b'.', b'/', source_trimmed.as_bytes());

#[cfg(not(feature = "memchr"))]
let index_iter = source_trimmed
.match_indices(|c| c == '.' || c == '/')
.chain(iter::once_with(|| (source_trimmed.len(), "/")))
.try_fold(vec![], |mut acc, (index, _c)| {
.map(|(i, _)| i);

let segments = index_iter
.chain(iter::once_with(|| source_trimmed.len()))
.try_fold(vec![], |mut acc, index| {
let first_char = if last_index == 0 {
None
} else {
Expand Down
Loading