From 201dc0df3b6e7993ebc0ced4f1071c04f8033db1 Mon Sep 17 00:00:00 2001 From: Jacob Rothstein Date: Thu, 1 Feb 2024 12:06:07 -0800 Subject: [PATCH] feat: make memchr optional --- Cargo.toml | 6 +++++- src/route_spec.rs | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b30cdfa..14dd03a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/route_spec.rs b/src/route_spec.rs index dea8f7a..031973a 100644 --- a/src/route_spec.rs +++ b/src/route_spec.rs @@ -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 @@ -156,7 +164,15 @@ impl FromStr for RouteSpec { fn from_str(source: &str) -> Result { 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 {