Skip to main content

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    /// The existing member is found by a linear scan, so building an object
162    /// of `n` members with `insert` costs `O(n^2)` comparisons. For a large
163    /// object whose keys you know to be distinct, use [`push`](Self::push),
164    /// or collect the members with [`FromIterator`].
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use jsonx_lib::Object;
170    ///
171    /// let mut o = Object::new();
172    /// assert_eq!(o.insert("a", 1), None);
173    /// assert_eq!(o.insert("a", 2), Some(1.into()));
174    /// assert_eq!(o.len(), 1);
175    /// ```
176    pub fn insert(
177        &mut self,
178        key: impl Into<Cow<'a, str>>,
179        value: impl Into<Value<'a>>,
180    ) -> Option<Value<'a>> {
181        let key = key.into();
182        let value = value.into();
183        match self.get_mut(&key) {
184            Some(slot) => Some(core::mem::replace(slot, value)),
185            None => {
186                self.members.push((key, value));
187                None
188            }
189        }
190    }
191
192    /// Appends a member without looking for an existing one with the same
193    /// key. Constant time; the writer then emits both members. Use
194    /// [`insert`](Self::insert) for map semantics.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use jsonx_lib::{Object, Value};
200    ///
201    /// let mut o = Object::new();
202    /// o.push("k", 1);
203    /// o.push("k", 2);
204    /// assert_eq!(Value::Object(o).to_string(), r#"{"k":1,"k":2}"#);
205    /// ```
206    pub fn push(&mut self, key: impl Into<Cow<'a, str>>, value: impl Into<Value<'a>>) {
207        self.members.push((key.into(), value.into()));
208    }
209
210    /// Removes the first member named `key` and returns its value. The other
211    /// members keep their order.
212    ///
213    /// # Examples
214    ///
215    /// ```
216    /// use jsonx_lib::json;
217    ///
218    /// let mut v = json!({ "a": 1, "b": 2, "c": 3 });
219    /// let obj = v.as_object_mut().unwrap();
220    /// assert_eq!(obj.remove("b"), Some(2.into()));
221    /// assert_eq!(obj.keys().collect::<Vec<_>>(), ["a", "c"]);
222    /// ```
223    pub fn remove(&mut self, key: &str) -> Option<Value<'a>> {
224        let at = self.members.iter().position(|(k, _)| k == key)?;
225        Some(self.members.remove(at).1)
226    }
227
228    /// Keeps only the members for which `keep` returns `true`, in order;
229    /// `keep` may change the values it keeps.
230    ///
231    /// # Examples
232    ///
233    /// ```
234    /// let mut v = jsonx_lib::json!({ "a": 1, "b": null, "c": 3 });
235    /// v.as_object_mut().unwrap().retain(|_, value| !value.is_null());
236    /// assert_eq!(v.to_string(), r#"{"a":1,"c":3}"#);
237    /// ```
238    pub fn retain(&mut self, mut keep: impl FnMut(&str, &mut Value<'a>) -> bool) {
239        self.members.retain_mut(|(key, value)| keep(key, value));
240    }
241
242    /// Sorts the members by key (byte order; members with equal keys keep
243    /// their order), for output that does not depend on how the object was
244    /// built.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// let mut v = jsonx_lib::json!({ "b": 1, "a": 2 });
250    /// v.as_object_mut().unwrap().sort_keys();
251    /// assert_eq!(v.to_string(), r#"{"a":2,"b":1}"#);
252    /// ```
253    pub fn sort_keys(&mut self) {
254        self.members.sort_by(|(a, _), (b, _)| a.cmp(b));
255    }
256
257    /// The member named `key`, to read, change, or insert in one lookup (a
258    /// linear scan, as for [`insert`](Self::insert)).
259    ///
260    /// # Examples
261    ///
262    /// ```
263    /// use jsonx_lib::{json, Value};
264    ///
265    /// let mut v = json!({ "hits": 1 });
266    /// let obj = v.as_object_mut().unwrap();
267    /// for key in ["hits", "misses", "hits"] {
268    ///     let count = obj.entry(key).or_insert(0);
269    ///     *count = Value::from(count.as_i64().unwrap_or(0) + 1);
270    /// }
271    /// assert_eq!(v.to_string(), r#"{"hits":3,"misses":1}"#);
272    /// ```
273    pub fn entry(&mut self, key: impl Into<Cow<'a, str>>) -> Entry<'_, 'a> {
274        let key = key.into();
275        match self.members.iter().position(|(k, _)| *k == key) {
276            Some(index) => Entry::Occupied(OccupiedEntry {
277                object: self,
278                index,
279            }),
280            None => Entry::Vacant(VacantEntry { object: self, key }),
281        }
282    }
283
284    /// Iterates over the members as `(key, value)` pairs, in order.
285    ///
286    /// # Examples
287    ///
288    /// ```
289    /// let doc = jsonx_lib::parse(r#"{"x": 1, "y": 2}"#)?;
290    /// let sum: i64 = doc.as_object().unwrap().iter().filter_map(|(_, v)| v.as_i64()).sum();
291    /// assert_eq!(sum, 3);
292    /// # Ok::<(), jsonx_lib::Error>(())
293    /// ```
294    #[inline]
295    pub fn iter(&self) -> Iter<'_, 'a> {
296        Iter {
297            inner: self.members.iter(),
298        }
299    }
300
301    /// Iterates over the members with mutable values, in order.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// use jsonx_lib::{json, Value};
307    ///
308    /// let mut v = json!({ "a": 1, "b": 2 });
309    /// for (_, value) in v.as_object_mut().unwrap().iter_mut() {
310    ///     *value = Value::Null;
311    /// }
312    /// assert_eq!(v.to_string(), r#"{"a":null,"b":null}"#);
313    /// ```
314    #[inline]
315    pub fn iter_mut(&mut self) -> IterMut<'_, 'a> {
316        IterMut {
317            inner: self.members.iter_mut(),
318        }
319    }
320
321    /// The keys, in order.
322    ///
323    /// # Examples
324    ///
325    /// ```
326    /// let doc = jsonx_lib::parse(r#"{"b": 1, "a": 2}"#)?;
327    /// assert_eq!(doc.as_object().unwrap().keys().collect::<Vec<_>>(), ["b", "a"]);
328    /// # Ok::<(), jsonx_lib::Error>(())
329    /// ```
330    pub fn keys(&self) -> impl DoubleEndedIterator<Item = &str> + ExactSizeIterator {
331        self.members.iter().map(|(k, _)| k.as_ref())
332    }
333
334    /// The values, in order.
335    ///
336    /// # Examples
337    ///
338    /// ```
339    /// let doc = jsonx_lib::parse(r#"{"b": 1, "a": 2}"#)?;
340    /// let values: Vec<_> = doc.as_object().unwrap().values().filter_map(|v| v.as_i64()).collect();
341    /// assert_eq!(values, [1, 2]);
342    /// # Ok::<(), jsonx_lib::Error>(())
343    /// ```
344    pub fn values(&self) -> impl DoubleEndedIterator<Item = &Value<'a>> + ExactSizeIterator {
345        self.members.iter().map(|(_, v)| v)
346    }
347
348    /// The members as a slice of `(key, value)` pairs.
349    ///
350    /// # Examples
351    ///
352    /// ```
353    /// let doc = jsonx_lib::parse(r#"{"k": "v"}"#)?;
354    /// let (key, value) = &doc.as_object().unwrap().as_slice()[0];
355    /// assert_eq!((key.as_ref(), value.as_str()), ("k", Some("v")));
356    /// # Ok::<(), jsonx_lib::Error>(())
357    /// ```
358    #[inline]
359    #[must_use]
360    pub fn as_slice(&self) -> &[(Cow<'a, str>, Value<'a>)] {
361        &self.members
362    }
363
364    /// Takes the members out as a `Vec` of `(key, value)` pairs.
365    ///
366    /// # Examples
367    ///
368    /// ```
369    /// use jsonx_lib::json;
370    ///
371    /// let v = json!({ "a": 1 });
372    /// let members = v.as_object().cloned().unwrap_or_default().into_vec();
373    /// assert_eq!(members[0].0, "a");
374    /// ```
375    #[inline]
376    #[must_use]
377    pub fn into_vec(mut self) -> Vec<(Cow<'a, str>, Value<'a>)> {
378        core::mem::take(&mut self.members)
379    }
380
381    /// Copies every borrowed key and string so the object no longer borrows
382    /// from the input. Iterative at any depth.
383    ///
384    /// # Examples
385    ///
386    /// ```
387    /// use jsonx_lib::{parse, Object};
388    ///
389    /// let owned: Object<'static> = {
390    ///     let text = String::from(r#"{"k": "v"}"#);
391    ///     parse(&text)?.as_object().cloned().unwrap_or_default().into_owned()
392    /// };
393    /// assert_eq!(owned["k"], "v");
394    /// # Ok::<(), jsonx_lib::Error>(())
395    /// ```
396    #[must_use]
397    pub fn into_owned(self) -> Object<'static> {
398        match tree::into_owned(Value::Object(self)) {
399            Value::Object(o) => o,
400            _ => Object::new(),
401        }
402    }
403
404    /// The value of the member at `index`. Only the entry API calls this,
405    /// with an index it just found or pushed while it holds the object
406    /// exclusively, so the index is always in bounds.
407    #[allow(clippy::indexing_slicing)]
408    fn member_value(&mut self, index: usize) -> &mut Value<'a> {
409        &mut self.members[index].1
410    }
411
412    #[inline]
413    pub(crate) fn members_mut(&mut self) -> &mut Vec<Member<'a>> {
414        &mut self.members
415    }
416}
417
418impl Drop for Object<'_> {
419    fn drop(&mut self) {
420        tree::drop_members(&mut self.members);
421    }
422}
423
424impl Clone for Object<'_> {
425    fn clone(&self) -> Self {
426        Self {
427            members: tree::clone_members(&self.members),
428        }
429    }
430}
431
432impl PartialEq for Object<'_> {
433    /// Members are compared in order: `{"a":1,"b":2}` and `{"b":2,"a":1}` are
434    /// different documents and compare unequal.
435    fn eq(&self, other: &Self) -> bool {
436        self.members.len() == other.members.len()
437            && self
438                .members
439                .iter()
440                .zip(&other.members)
441                .all(|((ka, va), (kb, vb))| ka == kb && tree::eq(va, vb))
442    }
443}
444
445impl Eq for Object<'_> {}
446
447impl core::hash::Hash for Object<'_> {
448    /// Hashes as the [`Value::Object`] it would be: consistent with `==`.
449    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
450        self.len().hash(state);
451        for (key, value) in self {
452            key.hash(state);
453            value.hash(state);
454        }
455    }
456}
457
458/// One member of an [`Object`], there or not; from [`Object::entry`].
459#[derive(Debug)]
460pub enum Entry<'o, 'a> {
461    /// The object has a member with the key (the first, if several).
462    Occupied(OccupiedEntry<'o, 'a>),
463    /// It does not.
464    Vacant(VacantEntry<'o, 'a>),
465}
466
467impl<'o, 'a> Entry<'o, 'a> {
468    /// The member's value, inserting `default` first if it is missing.
469    ///
470    /// # Examples
471    ///
472    /// ```
473    /// let mut o = jsonx_lib::Object::new();
474    /// o.entry("list").or_insert(jsonx_lib::json!([])).as_array_mut().unwrap().push(1.into());
475    /// assert_eq!(o["list"][0], 1);
476    /// ```
477    pub fn or_insert(self, default: impl Into<Value<'a>>) -> &'o mut Value<'a> {
478        match self {
479            Self::Occupied(entry) => entry.into_mut(),
480            Self::Vacant(entry) => entry.insert(default),
481        }
482    }
483
484    /// The member's value, inserting what `default` makes first if it is
485    /// missing.
486    ///
487    /// # Examples
488    ///
489    /// ```
490    /// let mut o = jsonx_lib::Object::new();
491    /// assert!(o.entry("k").or_insert_with(|| "made".into()) == "made");
492    /// ```
493    pub fn or_insert_with(self, default: impl FnOnce() -> Value<'a>) -> &'o mut Value<'a> {
494        match self {
495            Self::Occupied(entry) => entry.into_mut(),
496            Self::Vacant(entry) => entry.insert(default()),
497        }
498    }
499
500    /// The member's value, inserting `null` first if it is missing.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// let mut o = jsonx_lib::Object::new();
506    /// assert!(o.entry("k").or_default().is_null());
507    /// assert_eq!(o.len(), 1);
508    /// ```
509    pub fn or_default(self) -> &'o mut Value<'a> {
510        self.or_insert(Value::Null)
511    }
512
513    /// Runs `change` on the value if the member is there.
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// let mut v = jsonx_lib::json!({ "n": 1 });
519    /// let o = v.as_object_mut().unwrap();
520    /// o.entry("n").and_modify(|n| *n = 2.into()).or_insert(0);
521    /// o.entry("m").and_modify(|n| *n = 2.into()).or_insert(0);
522    /// assert_eq!(v.to_string(), r#"{"n":2,"m":0}"#);
523    /// ```
524    #[must_use]
525    pub fn and_modify(self, change: impl FnOnce(&mut Value<'a>)) -> Self {
526        match self {
527            Self::Occupied(mut entry) => {
528                change(entry.get_mut());
529                Self::Occupied(entry)
530            }
531            vacant @ Self::Vacant(_) => vacant,
532        }
533    }
534
535    /// The member's key.
536    ///
537    /// # Examples
538    ///
539    /// ```
540    /// assert_eq!(jsonx_lib::Object::new().entry("k").key(), "k");
541    /// ```
542    #[must_use]
543    pub fn key(&self) -> &str {
544        match self {
545            Self::Occupied(entry) => entry.key(),
546            Self::Vacant(entry) => &entry.key,
547        }
548    }
549}
550
551/// A member that is there; see [`Entry`].
552#[derive(Debug)]
553pub struct OccupiedEntry<'o, 'a> {
554    object: &'o mut Object<'a>,
555    index: usize,
556}
557
558impl<'o, 'a> OccupiedEntry<'o, 'a> {
559    /// The key.
560    #[must_use]
561    pub fn key(&self) -> &str {
562        self.object.members.get(self.index).map_or("", |(k, _)| k)
563    }
564
565    /// The value.
566    #[must_use]
567    pub fn get(&self) -> &Value<'a> {
568        self.object
569            .members
570            .get(self.index)
571            .map_or(&crate::value::NULL, |(_, v)| v)
572    }
573
574    /// The value, mutably.
575    pub fn get_mut(&mut self) -> &mut Value<'a> {
576        let index = self.index;
577        self.object.member_value(index)
578    }
579
580    /// The value, mutably, for as long as the object is borrowed.
581    pub fn into_mut(self) -> &'o mut Value<'a> {
582        self.object.member_value(self.index)
583    }
584
585    /// Replaces the value and returns the old one.
586    pub fn insert(&mut self, value: impl Into<Value<'a>>) -> Value<'a> {
587        core::mem::replace(self.get_mut(), value.into())
588    }
589
590    /// Removes the member, keeping the others' order, and returns its value.
591    ///
592    /// # Examples
593    ///
594    /// ```
595    /// use jsonx_lib::Entry;
596    ///
597    /// let mut v = jsonx_lib::json!({ "a": 1, "b": 2 });
598    /// if let Entry::Occupied(e) = v.as_object_mut().unwrap().entry("a") {
599    ///     assert_eq!(e.remove(), 1);
600    /// }
601    /// assert_eq!(v.to_string(), r#"{"b":2}"#);
602    /// ```
603    pub fn remove(self) -> Value<'a> {
604        if self.index < self.object.members.len() {
605            self.object.members.remove(self.index).1
606        } else {
607            Value::Null
608        }
609    }
610}
611
612/// A member that is not there; see [`Entry`].
613#[derive(Debug)]
614pub struct VacantEntry<'o, 'a> {
615    object: &'o mut Object<'a>,
616    key: Cow<'a, str>,
617}
618
619impl<'o, 'a> VacantEntry<'o, 'a> {
620    /// The key.
621    #[must_use]
622    pub fn key(&self) -> &str {
623        &self.key
624    }
625
626    /// Appends the member and returns its value.
627    pub fn insert(self, value: impl Into<Value<'a>>) -> &'o mut Value<'a> {
628        let index = self.object.members.len();
629        self.object.members.push((self.key, value.into()));
630        self.object.member_value(index)
631    }
632}
633
634impl fmt::Debug for Object<'_> {
635    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636        f.debug_map().entries(self.iter()).finish()
637    }
638}
639
640impl<'a> From<Vec<(Cow<'a, str>, Value<'a>)>> for Object<'a> {
641    /// Wraps the members as given; duplicates are kept.
642    #[inline]
643    fn from(members: Vec<(Cow<'a, str>, Value<'a>)>) -> Self {
644        Self { members }
645    }
646}
647
648impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> FromIterator<(K, V)> for Object<'a> {
649    /// Appends the members in order, as [`push`](Object::push) does;
650    /// duplicates are kept.
651    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
652        Self {
653            members: iter
654                .into_iter()
655                .map(|(k, v)| (k.into(), v.into()))
656                .collect(),
657        }
658    }
659}
660
661impl<'a, K: Into<Cow<'a, str>>, V: Into<Value<'a>>> Extend<(K, V)> for Object<'a> {
662    /// Appends the members in order, as [`push`](Object::push) does.
663    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
664        self.members
665            .extend(iter.into_iter().map(|(k, v)| (k.into(), v.into())));
666    }
667}
668
669impl<'a> Index<&str> for Object<'a> {
670    type Output = Value<'a>;
671
672    /// The value of the first member named `key`, or `null` if there is none.
673    fn index(&self, key: &str) -> &Value<'a> {
674        self.get(key).unwrap_or(&crate::value::NULL)
675    }
676}
677
678impl<'a> IntoIterator for Object<'a> {
679    type Item = (Cow<'a, str>, Value<'a>);
680    type IntoIter = vec::IntoIter<(Cow<'a, str>, Value<'a>)>;
681
682    #[inline]
683    fn into_iter(self) -> Self::IntoIter {
684        self.into_vec().into_iter()
685    }
686}
687
688impl<'r, 'a> IntoIterator for &'r Object<'a> {
689    type Item = (&'r str, &'r Value<'a>);
690    type IntoIter = Iter<'r, 'a>;
691
692    #[inline]
693    fn into_iter(self) -> Self::IntoIter {
694        self.iter()
695    }
696}
697
698impl<'r, 'a> IntoIterator for &'r mut Object<'a> {
699    type Item = (&'r str, &'r mut Value<'a>);
700    type IntoIter = IterMut<'r, 'a>;
701
702    #[inline]
703    fn into_iter(self) -> Self::IntoIter {
704        self.iter_mut()
705    }
706}
707
708/// An iterator over an [`Object`]'s members, from [`Object::iter`].
709///
710/// # Examples
711///
712/// ```
713/// let doc = jsonx_lib::parse(r#"{"a": 1}"#)?;
714/// let mut it = doc.as_object().unwrap().iter();
715/// assert_eq!(it.next().map(|(k, _)| k), Some("a"));
716/// assert!(it.next().is_none());
717/// # Ok::<(), jsonx_lib::Error>(())
718/// ```
719#[derive(Clone, Debug)]
720pub struct Iter<'r, 'a> {
721    inner: slice::Iter<'r, Member<'a>>,
722}
723
724impl<'r, 'a> Iterator for Iter<'r, 'a> {
725    type Item = (&'r str, &'r Value<'a>);
726
727    #[inline]
728    fn next(&mut self) -> Option<Self::Item> {
729        self.inner.next().map(|(k, v)| (k.as_ref(), v))
730    }
731
732    #[inline]
733    fn size_hint(&self) -> (usize, Option<usize>) {
734        self.inner.size_hint()
735    }
736}
737
738impl DoubleEndedIterator for Iter<'_, '_> {
739    #[inline]
740    fn next_back(&mut self) -> Option<Self::Item> {
741        self.inner.next_back().map(|(k, v)| (k.as_ref(), v))
742    }
743}
744
745impl ExactSizeIterator for Iter<'_, '_> {}
746impl FusedIterator for Iter<'_, '_> {}
747
748/// An iterator over an [`Object`]'s members with mutable values, from
749/// [`Object::iter_mut`].
750///
751/// # Examples
752///
753/// ```
754/// use jsonx_lib::json;
755///
756/// let mut v = json!({ "a": 1 });
757/// let mut it = v.as_object_mut().unwrap().iter_mut();
758/// assert_eq!(it.next().map(|(k, _)| k), Some("a"));
759/// ```
760#[derive(Debug)]
761pub struct IterMut<'r, 'a> {
762    inner: slice::IterMut<'r, Member<'a>>,
763}
764
765impl<'r, 'a> Iterator for IterMut<'r, 'a> {
766    type Item = (&'r str, &'r mut Value<'a>);
767
768    #[inline]
769    fn next(&mut self) -> Option<Self::Item> {
770        self.inner.next().map(split_mut)
771    }
772
773    #[inline]
774    fn size_hint(&self) -> (usize, Option<usize>) {
775        self.inner.size_hint()
776    }
777}
778
779impl DoubleEndedIterator for IterMut<'_, '_> {
780    #[inline]
781    fn next_back(&mut self) -> Option<Self::Item> {
782        self.inner.next_back().map(split_mut)
783    }
784}
785
786/// A member as a shared key and a mutable value.
787#[inline]
788fn split_mut<'r, 'a>(member: &'r mut Member<'a>) -> (&'r str, &'r mut Value<'a>) {
789    let (key, value) = member;
790    let key: &'r Cow<'a, str> = key;
791    (key, value)
792}
793
794impl ExactSizeIterator for IterMut<'_, '_> {}
795impl FusedIterator for IterMut<'_, '_> {}