1use crate::map::{self, OrderedMap};
2use std::fmt;
3use std::sync::Arc;
4
5#[derive(Clone, Debug, PartialEq, Default)]
14pub enum Value {
15 #[default]
16 Null,
17 Bool(bool),
18 Number(f64),
19 String(String),
20 Array(Vec<Value>),
21 Object(Object),
22}
23
24impl Value {
25 pub fn is_null(&self) -> bool {
26 matches!(self, Value::Null)
27 }
28
29 pub fn as_str(&self) -> Option<&str> {
30 match self {
31 Value::String(s) => Some(s),
32 _ => None,
33 }
34 }
35
36 pub fn as_f64(&self) -> Option<f64> {
37 match self {
38 Value::Number(n) => Some(*n),
39 _ => None,
40 }
41 }
42
43 pub fn as_bool(&self) -> Option<bool> {
44 match self {
45 Value::Bool(b) => Some(*b),
46 _ => None,
47 }
48 }
49
50 pub fn as_array(&self) -> Option<&Vec<Value>> {
51 match self {
52 Value::Array(a) => Some(a),
53 _ => None,
54 }
55 }
56
57 pub fn as_object(&self) -> Option<&Object> {
58 match self {
59 Value::Object(o) => Some(o),
60 _ => None,
61 }
62 }
63
64 pub fn get(&self, key: &str) -> Option<&Value> {
66 self.as_object().and_then(|o| o.get(key))
67 }
68
69 pub fn at(&self, index: usize) -> Option<&Value> {
71 self.as_array().and_then(|a| a.get(index))
72 }
73
74 pub fn type_name(&self) -> &'static str {
76 match self {
77 Value::Null => "null",
78 Value::Bool(_) => "boolean",
79 Value::Number(_) => "number",
80 Value::String(_) => "string",
81 Value::Array(_) => "array",
82 Value::Object(_) => "object",
83 }
84 }
85}
86
87impl fmt::Display for Value {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(&super::stringify(self))
91 }
92}
93
94impl From<bool> for Value {
95 fn from(b: bool) -> Self {
96 Value::Bool(b)
97 }
98}
99
100impl From<f64> for Value {
101 fn from(n: f64) -> Self {
102 Value::Number(n)
103 }
104}
105
106impl From<i64> for Value {
107 fn from(n: i64) -> Self {
108 Value::Number(n as f64)
109 }
110}
111
112impl From<i32> for Value {
113 fn from(n: i32) -> Self {
114 Value::Number(n.into())
115 }
116}
117
118impl From<&str> for Value {
119 fn from(s: &str) -> Self {
120 Value::String(s.to_owned())
121 }
122}
123
124impl From<String> for Value {
125 fn from(s: String) -> Self {
126 Value::String(s)
127 }
128}
129
130impl From<Vec<Value>> for Value {
131 fn from(a: Vec<Value>) -> Self {
132 Value::Array(a)
133 }
134}
135
136impl From<Object> for Value {
137 fn from(o: Object) -> Self {
138 Value::Object(o)
139 }
140}
141
142impl<T: Into<Value>> From<Option<T>> for Value {
143 fn from(v: Option<T>) -> Self {
144 v.map_or(Value::Null, Into::into)
145 }
146}
147
148#[derive(Clone, Default)]
164pub struct Object {
165 entries: Arc<OrderedMap<Value>>,
166 integer_keys: usize,
168}
169
170impl Object {
171 pub fn new() -> Self {
172 Self::default()
173 }
174
175 pub fn with_capacity(capacity: usize) -> Self {
176 Object {
177 entries: Arc::new(OrderedMap::with_capacity(capacity)),
178 integer_keys: 0,
179 }
180 }
181
182 pub fn len(&self) -> usize {
183 self.entries.len()
184 }
185
186 pub fn is_empty(&self) -> bool {
187 self.entries.is_empty()
188 }
189
190 pub fn get(&self, key: &str) -> Option<&Value> {
191 self.entries.get(key)
192 }
193
194 pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
195 if !self.entries.contains_key(key) {
196 return None;
197 }
198 Arc::make_mut(&mut self.entries).get_mut(key)
199 }
200
201 pub fn contains_key(&self, key: &str) -> bool {
202 self.entries.contains_key(key)
203 }
204
205 pub fn insert(&mut self, key: impl Into<String>, value: Value) -> Option<Value> {
208 let key = key.into();
209 let entries = Arc::make_mut(&mut self.entries);
210 if let Some(slot) = entries.get_mut(&key) {
211 return Some(std::mem::replace(slot, value));
212 }
213 if let Some(n) = array_index(&key) {
214 let at = entries
215 .keys()
216 .take(self.integer_keys)
217 .position(|k| array_index(k).is_some_and(|m| m > n));
218 let at = at.unwrap_or(self.integer_keys);
219 entries.insert_at(at, key, value);
220 self.integer_keys += 1;
221 } else {
222 entries.insert(key, value);
223 }
224 None
225 }
226
227 pub fn remove(&mut self, key: &str) -> Option<Value> {
229 if !self.entries.contains_key(key) {
230 return None;
231 }
232 let (i, value) = Arc::make_mut(&mut self.entries).remove_full(key)?;
233 if i < self.integer_keys {
234 self.integer_keys -= 1;
235 }
236 Some(value)
237 }
238
239 pub fn iter(&self) -> map::Iter<'_, Value> {
241 self.entries.iter()
242 }
243
244 pub fn keys(&self) -> impl DoubleEndedIterator<Item = &String> + ExactSizeIterator + Clone {
245 self.entries.keys()
246 }
247
248 pub fn values(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator + Clone {
249 self.entries.values()
250 }
251
252 pub fn get_index(&self, index: usize) -> Option<(&String, &Value)> {
254 self.entries.get_index(index)
255 }
256}
257
258impl PartialEq for Object {
259 fn eq(&self, other: &Self) -> bool {
260 Arc::ptr_eq(&self.entries, &other.entries) || self.entries == other.entries
261 }
262}
263
264impl fmt::Debug for Object {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.debug_map().entries(self.entries.iter()).finish()
267 }
268}
269
270impl<'a> IntoIterator for &'a Object {
271 type Item = (&'a String, &'a Value);
272 type IntoIter = map::Iter<'a, Value>;
273 fn into_iter(self) -> Self::IntoIter {
274 self.entries.iter()
275 }
276}
277
278impl IntoIterator for Object {
279 type Item = (String, Value);
280 type IntoIter = map::IntoIter<Value>;
281 fn into_iter(self) -> Self::IntoIter {
282 Arc::unwrap_or_clone(self.entries).into_iter()
283 }
284}
285
286impl<K: Into<String>> FromIterator<(K, Value)> for Object {
287 fn from_iter<I: IntoIterator<Item = (K, Value)>>(iter: I) -> Self {
290 let mut o = Object::new();
291 for (k, v) in iter {
292 o.insert(k, v);
293 }
294 o
295 }
296}
297
298pub(crate) fn array_index(key: &str) -> Option<u32> {
301 let bytes = key.as_bytes();
302 let (&first, rest) = bytes.split_first()?;
303 if !first.is_ascii_digit() || bytes.len() > 10 || (first == b'0' && !rest.is_empty()) {
304 return None;
305 }
306 let mut n = u64::from(first - b'0');
307 for &c in rest {
308 if !c.is_ascii_digit() {
309 return None;
310 }
311 n = n * 10 + u64::from(c - b'0');
312 }
313 (n < 0xFFFF_FFFF).then_some(n as u32)
314}
315
316#[macro_export]
319macro_rules! json {
320 (null) => { $crate::json::Value::Null };
321 ([ $($e:tt),* $(,)? ]) => { $crate::json::Value::Array(vec![ $( $crate::json!($e) ),* ]) };
322 ({ $($k:literal : $v:tt),* $(,)? }) => {{
323 #[allow(unused_mut)]
324 let mut o = $crate::json::Object::new();
325 $( o.insert($k, $crate::json!($v)); )*
326 $crate::json::Value::Object(o)
327 }};
328 ($e:expr) => { $crate::json::Value::from($e) };
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 #[test]
336 fn keys_follow_js_property_order() {
337 let mut o = Object::new();
338 for k in ["b", "10", "a", "2", "01", "4294967295", "4294967294", "0"] {
339 o.insert(k, Value::Null);
340 }
341 let keys: Vec<_> = o.keys().map(String::as_str).collect();
342 assert_eq!(
343 keys,
344 ["0", "2", "10", "4294967294", "b", "a", "01", "4294967295"]
345 );
346 o.remove("2");
347 o.insert("3", Value::Null);
348 let keys: Vec<_> = o.keys().map(String::as_str).collect();
349 assert_eq!(
350 keys,
351 ["0", "3", "10", "4294967294", "b", "a", "01", "4294967295"]
352 );
353 }
354
355 #[test]
356 fn a_change_to_a_copy_leaves_the_original() {
357 let mut original = Object::new();
358 original.insert("a", Value::from(1.0));
359 original.insert("b", Value::from(2.0));
360 let changes: [fn(&mut Object); 4] = [
361 |o| _ = o.insert("a", Value::from(9.0)),
362 |o| _ = o.insert("1", Value::Null),
363 |o| _ = o.remove("b"),
364 |o| *o.get_mut("a").unwrap() = Value::Null,
365 ];
366 for change in changes {
367 let mut copy = original.clone();
368 change(&mut copy);
369 assert_ne!(copy, original);
370 let keys: Vec<_> = original.iter().collect();
371 assert_eq!(
372 keys,
373 [
374 (&"a".to_owned(), &Value::from(1.0)),
375 (&"b".to_owned(), &Value::from(2.0))
376 ]
377 );
378 assert_eq!(original.integer_keys, 0);
379 }
380 }
381}