jsonx_lib/object.rs
1//! JSON objects.
2
3use alloc::{borrow::Cow, vec, vec::Vec};
4use core::{fmt, iter::FusedIterator, ops::Index, slice};
5
6use crate::{Value, tree, tree::Member};
7
8/// A JSON object: its members in document order.
9///
10/// Members are kept in a vector, in the order they were read or added, so a
11/// document is written back with its keys where they were. Lookup by key is a
12/// linear scan, which beats hashing for the small objects JSON documents are
13/// mostly made of; for a large object read once, iterate it instead of
14/// looking each key up.
15///
16/// Whether a parsed object can hold a key twice is up to the
17/// [`DuplicateKeys`](crate::DuplicateKeys) policy the parser used (by default
18/// a duplicate is an error). An object built in code can: [`insert`](Self::insert)
19/// replaces an existing member, [`push`](Self::push) always appends.
20///
21/// # Examples
22///
23/// ```
24/// use jsonx_lib::{parse, Object, Value};
25///
26/// let doc = parse(r#"{"name": "jsonx", "tags": ["json"]}"#)?;
27/// let obj: &Object = doc.as_object().unwrap();
28/// assert_eq!(obj.get("name").and_then(Value::as_str), Some("jsonx"));
29/// assert_eq!(obj.keys().collect::<Vec<_>>(), ["name", "tags"]);
30///
31/// let mut built = Object::new();
32/// built.insert("b", 1);
33/// built.insert("a", true);
34/// built.insert("b", 2); // replaces in place
35/// assert_eq!(Value::Object(built).to_string(), r#"{"b":2,"a":true}"#);
36/// # Ok::<(), jsonx_lib::Error>(())
37/// ```
38#[derive(Default)]
39pub struct Object<'a> {
40 members: Vec<Member<'a>>,
41}
42
43impl<'a> Object<'a> {
44 /// An empty object. Does not allocate.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// assert!(jsonx_lib::Object::new().is_empty());
50 /// ```
51 #[inline]
52 #[must_use]
53 pub const fn new() -> Self {
54 Self {
55 members: Vec::new(),
56 }
57 }
58
59 /// An empty object with room for `capacity` members.
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// let mut o = jsonx_lib::Object::with_capacity(2);
65 /// o.push("k", "v");
66 /// assert_eq!(o.len(), 1);
67 /// ```
68 #[inline]
69 #[must_use]
70 pub fn with_capacity(capacity: usize) -> Self {
71 Self {
72 members: Vec::with_capacity(capacity),
73 }
74 }
75
76 /// The number of members.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// let doc = jsonx_lib::parse(r#"{"a": 1, "b": 2}"#)?;
82 /// assert_eq!(doc.as_object().map(|o| o.len()), Some(2));
83 /// # Ok::<(), jsonx_lib::Error>(())
84 /// ```
85 #[inline]
86 #[must_use]
87 pub fn len(&self) -> usize {
88 self.members.len()
89 }
90
91 /// Whether the object has no members.
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// let doc = jsonx_lib::parse("{}")?;
97 /// assert!(doc.as_object().is_some_and(|o| o.is_empty()));
98 /// # Ok::<(), jsonx_lib::Error>(())
99 /// ```
100 #[inline]
101 #[must_use]
102 pub fn is_empty(&self) -> bool {
103 self.members.is_empty()
104 }
105
106 /// The value of the first member named `key`.
107 ///
108 /// # Examples
109 ///
110 /// ```
111 /// let doc = jsonx_lib::parse(r#"{"id": 7}"#)?;
112 /// let obj = doc.as_object().unwrap();
113 /// assert_eq!(obj.get("id").and_then(|v| v.as_u64()), Some(7));
114 /// assert!(obj.get("missing").is_none());
115 /// # Ok::<(), jsonx_lib::Error>(())
116 /// ```
117 #[must_use]
118 pub fn get(&self, key: &str) -> Option<&Value<'a>> {
119 self.members.iter().find(|(k, _)| k == key).map(|(_, v)| v)
120 }
121
122 /// A mutable reference to the value of the first member named `key`.
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// use jsonx_lib::{json, Value};
128 ///
129 /// let mut v = json!({ "n": 1 });
130 /// if let Some(n) = v.as_object_mut().and_then(|o| o.get_mut("n")) {
131 /// *n = Value::from(2);
132 /// }
133 /// assert_eq!(v["n"], 2);
134 /// ```
135 #[must_use]
136 pub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'a>> {
137 self.members
138 .iter_mut()
139 .find(|(k, _)| k == key)
140 .map(|(_, v)| v)
141 }
142
143 /// Whether a member is named `key`.
144 ///
145 /// # Examples
146 ///
147 /// ```
148 /// let doc = jsonx_lib::parse(r#"{"a": null}"#)?;
149 /// assert!(doc.as_object().is_some_and(|o| o.contains_key("a")));
150 /// # Ok::<(), jsonx_lib::Error>(())
151 /// ```
152 #[must_use]
153 pub fn contains_key(&self, key: &str) -> bool {
154 self.members.iter().any(|(k, _)| k == key)
155 }
156
157 /// Sets the member named `key` to `value`, as a map would: an existing
158 /// member keeps its position and its old value is returned; otherwise the
159 /// member is appended and `None` is returned.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use jsonx_lib::Object;
165 ///
166 /// let mut o = Object::new();
167 /// assert_eq!(o.insert("a", 1), None);
168 /// assert_eq!(o.insert("a", 2), Some(1.into()));
169 /// assert_eq!(o.len(), 1);
170 /// ```
171 pub fn insert(
172 &mut self,
173 key: impl Into<Cow<'a, str>>,
174 value: impl Into<Value<'a>>,
175 ) -> Option<Value<'a>> {
176 let key = key.into();
177 let value = value.into();
178 match self.get_mut(&key) {
179 Some(slot) => Some(core::mem::replace(slot, value)),
180 None => {
181 self.members.push((key, value));
182 None
183 }
184 }
185 }
186
187 /// Appends a member without looking for an existing one with the same
188 /// key. Constant time; the writer then emits both members. Use
189 /// [`insert`](Self::insert) for map semantics.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use jsonx_lib::{Object, Value};
195 ///
196 /// let mut o = Object::new();
197 /// o.push("k", 1);
198 /// o.push("k", 2);
199 /// assert_eq!(Value::Object(o).to_string(), r#"{"k":1,"k":2}"#);
200 /// ```
201 pub fn push(&mut self, key: impl Into<Cow<'a, str>>, value: impl Into<Value<'a>>) {
202 self.members.push((key.into(), value.into()));
203 }
204
205 /// Removes the first member named `key` and returns its value. The other
206 /// members keep their order.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use jsonx_lib::json;
212 ///
213 /// let mut v = json!({ "a": 1, "b": 2, "c": 3 });
214 /// let obj = v.as_object_mut().unwrap();
215 /// assert_eq!(obj.remove("b"), Some(2.into()));
216 /// assert_eq!(obj.keys().collect::<Vec<_>>(), ["a", "c"]);
217 /// ```
218 pub fn remove(&mut self, key: &str) -> Option<Value<'a>> {
219 let at = self.members.iter().position(|(k, _)| k == key)?;
220 Some(self.members.remove(at).1)
221 }
222
223 /// Iterates over the members as `(key, value)` pairs, in order.
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// let doc = jsonx_lib::parse(r#"{"x": 1, "y": 2}"#)?;
229 /// let sum: i64 = doc.as_object().unwrap().iter().filter_map(|(_, v)| v.as_i64()).sum();
230 /// assert_eq!(sum, 3);
231 /// # Ok::<(), jsonx_lib::Error>(())
232 /// ```
233 #[inline]
234 pub fn iter(&self) -> Iter<'_, 'a> {
235 Iter {
236 inner: self.members.iter(),
237 }
238 }
239
240 /// Iterates over the members with mutable values, in order.
241 ///
242 /// # Examples
243 ///
244 /// ```
245 /// use jsonx_lib::{json, Value};
246 ///
247 /// let mut v = json!({ "a": 1, "b": 2 });
248 /// for (_, value) in v.as_object_mut().unwrap().iter_mut() {
249 /// *value = Value::Null;
250 /// }
251 /// assert_eq!(v.to_string(), r#"{"a":null,"b":null}"#);
252 /// ```
253 #[inline]
254 pub fn iter_mut(&mut self) -> IterMut<'_, 'a> {
255 IterMut {
256 inner: self.members.iter_mut(),
257 }
258 }
259
260 /// The keys, in order.
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// let doc = jsonx_lib::parse(r#"{"b": 1, "a": 2}"#)?;
266 /// assert_eq!(doc.as_object().unwrap().keys().collect::<Vec<_>>(), ["b", "a"]);
267 /// # Ok::<(), jsonx_lib::Error>(())
268 /// ```
269 pub fn keys(&self) -> impl DoubleEndedIterator<Item = &str> + ExactSizeIterator {
270 self.members.iter().map(|(k, _)| k.as_ref())
271 }
272
273 /// The values, in order.
274 ///
275 /// # Examples
276 ///
277 /// ```
278 /// let doc = jsonx_lib::parse(r#"{"b": 1, "a": 2}"#)?;
279 /// let values: Vec<_> = doc.as_object().unwrap().values().filter_map(|v| v.as_i64()).collect();
280 /// assert_eq!(values, [1, 2]);
281 /// # Ok::<(), jsonx_lib::Error>(())
282 /// ```
283 pub fn values(&self) -> impl DoubleEndedIterator<Item = &Value<'a>> + ExactSizeIterator {
284 self.members.iter().map(|(_, v)| v)
285 }
286
287 /// The members as a slice of `(key, value)` pairs.
288 ///
289 /// # Examples
290 ///
291 /// ```
292 /// let doc = jsonx_lib::parse(r#"{"k": "v"}"#)?;
293 /// let (key, value) = &doc.as_object().unwrap().as_slice()[0];
294 /// assert_eq!((key.as_ref(), value.as_str()), ("k", Some("v")));
295 /// # Ok::<(), jsonx_lib::Error>(())
296 /// ```
297 #[inline]
298 #[must_use]
299 pub fn as_slice(&self) -> &[(Cow<'a, str>, Value<'a>)] {
300 &self.members
301 }
302
303 /// Takes the members out as a `Vec` of `(key, value)` pairs.
304 ///
305 /// # Examples
306 ///
307 /// ```
308 /// use jsonx_lib::json;
309 ///
310 /// let v = json!({ "a": 1 });
311 /// let members = v.as_object().cloned().unwrap_or_default().into_vec();
312 /// assert_eq!(members[0].0, "a");
313 /// ```
314 #[inline]
315 #[must_use]
316 pub fn into_vec(mut self) -> Vec<(Cow<'a, str>, Value<'a>)> {
317 core::mem::take(&mut self.members)
318 }
319
320 /// Copies every borrowed key and string so the object no longer borrows
321 /// from the input. Iterative at any depth.
322 ///
323 /// # Examples
324 ///
325 /// ```
326 /// use jsonx_lib::{parse, Object};
327 ///
328 /// let owned: Object<'static> = {
329 /// let text = String::from(r#"{"k": "v"}"#);
330 /// parse(&text)?.as_object().cloned().unwrap_or_default().into_owned()
331 /// };
332 /// assert_eq!(owned["k"], "v");
333 /// # Ok::<(), jsonx_lib::Error>(())
334 /// ```
335 #[must_use]
336 pub fn into_owned(self) -> Object<'static> {
337 match tree::into_owned(Value::Object(self)) {
338 Value::Object(o) => o,
339 _ => Object::new(),
340 }
341 }
342
343 #[inline]
344 pub(crate) fn members_mut(&mut self) -> &mut Vec<Member<'a>> {
345 &mut self.members
346 }
347}
348
349impl Drop for Object<'_> {
350 fn drop(&mut self) {
351 tree::drop_members(&mut self.members);
352 }
353}
354
355impl Clone for Object<'_> {
356 fn clone(&self) -> Self {
357 Self {
358 members: tree::clone_members(&self.members),
359 }
360 }
361}
362
363impl PartialEq for Object<'_> {
364 /// Members are compared in order: `{"a":1,"b":2}` and `{"b":2,"a":1}` are
365 /// different documents and compare unequal.
366 fn eq(&self, other: &Self) -> bool {
367 self.members.len() == other.members.len()
368 && self
369 .members
370 .iter()
371 .zip(&other.members)
372 .all(|((ka, va), (kb, vb))| ka == kb && tree::eq(va, vb))
373 }
374}
375
376impl Eq for Object<'_> {}
377
378impl fmt::Debug for Object<'_> {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 f.debug_map().entries(self.iter()).finish()
381 }
382}
383
384impl<'a> From<Vec<(Cow<'a, str>, Value<'a>)>> for Object<'a> {
385 /// Wraps the members as given; duplicates are kept.
386 #[inline]
387 fn from(members: Vec<(Cow<'a, str>, Value<'a>)>) -> Self {
388 Self { members }
389 }
390}
391
392impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> FromIterator<(K, V)> for Object<'a> {
393 /// Appends the members in order, as [`push`](Object::push) does;
394 /// duplicates are kept.
395 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
396 Self {
397 members: iter
398 .into_iter()
399 .map(|(k, v)| (k.into(), v.into()))
400 .collect(),
401 }
402 }
403}
404
405impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> Extend<(K, V)> for Object<'a> {
406 /// Appends the members in order, as [`push`](Object::push) does.
407 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
408 self.members
409 .extend(iter.into_iter().map(|(k, v)| (k.into(), v.into())));
410 }
411}
412
413impl<'a> Index<&str> for Object<'a> {
414 type Output = Value<'a>;
415
416 /// The value of the first member named `key`, or `null` if there is none.
417 fn index(&self, key: &str) -> &Value<'a> {
418 self.get(key).unwrap_or(&crate::value::NULL)
419 }
420}
421
422impl<'a> IntoIterator for Object<'a> {
423 type Item = (Cow<'a, str>, Value<'a>);
424 type IntoIter = vec::IntoIter<(Cow<'a, str>, Value<'a>)>;
425
426 #[inline]
427 fn into_iter(self) -> Self::IntoIter {
428 self.into_vec().into_iter()
429 }
430}
431
432impl<'r, 'a> IntoIterator for &'r Object<'a> {
433 type Item = (&'r str, &'r Value<'a>);
434 type IntoIter = Iter<'r, 'a>;
435
436 #[inline]
437 fn into_iter(self) -> Self::IntoIter {
438 self.iter()
439 }
440}
441
442impl<'r, 'a> IntoIterator for &'r mut Object<'a> {
443 type Item = (&'r str, &'r mut Value<'a>);
444 type IntoIter = IterMut<'r, 'a>;
445
446 #[inline]
447 fn into_iter(self) -> Self::IntoIter {
448 self.iter_mut()
449 }
450}
451
452/// An iterator over an [`Object`]'s members, from [`Object::iter`].
453///
454/// # Examples
455///
456/// ```
457/// let doc = jsonx_lib::parse(r#"{"a": 1}"#)?;
458/// let mut it = doc.as_object().unwrap().iter();
459/// assert_eq!(it.next().map(|(k, _)| k), Some("a"));
460/// assert!(it.next().is_none());
461/// # Ok::<(), jsonx_lib::Error>(())
462/// ```
463#[derive(Clone, Debug)]
464pub struct Iter<'r, 'a> {
465 inner: slice::Iter<'r, Member<'a>>,
466}
467
468impl<'r, 'a> Iterator for Iter<'r, 'a> {
469 type Item = (&'r str, &'r Value<'a>);
470
471 #[inline]
472 fn next(&mut self) -> Option<Self::Item> {
473 self.inner.next().map(|(k, v)| (k.as_ref(), v))
474 }
475
476 #[inline]
477 fn size_hint(&self) -> (usize, Option<usize>) {
478 self.inner.size_hint()
479 }
480}
481
482impl DoubleEndedIterator for Iter<'_, '_> {
483 #[inline]
484 fn next_back(&mut self) -> Option<Self::Item> {
485 self.inner.next_back().map(|(k, v)| (k.as_ref(), v))
486 }
487}
488
489impl ExactSizeIterator for Iter<'_, '_> {}
490impl FusedIterator for Iter<'_, '_> {}
491
492/// An iterator over an [`Object`]'s members with mutable values, from
493/// [`Object::iter_mut`].
494///
495/// # Examples
496///
497/// ```
498/// use jsonx_lib::json;
499///
500/// let mut v = json!({ "a": 1 });
501/// let mut it = v.as_object_mut().unwrap().iter_mut();
502/// assert_eq!(it.next().map(|(k, _)| k), Some("a"));
503/// ```
504#[derive(Debug)]
505pub struct IterMut<'r, 'a> {
506 inner: slice::IterMut<'r, Member<'a>>,
507}
508
509impl<'r, 'a> Iterator for IterMut<'r, 'a> {
510 type Item = (&'r str, &'r mut Value<'a>);
511
512 #[inline]
513 fn next(&mut self) -> Option<Self::Item> {
514 self.inner.next().map(split_mut)
515 }
516
517 #[inline]
518 fn size_hint(&self) -> (usize, Option<usize>) {
519 self.inner.size_hint()
520 }
521}
522
523impl DoubleEndedIterator for IterMut<'_, '_> {
524 #[inline]
525 fn next_back(&mut self) -> Option<Self::Item> {
526 self.inner.next_back().map(split_mut)
527 }
528}
529
530/// A member as a shared key and a mutable value.
531#[inline]
532fn split_mut<'r, 'a>(member: &'r mut Member<'a>) -> (&'r str, &'r mut Value<'a>) {
533 let (key, value) = member;
534 let key: &'r Cow<'a, str> = key;
535 (key, value)
536}
537
538impl ExactSizeIterator for IterMut<'_, '_> {}
539impl FusedIterator for IterMut<'_, '_> {}