Skip to content

Commit

Permalink
feat: make memchr optional
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed Feb 1, 2024
1 parent d6563d7 commit 201dc0d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ license = "MIT OR Apache-2.0"
keywords = ["router"]
categories = ["web-programming::http-server", "web-programming"]

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

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

Expand Down
18 changes: 17 additions & 1 deletion src/route_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +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 @@ -156,7 +164,15 @@ 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 = memchr::memchr2_iter(b'.', b'/', source_trimmed.as_bytes())
#[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 == '/')
.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 {
Expand Down

0 comments on commit 201dc0d

Please sign in to comment.