Skip to content

Commit dbbc4af

Browse files
committed
Make trim_end_unescaped more readable
1 parent 26e8886 commit dbbc4af

1 file changed

Lines changed: 8 additions & 30 deletions

File tree

lrlex/src/lib/parser.rs

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -686,39 +686,17 @@ where
686686
}
687687

688688
fn trim_end_unescaped(s: &str) -> &str {
689-
let mut cbuf = [0; 4];
690-
let mut total_ws_bytes = 0;
691-
let mut last_ws_char_len = 0;
692-
// First loop over spaces
693-
for ch in s.chars().rev().into_iter() {
694-
if RE_SPACE_SEP.is_match(ch.encode_utf8(&mut cbuf)) {
695-
last_ws_char_len = ch.len_utf8();
696-
total_ws_bytes += last_ws_char_len;
697-
} else {
698-
break;
699-
}
700-
}
701-
if total_ws_bytes == 0 {
689+
let trimmed = s.trim_end_matches(matches_whitespace);
690+
if trimmed.len() == s.len() {
702691
return s;
703692
}
704-
let mut preceeding_backslashes = 0;
705-
// Next loop over escaped slashes or spaces,
706-
// an even number of backslashes are all escaping slashes,
707-
// and an odd number of backslashes must have a trailing escaped space.
708-
for c in s[..s.len() - total_ws_bytes].chars().rev() {
709-
if c == '\\' {
710-
preceeding_backslashes += 1
711-
} else {
712-
break;
713-
}
693+
// If the number of backslashes is odd then the first space in the trimmed portion is escaped so re-add it.
694+
if trimmed.chars().rev().take_while(|&c| c == '\\').count() % 2 == 1 {
695+
// Panic safety: the trimmed portion is at least one char long.
696+
&s[..trimmed.len() + s[trimmed.len()..].chars().next().unwrap().len_utf8()]
697+
} else {
698+
trimmed
714699
}
715-
// The backslash count was odd, the last must escape a space.
716-
// Drop one of the intial spaces from the trim.
717-
if preceeding_backslashes % 2 == 1 {
718-
total_ws_bytes -= last_ws_char_len;
719-
}
720-
721-
&s[..s.len() - total_ws_bytes]
722700
}
723701

724702
#[cfg(test)]

0 commit comments

Comments
 (0)