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