1use std::{cmp::Ordering, fmt, hash::{Hash, Hasher}, ops::Index, sync::{Arc, OnceLock}};
6
7#[derive(Debug, Clone)]
11pub struct JsString(Arc<StringData>);
12#[derive(Debug)]
13struct StringData {
14 hash: u64,
18 units: Vec<u16>,
19 scalar: OnceLock<Option<String>>,
20}
21impl StringData {
22 fn new(units: Vec<u16>, scalar: OnceLock<Option<String>>) -> Self {
23 Self { hash: digest(&units), units, scalar }
24 }
25}
26fn digest(units: &[u16]) -> u64 {
29 static KEYS: OnceLock<std::collections::hash_map::RandomState> = OnceLock::new();
30 use std::hash::BuildHasher;
31 KEYS.get_or_init(Default::default).hash_one(units)
32}
33#[derive(Debug, Default, Clone, Copy)]
36pub struct JsHash;
37impl std::hash::BuildHasher for JsHash {
38 type Hasher = JsHasher;
39 fn build_hasher(&self) -> JsHasher { JsHasher(0) }
40}
41#[doc(hidden)]
42#[derive(Debug)]
43pub struct JsHasher(u64);
44impl Hasher for JsHasher {
45 fn finish(&self) -> u64 { self.0 }
46 fn write_u64(&mut self, value: u64) { self.0 = self.0.rotate_left(26) ^ value; }
47 fn write(&mut self, bytes: &[u8]) {
48 for &byte in bytes { self.0 = (self.0.rotate_left(5) ^ u64::from(byte)).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); }
49 }
50}
51impl PartialEq for JsString {
53 fn eq(&self, other: &Self) -> bool {
54 Arc::ptr_eq(&self.0, &other.0) || (self.0.hash == other.0.hash && self.units() == other.units())
55 }
56}
57impl Eq for JsString {}
58impl PartialOrd for JsString {
59 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
60}
61impl Ord for JsString {
62 fn cmp(&self, other: &Self) -> Ordering { self.units().cmp(other.units()) }
63}
64impl Hash for JsString {
65 fn hash<H: Hasher>(&self, state: &mut H) { state.write_u64(self.0.hash); }
66}
67impl Default for JsString {
68 fn default() -> Self { Self::from("") }
69}
70impl JsString {
71 pub fn from_units(units: Vec<u16>) -> Self {
72 Self(Arc::new(StringData::new(units, OnceLock::new())))
73 }
74 pub fn units(&self) -> &[u16] { &self.0.units }
75 pub fn surround(prefix: &str, value: &Self, suffix: &str) -> Self {
76 Self::from_units(prefix.encode_utf16().chain(value.0.units.iter().copied()).chain(suffix.encode_utf16()).collect())
77 }
78 pub fn as_str(&self) -> Option<&str> { self.0.scalar.get_or_init(|| String::from_utf16(self.units()).ok()).as_deref() }
79 pub fn is_empty(&self) -> bool { self.0.units.is_empty() }
80 pub fn is_blank(&self) -> bool {
81 self.0.units.iter().all(|&unit| char::from_u32(u32::from(unit))
82 .is_some_and(crate::projections::is_ecmascript_whitespace))
83 }
84 pub fn concat(parts: &[&Self], separator: &str) -> Self {
86 let mut units = Vec::new();
87 for (index, part) in parts.iter().enumerate() {
88 if index > 0 { units.extend(separator.encode_utf16()); }
89 units.extend_from_slice(part.units());
90 }
91 Self::from_units(units)
92 }
93 pub fn starts_with(&self, prefix: &str) -> bool {
94 self.0.units.iter().copied().take(prefix.encode_utf16().count()).eq(prefix.encode_utf16())
95 }
96 pub fn normalized_class(&self) -> Self {
100 if let Some(normalized) = crate::class_normalization::lookup(self) { return normalized; }
101 let whitespace = |unit: &u16| char::from_u32(u32::from(*unit))
102 .is_some_and(crate::projections::is_ecmascript_whitespace);
103 let start = self.0.units.iter().position(|u| !whitespace(u)).unwrap_or(self.0.units.len());
104 let end = self.0.units.iter().rposition(|u| !whitespace(u)).map_or(start, |i| i + 1);
105 let mut units = Vec::new();
106 for ch in char::decode_utf16(self.0.units[start..end].iter().copied()) {
107 match ch {
108 Err(error) => units.push(error.unpaired_surrogate()),
109 Ok(ch) => for upper in ch.to_uppercase() {
110 units.extend_from_slice(upper.encode_utf16(&mut [0; 2]));
111 },
112 }
113 }
114 Self::from_units(units)
115 }
116 pub fn write_json(&self, out: &mut String) {
117 out.push('"');
118 for ch in char::decode_utf16(self.0.units.iter().copied()) {
119 match ch {
120 Err(error) => out.push_str(&format!("\\u{:04x}", error.unpaired_surrogate())),
121 Ok('"') => out.push_str("\\\""),
122 Ok('\\') => out.push_str("\\\\"),
123 Ok('\u{08}') => out.push_str("\\b"),
124 Ok('\u{09}') => out.push_str("\\t"),
125 Ok('\u{0a}') => out.push_str("\\n"),
126 Ok('\u{0c}') => out.push_str("\\f"),
127 Ok('\u{0d}') => out.push_str("\\r"),
128 Ok(c) if c < ' ' => out.push_str(&format!("\\u{:04x}", c as u32)),
129 Ok(c) => out.push(c),
130 }
131 }
132 out.push('"');
133 }
134}
135impl From<&str> for JsString {
136 fn from(value: &str) -> Self { Self::from(value.to_owned()) }
137}
138impl From<String> for JsString {
139 fn from(value: String) -> Self { Self(Arc::new(StringData::new(value.encode_utf16().collect(), OnceLock::from(Some(value))))) }
140}
141impl fmt::Display for JsString {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 for ch in char::decode_utf16(self.0.units.iter().copied()) {
144 match ch {
145 Ok(c) => write!(f, "{c}")?,
146 Err(error) => write!(f, "\\u{:04x}", error.unpaired_surrogate())?,
149 }
150 }
151 Ok(())
152 }
153}
154
155#[derive(Debug, Clone, PartialEq)]
156pub enum DocumentValue {
157 Null,
158 Bool(bool),
159 Number(f64),
160 String(JsString),
161 Array(Vec<DocumentValue>),
162 Object(Vec<(JsString, DocumentValue)>),
163}
164impl DocumentValue {
165 pub fn as_string(&self) -> Option<&JsString> { if let Self::String(s) = self { Some(s) } else { None } }
166 pub fn as_str(&self) -> Option<&str> { self.as_string().and_then(JsString::as_str) }
167 pub fn is_string(&self) -> bool { matches!(self, Self::String(_)) }
168 pub fn is_object(&self) -> bool { matches!(self, Self::Object(_)) }
169 pub fn as_f64(&self) -> Option<f64> { if let Self::Number(n) = self { Some(*n) } else { None } }
170 pub fn as_array(&self) -> Option<&Vec<Self>> { if let Self::Array(a) = self { Some(a) } else { None } }
171 pub fn get(&self, key: &str) -> Option<&Self> {
172 if let Self::Object(entries) = self {
173 entries.iter().find(|(name, _)| name.as_str() == Some(key)).map(|(_, value)| value)
174 } else { None }
175 }
176}
177impl Index<&str> for DocumentValue {
178 type Output = Self;
179 fn index(&self, key: &str) -> &Self { self.get(key).unwrap_or(&Self::Null) }
180}
181impl Index<usize> for DocumentValue {
182 type Output = Self;
183 fn index(&self, key: usize) -> &Self { self.as_array().and_then(|a| a.get(key)).unwrap_or(&Self::Null) }
184}
185impl From<&serde_json::Value> for DocumentValue {
186 fn from(value: &serde_json::Value) -> Self {
187 use serde_json::Value;
188 match value {
189 Value::Null => Self::Null,
190 Value::Bool(b) => Self::Bool(*b),
191 Value::Number(n) => Self::Number(n.as_f64().unwrap()),
192 Value::String(s) => Self::String(s.as_str().into()),
193 Value::Array(a) => Self::Array(a.iter().map(Self::from).collect()),
194 Value::Object(o) => ordered_object(o.iter().map(|(k, v)| (k.as_str().into(), Self::from(v))).collect()),
195 }
196 }
197}
198pub fn ordered_object(mut entries: Vec<(JsString, DocumentValue)>) -> DocumentValue {
199 sort_entries(&mut entries);
200 DocumentValue::Object(entries)
201}
202fn sort_entries(entries: &mut [(JsString, DocumentValue)]) {
206 fn array_index(key: &JsString) -> Option<u32> {
207 let text = key.as_str()?;
208 let index = text.parse::<u32>().ok()?;
209 (index != u32::MAX && index.to_string() == text).then_some(index)
210 }
211 entries.sort_by(|a, b| match (array_index(&a.0), array_index(&b.0)) {
212 (Some(a), Some(b)) => a.cmp(&b),
213 (Some(_), None) => std::cmp::Ordering::Less,
214 (None, Some(_)) => std::cmp::Ordering::Greater,
215 _ => std::cmp::Ordering::Equal,
216 });
217}
218
219impl From<&JsString> for JsString {
220 fn from(value: &JsString) -> Self { value.clone() }
221}
222impl PartialEq<str> for JsString {
223 fn eq(&self, value: &str) -> bool { self.0.units.iter().copied().eq(value.encode_utf16()) }
224}
225impl PartialEq<&str> for JsString {
226 fn eq(&self, value: &&str) -> bool { self == *value }
227}
228
229impl std::ops::IndexMut<&str> for DocumentValue {
230 fn index_mut(&mut self, key: &str) -> &mut Self {
231 let Self::Object(entries) = self else { panic!("expected object") };
232 let index = match entries.iter().position(|(name, _)| name == key) {
233 Some(index) => index,
234 None => {
235 entries.push((key.into(), Self::Null));
237 sort_entries(entries);
238 entries.iter().position(|(name, _)| name == key).expect("key was just inserted")
239 },
240 };
241 &mut entries[index].1
242 }
243}
244impl PartialEq<bool> for DocumentValue {
245 fn eq(&self, value: &bool) -> bool { matches!(self, Self::Bool(b) if b == value) }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251 use std::collections::{HashMap, HashSet};
252
253 #[test]
254 fn issue_8351_cached_digest_agrees_with_code_unit_equality() {
255 let lone = JsString::from_units(vec![0x61, 0xd800]);
258 let lone_copy = JsString::from_units(vec![0x61, 0xd800]);
259 let scalar = JsString::from("attr:core");
260 let scalar_units = JsString::from_units("attr:core".encode_utf16().collect());
261 assert_eq!(lone, lone_copy);
262 assert_eq!(scalar, scalar_units);
263 assert_ne!(lone, JsString::from_units(vec![0x61, 0xdc00]));
264 let build = std::collections::hash_map::RandomState::new();
265 use std::hash::BuildHasher;
266 assert_eq!(build.hash_one(&lone), build.hash_one(&lone_copy));
267 assert_eq!(JsHash.hash_one(&scalar), JsHash.hash_one(&scalar_units));
268 let map: HashMap<_, _, JsHash> = [(lone.clone(), 1), (scalar.clone(), 2)].into_iter().collect();
269 assert_eq!(map.get(&lone_copy), Some(&1));
270 assert_eq!(map.get(&scalar_units), Some(&2));
271 assert_eq!(map.get(&JsString::from("attr:cor")), None);
272 let distinct: HashSet<_, JsHash> = (0..4096u16).map(|unit| JsString::from_units(vec![unit])).collect();
273 assert_eq!(distinct.len(), 4096);
274 }
275}