Skip to content

Commit

Permalink
serializer: Fix handling of backslashes and Unicode escape sequences …
Browse files Browse the repository at this point in the history
…in CSS content
  • Loading branch information
liulinboyi committed Feb 10, 2025
1 parent fa6f5eb commit 7d06d94
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,35 @@ where
}
}

fn handle_backslash(s: &str, i: usize) -> Option<&'static str> {
if i + 1 < s.len() {
match s.as_bytes()[i + 1] {
b'0'..=b'9' | b'a'..=b'f' | b'A'..=b'F' => {
// If the character following the backslash is part of a Unicode escape sequence, preserve the entire sequence
let mut j = i + 1;
while j < s.len() && s.as_bytes()[j].is_ascii_hexdigit() && j - i < 6 {
j += 1;
}
if j - i > 1 {
// Preserve the entire Unicode escape sequence
Some("\\")
} else {
// If it is not a valid Unicode escape sequence, escape the backslash itself
Some("\\\\")
}
}
_ => {
// If the character following the backslash is any other character, escape the backslash itself
Some("\\\\")
}
}
} else {
// If the backslash is the last character, escape the backslash itself
Some("\\\\")
}
}


impl<W> fmt::Write for CssStringWriter<'_, W>
where
W: fmt::Write,
Expand All @@ -320,7 +349,7 @@ where
for (i, b) in s.bytes().enumerate() {
let escaped = match_byte! { b,
b'"' => Some("\\\""),
b'\\' => Some("\\\\"),
b'\\' => handle_backslash(s, i),
b'\0' => Some("\u{FFFD}"),
b'\x01'..=b'\x1F' | b'\x7F' => None,
_ => continue,
Expand Down

0 comments on commit 7d06d94

Please sign in to comment.