Skip to main content

rust_css_parser/parser/utils/
hash.rs

1//! Port of `src/parser/utils/hash.ts`.
2//!
3//! The typescript `hash()` is async because of `crypto.subtle.digest()`: the rust digests are synchronous, `hash()` and
4//! `sync_hash()` share the implementation (`sync_hash()` rejects the sha algorithms, like `syncHash()`).
5
6use crate::ast::arena::AstArena;
7use base64::Engine;
8use sha1::Digest;
9
10pub const LOWER: &str = "abcdefghijklmnopqrstuvwxyz";
11pub const DIGITS: &str = "0123456789";
12
13/// supported hash algorithms
14pub const HASH_ALGORITHMS: [&str; 7] = ["hex", "base64", "base64url", "sha1", "sha256", "sha384", "sha512"];
15
16const FULL_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
17const FIRST_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
18
19/// simple deterministic hash
20fn hash_code(str: &str) -> u32 {
21    let mut hash: u32 = 0;
22    for c in str.encode_utf16() {
23        hash = hash.wrapping_mul(31).wrapping_add(c as u32);
24    }
25    hash
26}
27
28/// generate a hash id
29pub fn hash_id(input: &str, length: usize) -> String {
30    let mut n = hash_code(input) as u64;
31    let mut chars: Vec<u8> = Vec::with_capacity(length);
32    chars.push(FIRST_ALPHABET[(n % FIRST_ALPHABET.len() as u64) as usize]);
33    for i in 1..length {
34        n = (n + (chars.len() * i) as u64) % FULL_ALPHABET.len() as u64;
35        chars.push(FULL_ALPHABET[n as usize]);
36    }
37    String::from_utf8(chars).unwrap()
38}
39
40/// structural signature of a node or a token: type, name, values, tokens and children
41pub fn node_signature(arena: &AstArena, id: u32) -> String {
42    let mut result = format!(
43        "{}:{}:{}:{}:{}:{}",
44        arena.data_types.get(id),
45        arena.name.get(id),
46        arena.string_value.get(id),
47        crate::utils::number::js_number_to_string(arena.numeric_value.get(id)),
48        arena.unit.get(id),
49        arena.color_type.get(id)
50    );
51    if arena.first_token.get(id) != 0 {
52        result.push('(');
53        for token in arena.token_iter(id) {
54            result.push_str(&node_signature(arena, token));
55            result.push(',');
56        }
57        result.push(')');
58    }
59    if arena.first_child.get(id) != 0 {
60        result.push('{');
61        for child in arena.child_iter(id) {
62            result.push_str(&node_signature(arena, child));
63            result.push(',');
64        }
65        result.push('}');
66    }
67    result
68}
69
70fn bytes_to_hex(bytes: &[u8]) -> String {
71    bytes.iter().map(|b| format!("{:02x}", b)).collect()
72}
73
74/// hex of the code points of a string (`charCodeAt(0)` of each character)
75fn string_to_hex(input: &str) -> String {
76    let mut result = String::new();
77    for c in input.chars() {
78        let code = c.encode_utf16(&mut [0u16; 2])[0];
79        result.push_str(&format!("{:02x}", code));
80    }
81    result
82}
83
84/// `String.prototype.slice(0, length)`
85fn take(s: String, length: usize) -> String {
86    if s.len() <= length {
87        s
88    } else {
89        s[..length].to_string()
90    }
91}
92
93/// `btoa()`: None when a character is not latin1 (`btoa()` throws)
94fn btoa(input: &str) -> Result<String, String> {
95    let mut bytes = Vec::with_capacity(input.len());
96    for c in input.chars() {
97        if (c as u32) > 0xff {
98            return Err("Invalid character".into());
99        }
100        bytes.push(c as u32 as u8);
101    }
102    Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
103}
104
105fn hash_impl(input: &str, length: usize, algo: Option<&str>, allow_sha: bool) -> Result<String, String> {
106    let Some(algo) = algo else {
107        return Ok(hash_id(input, length));
108    };
109    match algo {
110        "hex" => Ok(take(string_to_hex(input), length)),
111        "base64" | "base64url" => {
112            let mut result = btoa(input)?;
113            if algo == "base64url" {
114                result = result.replace('+', "-").replace('/', "_").trim_end_matches('=').to_string();
115            }
116            Ok(take(result, length))
117        }
118        "sha1" | "sha256" | "sha384" | "sha512" if allow_sha => {
119            let bytes = input.as_bytes();
120            let digest = match algo {
121                "sha1" => sha1::Sha1::digest(bytes).to_vec(),
122                "sha256" => sha2::Sha256::digest(bytes).to_vec(),
123                "sha384" => sha2::Sha384::digest(bytes).to_vec(),
124                _ => sha2::Sha512::digest(bytes).to_vec(),
125            };
126            Ok(take(bytes_to_hex(&digest), length))
127        }
128        _ => Err(format!("Unsupported hash algorithm: {}", algo)),
129    }
130}
131
132/// generate a hash (`hash()`)
133pub fn hash(input: &str, length: usize, algo: Option<&str>) -> Result<String, String> {
134    hash_impl(input, length, algo, true)
135}
136
137/// generate a hash (`syncHash()`): the sha algorithms are not supported
138pub fn sync_hash(input: &str, length: usize, algo: Option<&str>) -> Result<String, String> {
139    hash_impl(input, length, algo, false)
140}