css-escape 0.1.1

Escape a string for use as a CSS identifier — the CSSOM CSS.escape() algorithm. Zero dependencies, no_std.
Documentation
//! End-to-end behavioral spec for `css-escape`.
//!
//! Expected values follow the CSSOM `CSS.escape()` algorithm and are cross-checked
//! against mathiasbynens' `CSS.escape` reference test suite.

use css_escape::escape;

#[test]
fn empty_string() {
    assert_eq!(escape(""), "");
}

#[test]
fn null_becomes_replacement_character() {
    assert_eq!(escape("\u{0}"), "\u{fffd}");
    assert_eq!(escape("a\u{0}b"), "a\u{fffd}b");
    assert_eq!(escape("a\u{0}b\u{0}c"), "a\u{fffd}b\u{fffd}c");
}

#[test]
fn control_characters_use_hex_escapes() {
    assert_eq!(escape("\u{1}\u{2}\u{1e}\u{1f}"), "\\1 \\2 \\1e \\1f ");
    assert_eq!(escape("\u{7f}"), "\\7f ");
    // a digit immediately after a hex escape is fine — the space terminates the escape
    assert_eq!(escape("\u{1}a"), "\\1 a");
}

#[test]
fn leading_digit_is_escaped() {
    assert_eq!(escape("0a"), "\\30 a");
    assert_eq!(escape("1a"), "\\31 a");
    assert_eq!(escape("9a"), "\\39 a");
    // a digit that is not first is left alone
    assert_eq!(escape("a0b"), "a0b");
    assert_eq!(escape("a1b2c3"), "a1b2c3");
}

#[test]
fn leading_hyphen_then_digit_is_escaped() {
    assert_eq!(escape("-0a"), "-\\30 a");
    assert_eq!(escape("-1a"), "-\\31 a");
    // hyphen followed by a non-digit is fine
    assert_eq!(escape("-a"), "-a");
}

#[test]
fn lone_hyphen_is_escaped() {
    assert_eq!(escape("-"), "\\-");
    // two or more hyphens are valid identifiers
    assert_eq!(escape("--"), "--");
    assert_eq!(escape("--a"), "--a");
}

#[test]
fn safe_characters_pass_through() {
    assert_eq!(escape("abcXYZ0123456789-_"), "abcXYZ0123456789-_");
    // U+0080 and above are passed through unescaped
    assert_eq!(escape("\u{80}-_"), "\u{80}-_");
}

#[test]
fn unsafe_punctuation_is_backslash_escaped() {
    assert_eq!(escape("hello world"), "hello\\ world");
    assert_eq!(escape(".foo#bar"), "\\.foo\\#bar");
    assert_eq!(escape("3.14"), "\\33 \\.14");
    assert_eq!(escape("a:b"), "a\\:b");
    assert_eq!(escape("(){}[]"), "\\(\\)\\{\\}\\[\\]");
}

#[test]
fn unicode_passes_through() {
    assert_eq!(escape("café"), "café");
    assert_eq!(escape("\u{1f980}"), "\u{1f980}"); // 🦀
    assert_eq!(escape("日本語"), "日本語");
}

#[test]
fn builds_a_safe_selector() {
    let id = "a b#c";
    assert_eq!(format!("#{}", escape(id)), "#a\\ b\\#c");
}