Skip to main content

rust_css_parser/parser/utils/
canonical.rs

1//! Port of `src/parser/utils/canonical.ts`.
2//!
3//! Canonical strings: the spellings of the known units and function names (`dB`, `translateX`, ...). They are
4//! registered once and stored in a single text: the string table references ranges of this text, no string is created.
5
6use std::cell::RefCell;
7use crate::utils::fx::HashMap;
8
9#[derive(Default)]
10struct Canonical {
11    /// offset of the registered strings in the text
12    offsets: HashMap<String, u32>,
13    /// registered strings, concatenated (the canonical strings are ascii: one code unit per byte)
14    text: String,
15}
16
17thread_local! {
18    static CANONICAL: RefCell<Canonical> = RefCell::new(Canonical::default());
19}
20
21/// register a canonical string
22/// returns the range of the string in the canonical text, packed: `start << 8 | length`
23pub fn register_canonical(str: &str) -> u32 {
24    debug_assert!(str.is_ascii() && str.len() < 256);
25    CANONICAL.with(|c| {
26        let mut c = c.borrow_mut();
27        let start = match c.offsets.get(str) {
28            Some(&start) => start,
29            None => {
30                let start = c.text.len() as u32;
31                c.offsets.insert(str.to_owned(), start);
32                c.text.push_str(str);
33                start
34            }
35        };
36        (start << 8) | str.len() as u32
37    })
38}
39
40/// start of a packed range
41#[inline]
42pub fn canonical_start(range: u32) -> u32 {
43    range >> 8
44}
45
46/// end of a packed range
47#[inline]
48pub fn canonical_end(range: u32) -> u32 {
49    (range >> 8) + (range & 0xff)
50}
51
52/// run a function with the canonical text (ascii: the bytes are the code units)
53pub fn with_canonical_text<R>(f: impl FnOnce(&str) -> R) -> R {
54    CANONICAL.with(|c| f(&c.borrow().text))
55}
56
57/// a range of the canonical text
58pub fn canonical_slice(start: u32, end: u32) -> String {
59    with_canonical_text(|t| t[start as usize..end as usize].to_owned())
60}
61
62/// code unit of the canonical text
63pub fn canonical_code_at(offset: u32) -> u32 {
64    with_canonical_text(|t| t.as_bytes().get(offset as usize).map_or(u32::MAX, |&b| b as u32))
65}