#![no_std]
#![forbid(unsafe_code)]
#![doc(html_root_url = "https://docs.rs/cssesc/0.1.0")]
#![allow(clippy::format_push_string)]
extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Quotes {
Single,
Double,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Options {
quotes: Option<Quotes>,
wrap: bool,
escape_everything: bool,
is_identifier: bool,
}
impl Options {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn quotes(mut self, quotes: Quotes) -> Self {
self.quotes = Some(quotes);
self
}
#[must_use]
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = wrap;
self
}
#[must_use]
pub fn escape_everything(mut self, value: bool) -> Self {
self.escape_everything = value;
self
}
#[must_use]
pub fn is_identifier(mut self, value: bool) -> Self {
self.is_identifier = value;
self
}
}
#[must_use]
pub fn cssesc(string: &str) -> String {
cssesc_with(string, &Options::new())
}
#[must_use]
pub fn cssesc_with(string: &str, options: &Options) -> String {
let quote = match options.quotes.unwrap_or(Quotes::Single) {
Quotes::Single => '\'',
Quotes::Double => '"',
};
let is_identifier = options.is_identifier;
let first_char = string.chars().next();
let mut output = String::with_capacity(string.len());
for character in string.chars() {
let code_point = u32::from(character);
if !(0x20..=0x7E).contains(&code_point) {
output.push_str(&hex_escape(code_point));
} else if options.escape_everything {
if any_single_escape(code_point) {
output.push('\\');
output.push(character);
} else {
output.push_str(&hex_escape(code_point));
}
} else if character == '\\'
|| (!is_identifier && is_active_quote(character, quote))
|| (is_identifier && single_escape(code_point))
{
output.push('\\');
output.push(character);
} else {
output.push(character);
}
}
if is_identifier {
if starts_with_dash_then_dash_or_digit(&output) {
output = format!("\\-{}", &output['-'.len_utf8()..]);
} else if let Some(first) = first_char.filter(char::is_ascii_digit) {
output = format!("\\3{first} {}", &output[first.len_utf8()..]);
}
}
output = remove_excessive_spaces(&output);
if !is_identifier && options.wrap {
let mut wrapped = String::with_capacity(output.len() + 2);
wrapped.push(quote);
wrapped.push_str(&output);
wrapped.push(quote);
return wrapped;
}
output
}
fn hex_escape(code_point: u32) -> String {
format!("\\{code_point:X} ")
}
fn is_active_quote(character: char, quote: char) -> bool {
(character == '"' && quote == '"') || (character == '\'' && quote == '\'')
}
fn any_single_escape(code_point: u32) -> bool {
matches!(code_point,
0x20..=0x2C | 0x2E | 0x2F | 0x3A..=0x40 | 0x5B..=0x5E | 0x60 | 0x7B..=0x7E)
}
fn single_escape(code_point: u32) -> bool {
matches!(code_point,
0x20..=0x2C | 0x2E | 0x2F | 0x3A..=0x40 | 0x5B | 0x5D | 0x5E | 0x60 | 0x7B..=0x7E)
}
fn starts_with_dash_then_dash_or_digit(output: &str) -> bool {
let mut chars = output.chars();
chars.next() == Some('-') && matches!(chars.next(), Some(c) if c == '-' || c.is_ascii_digit())
}
fn is_upper_hex(byte: u8) -> bool {
byte.is_ascii_digit() || (b'A'..=b'F').contains(&byte)
}
fn is_any_hex(byte: u8) -> bool {
byte.is_ascii_hexdigit()
}
fn remove_excessive_spaces(string: &str) -> String {
let bytes = string.as_bytes();
let n = bytes.len();
let mut out: Vec<u8> = Vec::with_capacity(n);
let mut index = 0;
while index < n {
if bytes[index] == b'\\' {
let mut backslashes = 0;
while index + backslashes < n && bytes[index + backslashes] == b'\\' {
backslashes += 1;
}
let hex_start = index + backslashes;
let mut hex_len = 0;
while hex_len < 6 && hex_start + hex_len < n && is_upper_hex(bytes[hex_start + hex_len])
{
hex_len += 1;
}
let space_at = hex_start + hex_len;
if hex_len >= 1 && space_at < n && bytes[space_at] == b' ' {
let after = space_at + 1;
let lookahead_ok =
after >= n || !(is_any_hex(bytes[after]) || bytes[after] == b' ');
if lookahead_ok {
out.extend_from_slice(&bytes[index..space_at]); if (backslashes - 1) % 2 == 1 {
out.push(b' ');
}
index = after;
continue;
}
}
}
out.push(bytes[index]);
index += 1;
}
String::from_utf8(out).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strings() {
assert_eq!(cssesc("Ladybird"), "Ladybird");
assert_eq!(cssesc("Lady Bird"), "Lady Bird");
assert_eq!(cssesc("café"), "caf\\E9");
assert_eq!(cssesc("\u{1D306}"), "\\1D306");
assert_eq!(cssesc("a\tb"), "a\\9 b"); assert_eq!(cssesc("\0"), "\\0");
assert_eq!(cssesc("a\\b"), "a\\\\b");
}
#[test]
fn quotes_and_wrap() {
assert_eq!(cssesc("'quote'"), "\\'quote\\'");
assert_eq!(
cssesc_with("'quote'", &Options::new().quotes(Quotes::Double)),
"'quote'"
);
assert_eq!(
cssesc_with("\"dq\"", &Options::new().quotes(Quotes::Double)),
"\\\"dq\\\""
);
assert_eq!(cssesc_with("foo", &Options::new().wrap(true)), "'foo'");
}
#[test]
fn escape_everything() {
assert_eq!(
cssesc_with("ab", &Options::new().escape_everything(true)),
"\\61\\62"
);
}
#[test]
fn identifiers() {
let id = Options::new().is_identifier(true);
assert_eq!(cssesc_with("-foo", &id), "-foo");
assert_eq!(cssesc_with("--foo", &id), "\\--foo");
assert_eq!(cssesc_with("-1", &id), "\\-1");
assert_eq!(cssesc_with("1abc", &id), "\\31 abc");
assert_eq!(cssesc_with("0", &id), "\\30");
assert_eq!(cssesc_with("foo.bar", &id), "foo\\.bar");
assert_eq!(cssesc_with("hello world", &id), "hello\\ world");
}
}