Skip to main content

rust_css_parser/
plain.rs

1//! Plain (javascript like) values: the plain objects of `toPlainObject()` / `fromObject()`, visitor results, json
2//! data. Objects keep the insertion order of their keys, numbers are `f64` (`NaN`, `-0` and the infinities included).
3
4use std::borrow::Cow;
5use std::rc::Rc;
6
7pub type Key = Cow<'static, str>;
8
9/// shared `undefined` (no reference count is ever touched: `Undefined` holds no data)
10struct SyncPlain(Plain);
11unsafe impl Sync for SyncPlain {}
12static UNDEFINED: SyncPlain = SyncPlain(Plain::Undefined);
13
14#[derive(Clone, Debug, PartialEq, Default)]
15pub enum Plain {
16    #[default]
17    Undefined,
18    Null,
19    Bool(bool),
20    Number(f64),
21    String(Rc<str>),
22    Array(Vec<Plain>),
23    Object(PlainObject),
24}
25
26/// object with ordered keys
27#[derive(Clone, Debug, PartialEq, Default)]
28pub struct PlainObject(pub Vec<(Key, Plain)>);
29
30impl PlainObject {
31    pub fn new() -> Self {
32        Self(Vec::new())
33    }
34
35    pub fn get(&self, key: &str) -> Option<&Plain> {
36        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
37    }
38
39    pub fn get_mut(&mut self, key: &str) -> Option<&mut Plain> {
40        self.0.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v)
41    }
42
43    /// set a key (replaced in place when it exists, appended otherwise)
44    pub fn set(&mut self, key: impl Into<Key>, value: impl Into<Plain>) {
45        let key = key.into();
46        let value = value.into();
47        if let Some(slot) = self.get_mut(&key) {
48            *slot = value;
49        } else {
50            self.0.push((key, value));
51        }
52    }
53
54    pub fn remove(&mut self, key: &str) -> Option<Plain> {
55        let index = self.0.iter().position(|(k, _)| k == key)?;
56        Some(self.0.remove(index).1)
57    }
58
59    pub fn has(&self, key: &str) -> bool {
60        self.get(key).is_some()
61    }
62
63    pub fn keys(&self) -> impl Iterator<Item = &str> {
64        self.0.iter().map(|(k, _)| k.as_ref())
65    }
66}
67
68impl Plain {
69    pub fn object() -> Self {
70        Plain::Object(PlainObject::new())
71    }
72
73    /// `value == null`
74    pub fn is_nullish(&self) -> bool {
75        matches!(self, Plain::Undefined | Plain::Null)
76    }
77
78    pub fn as_f64(&self) -> Option<f64> {
79        match self {
80            Plain::Number(n) => Some(*n),
81            _ => None,
82        }
83    }
84
85    pub fn as_str(&self) -> Option<&str> {
86        match self {
87            Plain::String(s) => Some(s),
88            _ => None,
89        }
90    }
91
92    pub fn as_bool(&self) -> Option<bool> {
93        match self {
94            Plain::Bool(b) => Some(*b),
95            _ => None,
96        }
97    }
98
99    pub fn as_array(&self) -> Option<&Vec<Plain>> {
100        match self {
101            Plain::Array(a) => Some(a),
102            _ => None,
103        }
104    }
105
106    pub fn as_object(&self) -> Option<&PlainObject> {
107        match self {
108            Plain::Object(o) => Some(o),
109            _ => None,
110        }
111    }
112
113    pub fn as_object_mut(&mut self) -> Option<&mut PlainObject> {
114        match self {
115            Plain::Object(o) => Some(o),
116            _ => None,
117        }
118    }
119
120    /// property of an object (`undefined` otherwise)
121    pub fn get(&self, key: &str) -> &Plain {
122        self.as_object().and_then(|o| o.get(key)).unwrap_or(&UNDEFINED.0)
123    }
124
125    /// javascript truthiness
126    pub fn truthy(&self) -> bool {
127        match self {
128            Plain::Undefined | Plain::Null => false,
129            Plain::Bool(b) => *b,
130            Plain::Number(n) => *n != 0.0 && !n.is_nan(),
131            Plain::String(s) => !s.is_empty(),
132            _ => true,
133        }
134    }
135
136    /// `JSON.stringify()`
137    pub fn to_json(&self) -> String {
138        let mut out = String::new();
139        self.write_json(&mut out);
140        out
141    }
142
143    fn write_json(&self, out: &mut String) {
144        match self {
145            Plain::Undefined | Plain::Null => out.push_str("null"),
146            Plain::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
147            Plain::Number(n) => {
148                if n.is_finite() {
149                    out.push_str(&crate::utils::number::js_number_to_string(*n))
150                } else {
151                    out.push_str("null")
152                }
153            }
154            Plain::String(s) => write_json_string(s, out),
155            Plain::Array(a) => {
156                out.push('[');
157                for (i, v) in a.iter().enumerate() {
158                    if i > 0 {
159                        out.push(',');
160                    }
161                    if matches!(v, Plain::Undefined) {
162                        out.push_str("null");
163                    } else {
164                        v.write_json(out);
165                    }
166                }
167                out.push(']');
168            }
169            Plain::Object(o) => {
170                out.push('{');
171                let mut first = true;
172                for (k, v) in &o.0 {
173                    if matches!(v, Plain::Undefined) {
174                        continue;
175                    }
176                    if !first {
177                        out.push(',');
178                    }
179                    first = false;
180                    write_json_string(k, out);
181                    out.push(':');
182                    v.write_json(out);
183                }
184                out.push('}');
185            }
186        }
187    }
188
189    /// convert a json value
190    pub fn from_json(value: &serde_json::Value) -> Self {
191        match value {
192            serde_json::Value::Null => Plain::Null,
193            serde_json::Value::Bool(b) => Plain::Bool(*b),
194            serde_json::Value::Number(n) => Plain::Number(n.as_f64().unwrap_or(f64::NAN)),
195            serde_json::Value::String(s) => Plain::String(Rc::from(s.as_str())),
196            serde_json::Value::Array(a) => Plain::Array(a.iter().map(Plain::from_json).collect()),
197            serde_json::Value::Object(o) => {
198                Plain::Object(PlainObject(o.iter().map(|(k, v)| (Cow::Owned(k.clone()), Plain::from_json(v))).collect()))
199            }
200        }
201    }
202}
203
204fn write_json_string(s: &str, out: &mut String) {
205    out.push('"');
206    for c in s.chars() {
207        match c {
208            '"' => out.push_str("\\\""),
209            '\\' => out.push_str("\\\\"),
210            '\n' => out.push_str("\\n"),
211            '\r' => out.push_str("\\r"),
212            '\t' => out.push_str("\\t"),
213            '\u{8}' => out.push_str("\\b"),
214            '\u{c}' => out.push_str("\\f"),
215            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
216            c => out.push(c),
217        }
218    }
219    out.push('"');
220}
221
222impl From<f64> for Plain {
223    fn from(n: f64) -> Self {
224        Plain::Number(n)
225    }
226}
227
228impl From<u32> for Plain {
229    fn from(n: u32) -> Self {
230        Plain::Number(n as f64)
231    }
232}
233
234impl From<i32> for Plain {
235    fn from(n: i32) -> Self {
236        Plain::Number(n as f64)
237    }
238}
239
240impl From<u8> for Plain {
241    fn from(n: u8) -> Self {
242        Plain::Number(n as f64)
243    }
244}
245
246impl From<bool> for Plain {
247    fn from(b: bool) -> Self {
248        Plain::Bool(b)
249    }
250}
251
252impl From<&str> for Plain {
253    fn from(s: &str) -> Self {
254        Plain::String(Rc::from(s))
255    }
256}
257
258impl From<String> for Plain {
259    fn from(s: String) -> Self {
260        Plain::String(Rc::from(s))
261    }
262}
263
264impl From<crate::ast::strings::SharedStr> for Plain {
265    fn from(s: crate::ast::strings::SharedStr) -> Self {
266        Plain::String(s.into())
267    }
268}
269
270impl From<Rc<str>> for Plain {
271    fn from(s: Rc<str>) -> Self {
272        Plain::String(s)
273    }
274}
275
276impl From<Vec<Plain>> for Plain {
277    fn from(a: Vec<Plain>) -> Self {
278        Plain::Array(a)
279    }
280}
281
282impl From<PlainObject> for Plain {
283    fn from(o: PlainObject) -> Self {
284        Plain::Object(o)
285    }
286}
287
288impl<T: Into<Plain>> From<Option<T>> for Plain {
289    fn from(o: Option<T>) -> Self {
290        o.map_or(Plain::Null, Into::into)
291    }
292}
293
294impl Plain {
295    /// plain value of a host definition (the functions are `undefined`)
296    pub fn from_host_def(def: &crate::host::HostDef) -> Plain {
297        use crate::host::HostDef;
298        match def {
299            HostDef::Null => Plain::Null,
300            HostDef::Bool(b) => Plain::Bool(*b),
301            HostDef::Number(n) => Plain::Number(*n),
302            HostDef::Str(s) => Plain::String(s.clone()),
303            HostDef::Fn { .. } => Plain::Undefined,
304            HostDef::Array(items) => Plain::Array(items.iter().map(Plain::from_host_def).collect()),
305            HostDef::Object(entries) => {
306                let mut o = PlainObject::new();
307                for (k, v) in entries {
308                    o.set(k.to_string(), Plain::from_host_def(v));
309                }
310                Plain::Object(o)
311            }
312        }
313    }
314}