Skip to main content

rust_css_parser/bindings/
value.rs

1//! Values exchanged with javascript and their binary encoding (shared by the N-API and the WASM bindings).
2//!
3//! Little endian. Each value starts with a tag:
4//!
5//! | tag | value |
6//! |-----|-------|
7//! | 0 | undefined |
8//! | 1 | null |
9//! | 2 / 3 | false / true |
10//! | 4 | number: f64 |
11//! | 5 | string: u32 byte length, utf-8 bytes |
12//! | 6 | bytes (`ArrayBuffer`, `Uint8Array`): u32 length, bytes |
13//! | 7 | array: u32 count, values |
14//! | 8 | object: u32 count, (string key, value) pairs |
15//! | 9 | function: u32 callback id, string name |
16//! | 10 | arena: u32 handle |
17//! | 11 | node (`AstArenaNode`): u32 arena handle, u32 id |
18//! | 12 | promise: u32 id |
19//! | 13 | error: string message |
20//! | 14 | output buffer: u32 id, u32 length (a rust buffer given to javascript, see `take_output()`) |
21
22use crate::host::{HostDef, HostValue};
23use crate::plain::{Plain, PlainObject};
24use std::rc::Rc;
25
26thread_local! {
27    static UNDEFINED: &'static Val = Box::leak(Box::new(Val::Undefined));
28}
29
30/// a reference to `undefined`
31pub fn undefined() -> &'static Val {
32    UNDEFINED.with(|u| *u)
33}
34
35/// a javascript value
36#[derive(Clone, Debug, Default)]
37pub enum Val {
38    #[default]
39    Undefined,
40    Null,
41    Bool(bool),
42    Num(f64),
43    Str(Rc<str>),
44    Bytes(Rc<[u8]>),
45    Array(Vec<Val>),
46    Object(Vec<(Rc<str>, Val)>),
47    Fn(u32, Rc<str>),
48    Arena(u32),
49    Node(u32, u32),
50    Promise(u32),
51    Error(Rc<str>),
52    /// a buffer owned by the output registry: id, length of the content
53    Output(u32, u32),
54}
55
56impl Val {
57    pub fn str(s: &str) -> Val {
58        Val::Str(Rc::from(s))
59    }
60
61    pub fn object(entries: Vec<(&str, Val)>) -> Val {
62        Val::Object(entries.into_iter().map(|(k, v)| (Rc::from(k), v)).collect())
63    }
64
65    pub fn is_nullish(&self) -> bool {
66        matches!(self, Val::Undefined | Val::Null)
67    }
68
69    pub fn get(&self, key: &str) -> &Val {
70        match self {
71            Val::Object(entries) => entries.iter().find(|(k, _)| &**k == key).map_or(undefined(), |(_, v)| v),
72            _ => undefined(),
73        }
74    }
75
76    pub fn num(&self) -> f64 {
77        match self {
78            Val::Num(n) => *n,
79            Val::Bool(b) => *b as u8 as f64,
80            Val::Null => 0.0,
81            _ => f64::NAN,
82        }
83    }
84
85    pub fn u32(&self) -> u32 {
86        let n = self.num();
87        if n.is_finite() && n >= 0.0 {
88            n as u32
89        } else {
90            0
91        }
92    }
93
94    pub fn as_str(&self) -> Option<&str> {
95        match self {
96            Val::Str(s) => Some(s),
97            _ => None,
98        }
99    }
100
101    pub fn truthy(&self) -> bool {
102        match self {
103            Val::Undefined | Val::Null => false,
104            Val::Bool(b) => *b,
105            Val::Num(n) => *n != 0.0 && !n.is_nan(),
106            Val::Str(s) => !s.is_empty(),
107            _ => true,
108        }
109    }
110
111    /// a list of numbers (node ids)
112    pub fn ids(&self) -> Vec<u32> {
113        match self {
114            Val::Array(items) => items.iter().map(|v| match v {
115                Val::Node(_, id) => *id,
116                v => v.u32(),
117            }).collect(),
118            Val::Node(_, id) => vec![*id],
119            Val::Num(_) => vec![self.u32()],
120            _ => Vec::new(),
121        }
122    }
123
124    /// host definition (options, visitors): the functions are callbacks
125    pub fn to_def(&self) -> HostDef {
126        match self {
127            Val::Undefined | Val::Null | Val::Error(_) | Val::Promise(_) | Val::Output(..) => HostDef::Null,
128            Val::Bool(b) => HostDef::Bool(*b),
129            Val::Num(n) => HostDef::Number(*n),
130            Val::Str(s) => HostDef::Str(s.clone()),
131            Val::Bytes(_) => HostDef::Null,
132            Val::Array(items) => HostDef::Array(items.iter().map(|v| v.to_def()).collect()),
133            Val::Object(entries) => HostDef::Object(entries.iter().filter(|(_, v)| !matches!(v, Val::Undefined)).map(|(k, v)| (k.clone(), v.to_def())).collect()),
134            Val::Fn(id, name) => HostDef::Fn { id: *id, name: name.clone() },
135            Val::Arena(h) => HostDef::Number(*h as f64),
136            Val::Node(_, id) => HostDef::Number(*id as f64),
137        }
138    }
139
140    /// value returned by a callback
141    pub fn to_host(&self) -> HostValue {
142        match self {
143            Val::Undefined => HostValue::Undefined,
144            Val::Null => HostValue::Null,
145            Val::Bool(b) => HostValue::Bool(*b),
146            Val::Num(n) => HostValue::Number(*n),
147            Val::Str(s) => HostValue::Str(s.clone()),
148            Val::Bytes(b) => HostValue::Bytes(b.clone()),
149            Val::Array(items) => HostValue::Array(items.iter().map(|v| v.to_host()).collect()),
150            Val::Object(_) => HostValue::Plain(self.to_plain()),
151            Val::Node(arena, id) => HostValue::ForeignNode(*arena, *id),
152            Val::Promise(id) => HostValue::Promise(*id),
153            Val::Fn(..) | Val::Arena(_) | Val::Error(_) | Val::Output(..) => HostValue::Undefined,
154        }
155    }
156
157    pub fn to_plain(&self) -> Plain {
158        match self {
159            Val::Undefined | Val::Fn(..) | Val::Promise(_) | Val::Error(_) | Val::Output(..) => Plain::Undefined,
160            Val::Null => Plain::Null,
161            Val::Bool(b) => Plain::Bool(*b),
162            Val::Num(n) => Plain::Number(*n),
163            Val::Str(s) => Plain::String(s.clone()),
164            Val::Bytes(b) => Plain::String(Rc::from(String::from_utf8_lossy(b).as_ref())),
165            Val::Array(items) => Plain::Array(items.iter().map(|v| v.to_plain()).collect()),
166            Val::Object(entries) => {
167                let mut o = PlainObject::new();
168                for (k, v) in entries {
169                    o.set(k.to_string(), v.to_plain());
170                }
171                Plain::Object(o)
172            }
173            Val::Arena(h) => Plain::Number(*h as f64),
174            Val::Node(_, id) => Plain::Number(*id as f64),
175        }
176    }
177
178    pub fn from_plain(plain: &Plain) -> Val {
179        match plain {
180            Plain::Undefined => Val::Undefined,
181            Plain::Null => Val::Null,
182            Plain::Bool(b) => Val::Bool(*b),
183            Plain::Number(n) => Val::Num(*n),
184            Plain::String(s) => Val::Str(s.clone()),
185            Plain::Array(items) => Val::Array(items.iter().map(Val::from_plain).collect()),
186            Plain::Object(o) => Val::Object(o.0.iter().map(|(k, v)| (Rc::from(k.as_ref()), Val::from_plain(v))).collect()),
187        }
188    }
189
190    pub fn from_host(value: &HostValue, arena: u32) -> Val {
191        match value {
192            HostValue::Undefined => Val::Undefined,
193            HostValue::Null => Val::Null,
194            HostValue::Bool(b) => Val::Bool(*b),
195            HostValue::Number(n) => Val::Num(*n),
196            HostValue::Str(s) => Val::Str(s.clone()),
197            HostValue::Bytes(b) => Val::Bytes(b.clone()),
198            HostValue::ForeignNode(a, id) => Val::Node(*a, *id),
199            HostValue::Plain(p) => Val::from_plain(p),
200            HostValue::Array(items) => Val::Array(items.iter().map(|v| Val::from_host(v, arena)).collect()),
201            HostValue::Promise(id) => Val::Promise(*id),
202        }
203    }
204
205    /// encode the value at the end of a buffer
206    pub fn encode(&self, out: &mut Vec<u8>) {
207        fn string(out: &mut Vec<u8>, s: &str) {
208            out.extend_from_slice(&(s.len() as u32).to_le_bytes());
209            out.extend_from_slice(s.as_bytes());
210        }
211        match self {
212            Val::Undefined => out.push(0),
213            Val::Null => out.push(1),
214            Val::Bool(b) => out.push(2 + *b as u8),
215            Val::Num(n) => {
216                out.push(4);
217                out.extend_from_slice(&n.to_le_bytes());
218            }
219            Val::Str(s) => {
220                out.push(5);
221                string(out, s);
222            }
223            Val::Bytes(b) => {
224                out.push(6);
225                out.extend_from_slice(&(b.len() as u32).to_le_bytes());
226                out.extend_from_slice(b);
227            }
228            Val::Array(items) => {
229                out.push(7);
230                out.extend_from_slice(&(items.len() as u32).to_le_bytes());
231                for item in items {
232                    item.encode(out);
233                }
234            }
235            Val::Object(entries) => {
236                out.push(8);
237                out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
238                for (k, v) in entries {
239                    string(out, k);
240                    v.encode(out);
241                }
242            }
243            Val::Fn(id, name) => {
244                out.push(9);
245                out.extend_from_slice(&id.to_le_bytes());
246                string(out, name);
247            }
248            Val::Arena(h) => {
249                out.push(10);
250                out.extend_from_slice(&h.to_le_bytes());
251            }
252            Val::Node(a, id) => {
253                out.push(11);
254                out.extend_from_slice(&a.to_le_bytes());
255                out.extend_from_slice(&id.to_le_bytes());
256            }
257            Val::Promise(id) => {
258                out.push(12);
259                out.extend_from_slice(&id.to_le_bytes());
260            }
261            Val::Error(message) => {
262                out.push(13);
263                string(out, message);
264            }
265            Val::Output(id, len) => {
266                out.push(14);
267                out.extend_from_slice(&id.to_le_bytes());
268                out.extend_from_slice(&len.to_le_bytes());
269            }
270        }
271    }
272
273    /// decode a value. `pos` is moved after it
274    pub fn decode(bytes: &[u8], pos: &mut usize) -> Val {
275        fn u32_at(bytes: &[u8], pos: &mut usize) -> u32 {
276            let v = u32::from_le_bytes(bytes[*pos..*pos + 4].try_into().unwrap());
277            *pos += 4;
278            v
279        }
280        fn string(bytes: &[u8], pos: &mut usize) -> Rc<str> {
281            let len = u32_at(bytes, pos) as usize;
282            let s: Rc<str> = Rc::from(std::str::from_utf8(&bytes[*pos..*pos + len]).unwrap_or(""));
283            *pos += len;
284            s
285        }
286        let tag = bytes[*pos];
287        *pos += 1;
288        match tag {
289            0 => Val::Undefined,
290            1 => Val::Null,
291            2 => Val::Bool(false),
292            3 => Val::Bool(true),
293            4 => {
294                let v = f64::from_le_bytes(bytes[*pos..*pos + 8].try_into().unwrap());
295                *pos += 8;
296                Val::Num(v)
297            }
298            5 => Val::Str(string(bytes, pos)),
299            6 => {
300                let len = u32_at(bytes, pos) as usize;
301                let b: Rc<[u8]> = Rc::from(&bytes[*pos..*pos + len]);
302                *pos += len;
303                Val::Bytes(b)
304            }
305            7 => {
306                let n = u32_at(bytes, pos);
307                Val::Array((0..n).map(|_| Val::decode(bytes, pos)).collect())
308            }
309            8 => {
310                let n = u32_at(bytes, pos);
311                Val::Object((0..n).map(|_| (string(bytes, pos), Val::decode(bytes, pos))).collect())
312            }
313            9 => {
314                let id = u32_at(bytes, pos);
315                Val::Fn(id, string(bytes, pos))
316            }
317            10 => Val::Arena(u32_at(bytes, pos)),
318            11 => {
319                let a = u32_at(bytes, pos);
320                Val::Node(a, u32_at(bytes, pos))
321            }
322            12 => Val::Promise(u32_at(bytes, pos)),
323            13 => Val::Error(string(bytes, pos)),
324            14 => {
325                let id = u32_at(bytes, pos);
326                Val::Output(id, u32_at(bytes, pos))
327            }
328            _ => Val::Undefined,
329        }
330    }
331}