Skip to main content

css_escape/
lib.rs

1//! # css-escape — escape a string as a CSS identifier
2//!
3//! A faithful implementation of the CSSOM
4//! [`CSS.escape()`](https://drafts.csswg.org/cssom/#the-css.escape()-method) algorithm
5//! (the same one behind the [`css.escape`](https://www.npmjs.com/package/css.escape)
6//! npm package): turn an arbitrary string into something safe to use as a CSS
7//! identifier, for example when building a selector from user input. Zero
8//! dependencies and `#![no_std]`.
9//!
10//! ```
11//! use css_escape::escape;
12//!
13//! // Safely target an element by id, whatever the id contains.
14//! assert_eq!(format!("#{}", escape("a b#c")), "#a\\ b\\#c");
15//! assert_eq!(escape("0first"), "\\30 first"); // a leading digit is escaped
16//! assert_eq!(escape("café"), "café");          // non-ASCII passes through
17//! ```
18//!
19//! This escapes *identifiers* (selectors, class/id names). Serializing a quoted CSS
20//! string value is a different operation — it must also escape newlines and control
21//! characters — and is out of scope.
22
23#![no_std]
24#![doc(html_root_url = "https://docs.rs/css-escape/0.1.0")]
25
26// Compile-test the README's examples as part of `cargo test`.
27#[cfg(doctest)]
28#[doc = include_str!("../README.md")]
29struct ReadmeDoctests;
30
31extern crate alloc;
32
33use alloc::string::String;
34use alloc::vec::Vec;
35use core::fmt::Write;
36
37/// Escape `value` for use as a CSS identifier, per the CSSOM `CSS.escape()` algorithm.
38///
39/// ```
40/// assert_eq!(css_escape::escape(".foo#bar"), "\\.foo\\#bar");
41/// ```
42#[must_use]
43pub fn escape(value: &str) -> String {
44    let chars: Vec<char> = value.chars().collect();
45    let len = chars.len();
46    let first = chars.first().copied();
47    let mut out = String::with_capacity(value.len());
48
49    for (i, &c) in chars.iter().enumerate() {
50        match c {
51            // U+0000 NULL → U+FFFD REPLACEMENT CHARACTER.
52            '\0' => out.push('\u{fffd}'),
53            // C0 controls (except NUL) and U+007F DELETE → `\<hex> `.
54            '\u{1}'..='\u{1f}' | '\u{7f}' => push_hex(&mut out, c),
55            // A leading digit must be escaped.
56            '0'..='9' if i == 0 => push_hex(&mut out, c),
57            // A digit right after a leading `-` must be escaped.
58            '0'..='9' if i == 1 && first == Some('-') => push_hex(&mut out, c),
59            // A `-` that is the entire identifier must be escaped.
60            '-' if i == 0 && len == 1 => out.push_str("\\-"),
61            // Safe: U+0080+, `-`, `_`, and ASCII alphanumerics pass through.
62            c if c >= '\u{80}' || c == '-' || c == '_' || c.is_ascii_alphanumeric() => out.push(c),
63            // Anything else is escaped with a backslash.
64            c => {
65                out.push('\\');
66                out.push(c);
67            }
68        }
69    }
70    out
71}
72
73/// Append `\<lowercase-hex> ` (backslash, code point in hex, trailing space) to `out`.
74fn push_hex(out: &mut String, c: char) {
75    // Writing to a `String` is infallible.
76    let _ = write!(out, "\\{:x} ", c as u32);
77}