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