From a2b9ac0253247c9acef27a85df3f16b54b7103d9 Mon Sep 17 00:00:00 2001 From: Sebastian Walz Date: Fri, 20 Nov 2026 18:50:13 +0100 Subject: [PATCH] feat(scheme): simplify using niche optimisation Signed-off-by: Sebastian Walz --- src/uri/mod.rs | 79 ++------- src/uri/scheme.rs | 423 ++++++++++++++++++++++------------------------ 2 files changed, 224 insertions(+), 278 deletions(-) diff --git a/src/uri/mod.rs b/src/uri/mod.rs index 0f0b0156..66e0f293 100644 --- a/src/uri/mod.rs +++ b/src/uri/mod.rs @@ -32,8 +32,6 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::str::{self, FromStr}; -use self::scheme::Scheme2; - pub use self::authority::Authority; pub use self::builder::Builder; pub use self::path::PathAndQuery; @@ -94,7 +92,7 @@ mod tests; /// ``` #[derive(Clone)] pub struct Uri { - scheme: Scheme, + scheme: Option, authority: Authority, path_and_query: PathAndQuery, } @@ -250,13 +248,6 @@ impl Uri { return Err(ErrorKind::SchemeMissing.into()); } - let scheme = match src.scheme { - Some(scheme) => scheme, - None => Scheme { - inner: Scheme2::None, - }, - }; - let authority = match src.authority { Some(authority) => authority, None => Authority::empty(), @@ -268,7 +259,7 @@ impl Uri { }; Ok(Uri { - scheme, + scheme: src.scheme, authority, path_and_query, }) @@ -304,24 +295,22 @@ impl Uri { 1 => match s[0] { b'/' => { return Ok(Uri { - scheme: Scheme::empty(), + scheme: None, authority: Authority::empty(), path_and_query: PathAndQuery::slash(), }); } b'*' => { return Ok(Uri { - scheme: Scheme::empty(), + scheme: None, authority: Authority::empty(), path_and_query: PathAndQuery::star(), }); } _ => { - let authority = Authority::from_shared(s)?; - return Ok(Uri { - scheme: Scheme::empty(), - authority, + scheme: None, + authority: Authority::from_shared(s)?, path_and_query: PathAndQuery::empty(), }); } @@ -331,7 +320,7 @@ impl Uri { if s[0] == b'/' { return Ok(Uri { - scheme: Scheme::empty(), + scheme: None, authority: Authority::empty(), path_and_query: PathAndQuery::from_shared(s)?, }); @@ -394,7 +383,7 @@ impl Uri { /// Returns the path & query components of the Uri #[inline] pub fn path_and_query(&self) -> Option<&PathAndQuery> { - if !self.scheme.inner.is_none() || self.authority.data.is_empty() { + if !self.scheme.is_none() || self.authority.data.is_empty() { Some(&self.path_and_query) } else { None @@ -481,11 +470,7 @@ impl Uri { /// ``` #[inline] pub fn scheme(&self) -> Option<&Scheme> { - if self.scheme.inner.is_none() { - None - } else { - Some(&self.scheme) - } + self.scheme.as_ref() } /// Get the scheme of this `Uri` as a `&str`. @@ -500,11 +485,7 @@ impl Uri { /// ``` #[inline] pub fn scheme_str(&self) -> Option<&str> { - if self.scheme.inner.is_none() { - None - } else { - Some(self.scheme.as_str()) - } + self.scheme().map(Scheme::as_str) } /// Get the authority of this `Uri`. @@ -702,7 +683,7 @@ impl Uri { } fn has_path(&self) -> bool { - !self.path_and_query.data.is_empty() || !self.scheme.inner.is_none() + !self.path_and_query.data.is_empty() || self.scheme.is_some() } } @@ -773,7 +754,7 @@ impl TryFrom<&Uri> for Uri { impl From for Uri { fn from(authority: Authority) -> Self { Self { - scheme: Scheme::empty(), + scheme: None, authority, path_and_query: PathAndQuery::empty(), } @@ -784,7 +765,7 @@ impl From for Uri { impl From for Uri { fn from(path_and_query: PathAndQuery) -> Self { Self { - scheme: Scheme::empty(), + scheme: None, authority: Authority::empty(), path_and_query, } @@ -800,11 +781,6 @@ impl From for Parts { None }; - let scheme = match src.scheme.inner { - Scheme2::None => None, - _ => Some(src.scheme), - }; - let authority = if src.authority.data.is_empty() { None } else { @@ -812,7 +788,7 @@ impl From for Parts { }; Parts { - scheme, + scheme: src.scheme, authority, path_and_query, _priv: (), @@ -822,26 +798,7 @@ impl From for Parts { fn parse_full(mut s: Bytes) -> Result { // Parse the scheme - let scheme = match Scheme2::parse(&s[..])? { - Scheme2::None => Scheme2::None, - Scheme2::Standard(p) => { - // TODO: use truncate - let _ = s.split_to(p.len() + 3); - Scheme2::Standard(p) - } - Scheme2::Other(n) => { - // Grab the protocol - let mut scheme = s.split_to(n + 3); - - // Strip ://, TODO: truncate - let _ = scheme.split_off(n); - - // Allocate the ByteStr - let val = unsafe { ByteStr::from_utf8_unchecked(scheme) }; - - Scheme2::Other(Box::new(val)) - } - }; + let scheme = Scheme::parse(&mut s)?; // Find the end of the authority. The scheme will already have been // extracted. @@ -857,7 +814,7 @@ fn parse_full(mut s: Bytes) -> Result { }; return Ok(Uri { - scheme: scheme.into(), + scheme, authority, path_and_query: PathAndQuery::empty(), }); @@ -1022,7 +979,7 @@ impl Default for Uri { #[inline] fn default() -> Uri { Uri { - scheme: Scheme::empty(), + scheme: None, authority: Authority::empty(), path_and_query: PathAndQuery::slash(), } @@ -1117,7 +1074,7 @@ impl Hash for Uri { where H: Hasher, { - if !self.scheme.inner.is_none() { + if self.scheme.is_some() { self.scheme.hash(state); state.write_u8(0xff); } diff --git a/src/uri/scheme.rs b/src/uri/scheme.rs index 0cfe3166..c1909a19 100644 --- a/src/uri/scheme.rs +++ b/src/uri/scheme.rs @@ -9,40 +9,15 @@ use super::{ErrorKind, InvalidUri}; use crate::byte_str::ByteStr; /// Represents the scheme component of a URI -#[derive(Clone)] -pub struct Scheme { - pub(super) inner: Scheme2, -} - -#[derive(Clone, Debug)] -pub(super) enum Scheme2> { - None, - Standard(Protocol), - Other(T), -} - -#[derive(Copy, Clone, Debug)] -pub(super) enum Protocol { - Http, - Https, -} +#[derive(Clone, Debug, Hash, Eq, PartialEq)] +pub struct Scheme(SchemeInner); impl Scheme { /// HTTP protocol scheme - pub const HTTP: Scheme = Scheme { - inner: Scheme2::Standard(Protocol::Http), - }; + pub const HTTP: Scheme = Self(SchemeInner::Http); /// HTTP protocol over TLS. - pub const HTTPS: Scheme = Scheme { - inner: Scheme2::Standard(Protocol::Https), - }; - - pub(super) fn empty() -> Self { - Scheme { - inner: Scheme2::None, - } - } + pub const HTTPS: Scheme = Self(SchemeInner::Https); /// Return a str representation of the scheme /// @@ -55,92 +30,76 @@ impl Scheme { /// ``` #[inline] pub fn as_str(&self) -> &str { - use self::Protocol::*; - use self::Scheme2::*; - - match self.inner { - Standard(Http) => "http", - Standard(Https) => "https", - Other(ref v) => &v[..], - None => unreachable!(), - } + self.0.as_str() } -} -impl TryFrom<&[u8]> for Scheme { - type Error = InvalidUri; - #[inline] - fn try_from(s: &[u8]) -> Result { - use self::Scheme2::*; + pub(super) fn parse(bytes: &mut Bytes) -> Result, InvalidUri> { + let maybe_scheme = SchemeInner::parse(&bytes[..])? + .map(|scheme| match scheme { + SchemeInner::Http => { + // TODO: use truncate + let _ = bytes.split_to(7); + Self::HTTP + } + SchemeInner::Https => { + // TODO: use truncate + let _ = bytes.split_to(8); + Self::HTTPS + } + SchemeInner::Other(n) => { + // Grab the protocol + let mut scheme = bytes.split_to(n + 3); - match Scheme2::parse_exact(s)? { - None => Err(ErrorKind::InvalidScheme.into()), - Standard(p) => Ok(Standard(p).into()), - Other(_) => { - let bytes = Bytes::copy_from_slice(s); + // Strip ://, TODO: truncate + let _ = scheme.split_off(n); - // Safety: postcondition on parse_exact() means that s and - // hence bytes are valid UTF-8. - let string = unsafe { ByteStr::from_utf8_unchecked(bytes) }; + // Allocate the ByteStr + let val = unsafe { ByteStr::from_utf8_unchecked(scheme) }; - Ok(Other(Box::new(string)).into()) - } - } + Self(SchemeInner::Other(Box::new(val))) + } + }); + Ok(maybe_scheme) } } -impl TryFrom<&str> for Scheme { - type Error = InvalidUri; +impl AsRef for Scheme { #[inline] - fn try_from(s: &str) -> Result { - TryFrom::try_from(s.as_bytes()) - } -} - -impl FromStr for Scheme { - type Err = InvalidUri; - - fn from_str(s: &str) -> Result { - TryFrom::try_from(s) + fn as_ref(&self) -> &str { + self.as_str() } } -impl fmt::Debug for Scheme { +impl fmt::Display for Scheme { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Debug::fmt(self.as_str(), f) + self.0.fmt(f) } } -impl fmt::Display for Scheme { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) +impl FromStr for Scheme { + type Err = InvalidUri; + + fn from_str(s: &str) -> Result { + s.try_into() } } -impl AsRef for Scheme { +impl TryFrom<&[u8]> for Scheme { + type Error = InvalidUri; #[inline] - fn as_ref(&self) -> &str { - self.as_str() + fn try_from(s: &[u8]) -> Result { + s.try_into().map(Self) } } -impl PartialEq for Scheme { - fn eq(&self, other: &Scheme) -> bool { - use self::Protocol::*; - use self::Scheme2::*; - - match (&self.inner, &other.inner) { - (&Standard(Http), &Standard(Http)) => true, - (&Standard(Https), &Standard(Https)) => true, - (Other(a), Other(b)) => a.eq_ignore_ascii_case(b), - (&None, _) | (_, &None) => unreachable!(), - _ => false, - } +impl TryFrom<&str> for Scheme { + type Error = InvalidUri; + #[inline] + fn try_from(s: &str) -> Result { + s.try_into().map(Self) } } -impl Eq for Scheme {} - /// Case-insensitive equality /// /// # Examples @@ -163,127 +122,80 @@ impl PartialEq for str { } } -/// Case-insensitive hashing -impl Hash for Scheme { - fn hash(&self, state: &mut H) - where - H: Hasher, - { - match self.inner { - Scheme2::None => (), - Scheme2::Standard(Protocol::Http) => state.write_u8(1), - Scheme2::Standard(Protocol::Https) => state.write_u8(2), - Scheme2::Other(ref other) => { - other.len().hash(state); - for &b in other.as_bytes() { - state.write_u8(b.to_ascii_lowercase()); - } - } - } - } -} - -impl Scheme2 { - pub(super) fn is_none(&self) -> bool { - matches!(*self, Scheme2::None) - } +#[derive(Clone)] +enum SchemeInner> { + Http, + Https, + Other(T), } -// Require the scheme to not be too long in order to enable further -// optimizations later. -const MAX_SCHEME_LEN: usize = 64; - -// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) -// -// SCHEME_CHARS is a table of valid characters in the scheme part of a URI. An -// entry in the table is 0 for invalid characters. For valid characters the -// entry is itself (i.e. the entry for 43 is b'+' because b'+' == 43u8). An -// important characteristic of this table is that all entries above 127 are -// invalid. This makes all of the valid entries a valid single-byte UTF-8 code -// point. This means that a slice of such valid entries is valid UTF-8. -#[rustfmt::skip] -const SCHEME_CHARS: [u8; 256] = [ - // 0 1 2 3 4 5 6 7 8 9 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3x - 0, 0, 0, b'+', 0, b'-', b'.', 0, b'0', b'1', // 4x - b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', 0, // 5x - 0, 0, 0, 0, 0, b'A', b'B', b'C', b'D', b'E', // 6x - b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', // 7x - b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', // 8x - b'Z', 0, 0, 0, 0, 0, 0, b'a', b'b', b'c', // 9x - b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', // 10x - b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', // 11x - b'x', b'y', b'z', 0, 0, 0, b'~', 0, 0, 0, // 12x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 13x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 14x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 15x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 17x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 18x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 19x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 21x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 22x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 23x - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 24x - 0, 0, 0, 0, 0, 0 // 25x -]; - -impl Scheme2 { - // Postcondition: On all Ok() returns, s is valid UTF-8 - fn parse_exact(s: &[u8]) -> Result, InvalidUri> { - match s { - _ if s.eq_ignore_ascii_case(b"http") => Ok(Protocol::Http.into()), - _ if s.eq_ignore_ascii_case(b"https") => Ok(Protocol::Https.into()), - _ => { - if s.len() > MAX_SCHEME_LEN { - return Err(ErrorKind::SchemeTooLong.into()); - } - - // check that each byte in s is a SCHEME_CHARS which implies - // that it is a valid single byte UTF-8 code point. - for &b in s { - match SCHEME_CHARS[b as usize] { - b':' => { - // Don't want :// here - return Err(ErrorKind::InvalidScheme.into()); - } - 0 => { - return Err(ErrorKind::InvalidScheme.into()); - } - _ => {} - } - } - - Ok(Scheme2::Other(())) - } +impl SchemeInner { + fn as_str(&self) -> &str { + match self { + Self::Http => "http", + Self::Https => "https", + Self::Other(ref v) => &v[..], } } +} - pub(super) fn parse(s: &[u8]) -> Result, InvalidUri> { - if s.len() >= 7 { - // Check for HTTP - if s[..7].eq_ignore_ascii_case(b"http://") { - // Prefix will be striped - return Ok(Protocol::Http.into()); - } - } - - if s.len() >= 8 { - // Check for HTTPs - if s[..8].eq_ignore_ascii_case(b"https://") { - return Ok(Protocol::Https.into()); - } - } - - if s.len() > 3 { +impl SchemeInner { + // Require the scheme to not be too long in order to enable further + // optimizations later. + const MAX_SCHEME_LEN: usize = 64; + + // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + // + // SCHEME_CHARS is a table of valid characters in the scheme part of a URI. An + // entry in the table is 0 for invalid characters. For valid characters the + // entry is itself (i.e. the entry for 43 is b'+' because b'+' == 43u8). An + // important characteristic of this table is that all entries above 127 are + // invalid. This makes all of the valid entries a valid single-byte UTF-8 code + // point. This means that a slice of such valid entries is valid UTF-8. + #[rustfmt::skip] + const SCHEME_CHARS: [u8; 256] = [ + // 0 1 2 3 4 5 6 7 8 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3x + 0, 0, 0, b'+', 0, b'-', b'.', 0, b'0', b'1', // 4x + b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', 0, // 5x + 0, 0, 0, 0, 0, b'A', b'B', b'C', b'D', b'E', // 6x + b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', // 7x + b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', // 8x + b'Z', 0, 0, 0, 0, 0, 0, b'a', b'b', b'c', // 9x + b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', // 10x + b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', // 11x + b'x', b'y', b'z', 0, 0, 0, b'~', 0, 0, 0, // 12x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 13x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 14x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 15x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 17x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 18x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 19x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 21x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 22x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 23x + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 24x + 0, 0, 0, 0, 0, 0 // 25x + ]; + + fn parse(s: &[u8]) -> Result>, InvalidUri> { + if s.len() <= 3 { + // Too short for any non-empty scheme before `://`: + Ok(None) + } else if s.len() >= 7 && s[..7].eq_ignore_ascii_case(b"http://") { + Ok(Some(SchemeInner::Http)) + } else if s.len() >= 8 && s[..8].eq_ignore_ascii_case(b"https://") { + Ok(Some(SchemeInner::Https)) + } else { for i in 0..s.len() { let b = s[i]; - match SCHEME_CHARS[b as usize] { + match Self::SCHEME_CHARS[b as usize] { b':' => { // Not enough data remaining if s.len() < i + 3 { @@ -295,43 +207,120 @@ impl Scheme2 { break; } - if i > MAX_SCHEME_LEN { + if i > Self::MAX_SCHEME_LEN { return Err(ErrorKind::SchemeTooLong.into()); } // Return scheme - return Ok(Scheme2::Other(i)); + return Ok(Some(SchemeInner::Other(i))); } // Invalid scheme character, abort 0 => break, _ => {} } } + Ok(None) } + } + + // Postcondition: On all Ok() returns, s is valid UTF-8 + fn parse_exact(s: &[u8]) -> Result, InvalidUri> { + if s.eq_ignore_ascii_case(b"http") { + Ok(SchemeInner::Http) + } else if s.eq_ignore_ascii_case(b"https") { + Ok(SchemeInner::Https) + } else if s.len() <= Self::MAX_SCHEME_LEN { + // check that each byte in s is a SCHEME_CHARS which implies + // that it is a valid single byte UTF-8 code point. + for &b in s { + match Self::SCHEME_CHARS[b as usize] { + b':' => { + // Don't want :// here + return Err(ErrorKind::InvalidScheme.into()); + } + 0 => { + return Err(ErrorKind::InvalidScheme.into()); + } + _ => {} + } + } - Ok(Scheme2::None) + Ok(SchemeInner::Other(())) + } else { + Err(ErrorKind::SchemeTooLong.into()) + } } } -impl Protocol { - pub(super) fn len(&self) -> usize { - match *self { - Protocol::Http => 4, - Protocol::Https => 5, +impl fmt::Debug for SchemeInner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self.as_str(), f) + } +} + +impl fmt::Display for SchemeInner { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl Eq for SchemeInner { } + +/// Case-insensitive hashing +impl Hash for SchemeInner { + fn hash(&self, state: &mut H) + where + H: Hasher, + { + match self { + Self::Http => state.write_u8(1), + Self::Https => state.write_u8(2), + Self::Other(ref other) => { + other.len().hash(state); + for &b in other.as_bytes() { + state.write_u8(b.to_ascii_lowercase()); + } + } } } } -impl From for Scheme2 { - fn from(src: Protocol) -> Self { - Scheme2::Standard(src) +impl PartialEq for SchemeInner { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Http, Self::Http) + | (Self::Https, Self::Https) => true, + (Self::Other(a), Self::Other(b)) => a.eq_ignore_ascii_case(b), + _ => false, + } + } +} + +impl TryFrom<&[u8]> for SchemeInner { + type Error = InvalidUri; + #[inline] + fn try_from(s: &[u8]) -> Result { + Ok(match SchemeInner::parse_exact(s)? { + SchemeInner::Http => Self::Http, + SchemeInner::Https => Self::Https, + SchemeInner::Other(()) => { + let bytes = Bytes::copy_from_slice(s); + + // Safety: postcondition on parse_exact() means that s and + // hence bytes are valid UTF-8. + let string = unsafe { ByteStr::from_utf8_unchecked(bytes) }; + + Self::Other(Box::new(string)) + } + }) } } -#[doc(hidden)] -impl From for Scheme { - fn from(src: Scheme2) -> Self { - Scheme { inner: src } +impl TryFrom<&str> for SchemeInner { + type Error = InvalidUri; + #[inline] + fn try_from(s: &str) -> Result { + s.as_bytes().try_into() } }