Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
perf(core): add early exits for `lex_url`, `lex_email_address` (#2910)
Steve Kurch99410a0ecaf6
diff --git a/harper-core/src/lexing/email_address.rs b/harper-core/src/lexing/email_address.rsindex 5a4119f70..d712c3ab9 100644--- a/harper-core/src/lexing/email_address.rs+++ b/harper-core/src/lexing/email_address.rs@@ -4,9 +4,28 @@ use super::FoundToken;use super::hostname::lex_hostname;use crate::TokenKind;+/// The maximum length of an email address, in characters.+pub(crate) const MAX_EMAIL_LEN: usize = 254;+pub fn lex_email_address(source: &[char]) -> Option<FoundToken> {+ let source = &source[..usize::min(source.len(), MAX_EMAIL_LEN)];+// Location of the @ sign- let (at_loc, _) = source.iter().enumerate().rev().find(|(_, c)| **c == '@')?;+ let at_loc = {+ let mut iter = source.iter().enumerate();+ // Assuming we don't start lexing in the middle of a local-part, i.e. we start unquoted.+ let mut in_quote = false;+ // Loop until we find an acceptable '@' or a reason to early-exit.+ loop {+ match iter.next()? {+ (_, '"') => in_quote = !in_quote,+ // Unquoted space; can't be a valid local-part.+ (_, ' ') if !in_quote => return None,+ (i, '@') if !in_quote => break i,+ _ => {}+ }+ }+ };let local_part = &source[0..at_loc];diff --git a/harper-core/src/lexing/url.rs b/harper-core/src/lexing/url.rsindex 9e7135314..4fce8cf34 100644--- a/harper-core/src/lexing/url.rs+++ b/harper-core/src/lexing/url.rs@@ -4,11 +4,19 @@ use super::{FoundToken, hostname::lex_hostname};use crate::TokenKind;pub fn lex_url(source: &[char]) -> Option<FoundToken> {- let sep = source.iter().position(|c| *c == ':')?;-- if !validate_scheme(&source[0..sep]) {- return None;- }+ let sep = {+ let mut iter = source.iter().enumerate();+ loop {+ match iter.next()? {+ // Must begin with an alphabetic character.+ (0, c) if !c.is_ascii_alphabetic() => return None,+ // This check must happen before the `valid_scheme_char` check.+ (i, ':') => break i,+ (_, c) if !valid_scheme_char(*c) => return None,+ _ => {}+ }+ }+ };let url_end = lex_ip_schemepart(&source[sep + 1..])?;@@ -18,11 +26,6 @@ pub fn lex_url(source: &[char]) -> Option<FoundToken> {})}-/// Checks whether a given char string is a valid "scheme" part of a URI.-fn validate_scheme(source: &[char]) -> bool {- source.iter().all(|c: &char| valid_scheme_char(*c))-}-fn lex_ip_schemepart(source: &[char]) -> Option<usize> {if !matches!(source, ['/', '/', ..]) {return None;