Skip to main content

lexical_ui/json/
value.rs

1use std::fmt;
2
3/// A JS value as `JSON.parse` returns it and `JSON.stringify` writes it.
4#[derive(Clone, Debug, PartialEq)]
5pub enum Value {
6    /// JS `undefined`. `JSON.parse` never returns it. An object property that
7    /// holds it keeps its position in the key order and is skipped by
8    /// `stringify`, as JS skips it; in an array it is written as `null`.
9    Undefined,
10    Null,
11    Bool(bool),
12    Number(f64),
13    String(String),
14    Array(Vec<Value>),
15    Object(Object),
16}
17
18impl Value {
19    pub fn as_str(&self) -> Option<&str> {
20        match self {
21            Value::String(s) => Some(s),
22            _ => None,
23        }
24    }
25
26    pub fn as_f64(&self) -> Option<f64> {
27        match self {
28            Value::Number(n) => Some(*n),
29            _ => None,
30        }
31    }
32
33    pub fn as_bool(&self) -> Option<bool> {
34        match self {
35            Value::Bool(b) => Some(*b),
36            _ => None,
37        }
38    }
39
40    pub fn as_array(&self) -> Option<&Vec<Value>> {
41        match self {
42            Value::Array(a) => Some(a),
43            _ => None,
44        }
45    }
46
47    pub fn as_object(&self) -> Option<&Object> {
48        match self {
49            Value::Object(o) => Some(o),
50            _ => None,
51        }
52    }
53
54    /// The property `key` of an object; `None` for anything else.
55    pub fn get(&self, key: &str) -> Option<&Value> {
56        self.as_object().and_then(|o| o.get(key))
57    }
58
59    pub fn is_undefined(&self) -> bool {
60        matches!(self, Value::Undefined)
61    }
62
63    pub fn is_null(&self) -> bool {
64        matches!(self, Value::Null)
65    }
66}
67
68impl From<&str> for Value {
69    fn from(s: &str) -> Self {
70        Value::String(s.to_owned())
71    }
72}
73
74impl From<String> for Value {
75    fn from(s: String) -> Self {
76        Value::String(s)
77    }
78}
79
80impl From<f64> for Value {
81    fn from(n: f64) -> Self {
82        Value::Number(n)
83    }
84}
85
86impl From<bool> for Value {
87    fn from(b: bool) -> Self {
88        Value::Bool(b)
89    }
90}
91
92impl From<Object> for Value {
93    fn from(o: Object) -> Self {
94        Value::Object(o)
95    }
96}
97
98impl From<Vec<Value>> for Value {
99    fn from(a: Vec<Value>) -> Self {
100        Value::Array(a)
101    }
102}
103
104/// `JSON.stringify(value)`, or `undefined` where JS returns `undefined`.
105impl fmt::Display for Value {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        match super::stringify(self) {
108            Some(text) => f.write_str(&text),
109            None => f.write_str("undefined"),
110        }
111    }
112}
113
114/// A JS object's own properties, in JS's order: keys that are array indices
115/// first, in ascending order, then the other keys in the order they were
116/// added. Setting a key that exists keeps its position.
117#[derive(Clone, Debug, Default, PartialEq)]
118pub struct Object {
119    entries: Vec<(String, Value)>,
120}
121
122impl Object {
123    pub fn new() -> Self {
124        Self::default()
125    }
126
127    pub fn len(&self) -> usize {
128        self.entries.len()
129    }
130
131    pub fn is_empty(&self) -> bool {
132        self.entries.is_empty()
133    }
134
135    /// The property `key`, `None` when it is absent. A property set to
136    /// [`Value::Undefined`] is present.
137    pub fn get(&self, key: &str) -> Option<&Value> {
138        self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
139    }
140
141    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
142        self.entries
143            .iter_mut()
144            .find(|(k, _)| k == key)
145            .map(|(_, v)| v)
146    }
147
148    pub fn contains_key(&self, key: &str) -> bool {
149        self.get(key).is_some()
150    }
151
152    /// `object[key] = value`.
153    pub fn insert(&mut self, key: impl Into<String>, value: Value) {
154        let key = key.into();
155        if let Some(existing) = self.get_mut(&key) {
156            *existing = value;
157            return;
158        }
159        let at = match array_index(&key) {
160            Some(index) => self
161                .entries
162                .iter()
163                .position(|(k, _)| array_index(k).is_none_or(|i| i > index))
164                .unwrap_or(self.entries.len()),
165            None => self.entries.len(),
166        };
167        self.entries.insert(at, (key, value));
168    }
169
170    /// `delete object[key]`, returning the value it held.
171    pub fn remove(&mut self, key: &str) -> Option<Value> {
172        let at = self.entries.iter().position(|(k, _)| k == key)?;
173        Some(self.entries.remove(at).1)
174    }
175
176    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
177        self.entries.iter().map(|(k, v)| (k.as_str(), v))
178    }
179
180    pub fn keys(&self) -> impl Iterator<Item = &str> {
181        self.entries.iter().map(|(k, _)| k.as_str())
182    }
183}
184
185impl<K: Into<String>> FromIterator<(K, Value)> for Object {
186    fn from_iter<I: IntoIterator<Item = (K, Value)>>(iter: I) -> Self {
187        let mut object = Object::new();
188        for (k, v) in iter {
189            object.insert(k, v);
190        }
191        object
192    }
193}
194
195/// The index a key names when it is an array index: the canonical decimal
196/// form of an integer below 2³² − 1, which JS orders before other keys.
197pub(crate) fn array_index(key: &str) -> Option<u32> {
198    if key.is_empty() || (key.len() > 1 && key.starts_with('0')) {
199        return None;
200    }
201    if !key.bytes().all(|b| b.is_ascii_digit()) {
202        return None;
203    }
204    key.parse::<u32>().ok().filter(|&i| i != u32::MAX)
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn keys_follow_js_property_order() {
213        // Object.keys({b: 1, 2: 1, a: 1, 1: 1, '01': 1, 4294967295: 1})
214        let mut o = Object::new();
215        for k in ["b", "2", "a", "1", "01", "4294967295"] {
216            o.insert(k, Value::Null);
217        }
218        o.insert("b", Value::Bool(true));
219        assert_eq!(
220            o.keys().collect::<Vec<_>>(),
221            ["1", "2", "b", "a", "01", "4294967295"]
222        );
223        assert_eq!(o.get("b"), Some(&Value::Bool(true)));
224    }
225}