From 4b9f1e699f3c845c0c36d980417cddde9eb5733e Mon Sep 17 00:00:00 2001 From: David Sherret Date: Thu, 13 Feb 2025 13:43:14 +0100 Subject: [PATCH] perf: make parse_scheme slightly faster (#1025) * perf: make parse_scheme slightly faster * add comment and unit test * move to one line --- url/src/parser.rs | 8 ++++---- url/tests/unit.rs | 8 ++++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/url/src/parser.rs b/url/src/parser.rs index 1ab0dc1d..ae506189 100644 --- a/url/src/parser.rs +++ b/url/src/parser.rs @@ -398,15 +398,15 @@ impl<'a> Parser<'a> { } pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result, ()> { - if input.is_empty() || !input.starts_with(ascii_alpha) { + // starts_with will also fail for empty strings so we can skip that comparison for perf + if !input.starts_with(ascii_alpha) { return Err(()); } debug_assert!(self.serialization.is_empty()); while let Some(c) = input.next() { match c { - 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.' => { - self.serialization.push(c.to_ascii_lowercase()) - } + 'a'..='z' | '0'..='9' | '+' | '-' | '.' => self.serialization.push(c), + 'A'..='Z' => self.serialization.push(c.to_ascii_lowercase()), ':' => return Ok(input), _ => { self.serialization.clear(); diff --git a/url/tests/unit.rs b/url/tests/unit.rs index b3596610..6a9430bd 100644 --- a/url/tests/unit.rs +++ b/url/tests/unit.rs @@ -1031,6 +1031,14 @@ fn test_set_scheme_to_file_with_host() { assert_eq!(result, Err(())); } +#[test] +fn test_set_scheme_empty_err() { + let mut url: Url = "http://localhost:6767/foo/bar".parse().unwrap(); + let result = url.set_scheme(""); + assert_eq!(url.to_string(), "http://localhost:6767/foo/bar"); + assert_eq!(result, Err(())); +} + #[test] fn no_panic() { let mut url = Url::parse("arhttpsps:/.//eom/dae.com/\\\\t\\:").unwrap();