Skip to main content

rust_css_parser/parser/utils/
codes.rs

1//! Port of `src/parser/utils/codes.ts`.
2//!
3//! Hashing and comparison of strings and of ranges of code units, without creating strings.
4//! The values of the tokens are ranges of the code units of the source: a string and a range with the same content
5//! have the same hash (30 bits).
6
7use std::rc::Rc;
8
9/// a code unit: a byte of an ascii input or an utf-16 code unit
10pub trait Unit: Copy + Into<u32> + 'static {}
11impl Unit for u8 {}
12impl Unit for u16 {}
13
14/// code units of the css source: the bytes of an ascii input, the utf-16 code units otherwise.
15/// shared (reference counted): the tokenizer, the string table and the sources reference the same buffer
16#[derive(Clone, Debug)]
17pub enum CodeUnits {
18    Bytes(Rc<[u8]>),
19    Utf16(Rc<[u16]>),
20}
21
22impl CodeUnits {
23    /// code units of a string: the bytes when the string is ascii, the utf-16 code units otherwise
24    pub fn from_str(text: &str) -> Self {
25        if text.is_ascii() {
26            CodeUnits::Bytes(Rc::from(text.as_bytes()))
27        } else {
28            CodeUnits::Utf16(text.encode_utf16().collect::<Vec<u16>>().into())
29        }
30    }
31
32    /// code units of utf-16 code units: bytes when every unit is ascii
33    pub fn from_utf16(units: &[u16]) -> Self {
34        if units.iter().all(|&u| u < 0x80) {
35            CodeUnits::Bytes(units.iter().map(|&u| u as u8).collect::<Vec<u8>>().into())
36        } else {
37            CodeUnits::Utf16(Rc::from(units))
38        }
39    }
40
41    #[inline]
42    pub fn len(&self) -> usize {
43        match self {
44            CodeUnits::Bytes(b) => b.len(),
45            CodeUnits::Utf16(u) => u.len(),
46        }
47    }
48
49    #[inline]
50    pub fn is_empty(&self) -> bool {
51        self.len() == 0
52    }
53
54    /// code unit at an index (`codes[i]`). out of range reads return `0xffffffff` (`undefined` in typescript)
55    #[inline]
56    pub fn at(&self, index: usize) -> u32 {
57        match self {
58            CodeUnits::Bytes(b) => b.get(index).map_or(u32::MAX, |&c| c as u32),
59            CodeUnits::Utf16(u) => u.get(index).map_or(u32::MAX, |&c| c as u32),
60        }
61    }
62
63    /// the text of a range. ascii ranges are borrowed: no copy
64    pub fn slice(&self, start: usize, end: usize) -> std::borrow::Cow<'_, str> {
65        match self {
66            // ascii bytes are valid utf-8
67            CodeUnits::Bytes(b) => std::borrow::Cow::Borrowed(unsafe { std::str::from_utf8_unchecked(&b[start..end]) }),
68            CodeUnits::Utf16(u) => std::borrow::Cow::Owned(String::from_utf16_lossy(&u[start..end])),
69        }
70    }
71
72    pub fn hash_range(&self, start: usize, end: usize) -> i32 {
73        match self {
74            CodeUnits::Bytes(b) => hash_range(b, start, end),
75            CodeUnits::Utf16(u) => hash_range(u, start, end),
76        }
77    }
78
79    pub fn hash_range_lower(&self, start: usize, end: usize) -> i32 {
80        match self {
81            CodeUnits::Bytes(b) => hash_range_lower(b, start, end),
82            CodeUnits::Utf16(u) => hash_range_lower(u, start, end),
83        }
84    }
85}
86
87/// FNV-1a offset basis
88const FNV_OFFSET: u32 = 0x811c9dc5;
89/// FNV-1a prime
90const FNV_PRIME: u32 = 0x01000193;
91/// the hashes are 30 bits integers
92const HASH_MASK: u32 = 0x3fffffff;
93/// KELVIN SIGN: lowercased to `k` by `toLowerCase()`
94const KELVIN_SIGN: u32 = 0x212a;
95
96/// hash of a string (case sensitive), over its utf-16 code units. same value as [`hash_range`]
97pub fn hash_string(str: &str) -> i32 {
98    let mut hash = FNV_OFFSET;
99    for code in str.encode_utf16() {
100        hash = (hash ^ code as u32).wrapping_mul(FNV_PRIME);
101    }
102    (hash & HASH_MASK) as i32
103}
104
105/// hash of utf-16 code units (case sensitive)
106pub fn hash_units<T: Unit>(codes: &[T]) -> i32 {
107    hash_range(codes, 0, codes.len())
108}
109
110/// hash of a range of code units (case sensitive). same value as [`hash_string`] for the same code units
111#[inline]
112pub fn hash_range<T: Unit>(codes: &[T], start: usize, end: usize) -> i32 {
113    let mut hash = FNV_OFFSET;
114    for &code in &codes[start..end] {
115        hash = (hash ^ code.into()).wrapping_mul(FNV_PRIME);
116    }
117    (hash & HASH_MASK) as i32
118}
119
120/// lowercase ascii code of a code unit: the ascii uppercase letters and the kelvin sign are lowercased. -1 for the
121/// other non ascii code units
122#[inline]
123pub fn lower_ascii(code: u32) -> i32 {
124    if (0x41..=0x5a).contains(&code) {
125        return (code + 32) as i32;
126    }
127    if code > 0x7f {
128        return if code == KELVIN_SIGN { 0x6b } else { -1 };
129    }
130    code as i32
131}
132
133/// hash of a range of code units, ignoring the case. -1 when the range contains a non ascii character that cannot
134/// match an ascii key
135pub fn hash_range_lower<T: Unit>(codes: &[T], start: usize, end: usize) -> i32 {
136    let mut hash = FNV_OFFSET;
137    for &code in &codes[start..end] {
138        let code = lower_ascii(code.into());
139        if code == -1 {
140            return -1;
141        }
142        hash = (hash ^ code as u32).wrapping_mul(FNV_PRIME);
143    }
144    (hash & HASH_MASK) as i32
145}
146
147/// hash of a string ignoring the case, see [`hash_range_lower`]
148pub fn hash_string_lower(str: &str) -> i32 {
149    let mut hash = FNV_OFFSET;
150    for code in str.encode_utf16() {
151        let code = lower_ascii(code as u32);
152        if code == -1 {
153            return -1;
154        }
155        hash = (hash ^ code as u32).wrapping_mul(FNV_PRIME);
156    }
157    (hash & HASH_MASK) as i32
158}