css-escape 0.1.1

Escape a string for use as a CSS identifier — the CSSOM CSS.escape() algorithm. Zero dependencies, no_std.
Documentation
//! # css-escape — escape a string as a CSS identifier
//!
//! A faithful implementation of the CSSOM
//! [`CSS.escape()`](https://drafts.csswg.org/cssom/#the-css.escape()-method) algorithm
//! (the same one behind the [`css.escape`](https://www.npmjs.com/package/css.escape)
//! npm package): turn an arbitrary string into something safe to use as a CSS
//! identifier, for example when building a selector from user input. Zero
//! dependencies and `#![no_std]`.
//!
//! ```
//! use css_escape::escape;
//!
//! // Safely target an element by id, whatever the id contains.
//! assert_eq!(format!("#{}", escape("a b#c")), "#a\\ b\\#c");
//! assert_eq!(escape("0first"), "\\30 first"); // a leading digit is escaped
//! assert_eq!(escape("café"), "café");          // non-ASCII passes through
//! ```
//!
//! This escapes *identifiers* (selectors, class/id names). Serializing a quoted CSS
//! string value is a different operation — it must also escape newlines and control
//! characters — and is out of scope.

#![no_std]
#![doc(html_root_url = "https://docs.rs/css-escape/0.1.0")]

// Compile-test the README's examples as part of `cargo test`.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt::Write;

/// Escape `value` for use as a CSS identifier, per the CSSOM `CSS.escape()` algorithm.
///
/// ```
/// assert_eq!(css_escape::escape(".foo#bar"), "\\.foo\\#bar");
/// ```
#[must_use]
pub fn escape(value: &str) -> String {
    let chars: Vec<char> = value.chars().collect();
    let len = chars.len();
    let first = chars.first().copied();
    let mut out = String::with_capacity(value.len());

    for (i, &c) in chars.iter().enumerate() {
        match c {
            // U+0000 NULL → U+FFFD REPLACEMENT CHARACTER.
            '\0' => out.push('\u{fffd}'),
            // C0 controls (except NUL) and U+007F DELETE → `\<hex> `.
            '\u{1}'..='\u{1f}' | '\u{7f}' => push_hex(&mut out, c),
            // A leading digit must be escaped.
            '0'..='9' if i == 0 => push_hex(&mut out, c),
            // A digit right after a leading `-` must be escaped.
            '0'..='9' if i == 1 && first == Some('-') => push_hex(&mut out, c),
            // A `-` that is the entire identifier must be escaped.
            '-' if i == 0 && len == 1 => out.push_str("\\-"),
            // Safe: U+0080+, `-`, `_`, and ASCII alphanumerics pass through.
            c if c >= '\u{80}' || c == '-' || c == '_' || c.is_ascii_alphanumeric() => out.push(c),
            // Anything else is escaped with a backslash.
            c => {
                out.push('\\');
                out.push(c);
            }
        }
    }
    out
}

/// Append `\<lowercase-hex> ` (backslash, code point in hex, trailing space) to `out`.
fn push_hex(out: &mut String, c: char) {
    // Writing to a `String` is infallible.
    let _ = write!(out, "\\{:x} ", c as u32);
}