Skip to main content

oxirush_utils/tree/
value.rs

1/*
2   OxiRush
3   Copyright 2025-2026 Valentin D'Emmanuele
4
5   Licensed under the Apache License, Version 2.0 (the "License");
6   you may not use this file except in compliance with the License.
7   You may obtain a copy of the License at
8
9   http://www.apache.org/licenses/LICENSE-2.0
10
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16*/
17
18//! The value of a tree: JSON whose objects keep their members in the order in which they
19//! are written, whatever the features of `serde_json` in a build.
20
21use alloc::borrow::ToOwned;
22use alloc::boxed::Box;
23use alloc::collections::BTreeSet;
24use alloc::string::{String, ToString};
25use alloc::vec::Vec;
26use core::fmt;
27use core::ops;
28
29pub use serde_json::Number;
30
31/// A tree: a JSON value whose objects keep their members in the order in which they were
32/// written, which is that of the specification for the tree of a message.
33///
34/// It has the variants and the calls of `serde_json::Value`, and converts to and from
35/// one. Two objects are equal when they have the same members, whatever their order, as
36/// two JSON objects are. It prints as JSON, its members in their order, and `{:#}`
37/// prints it indented.
38///
39/// ```
40/// use oxirush_utils::tree::{Map, Value};
41///
42/// let mut slice = Map::new();
43/// slice.insert("sst".into(), 1.into());
44/// slice.insert("sd".into(), "0000ff".into());
45/// let tree = Value::Object(slice);
46/// assert_eq!(tree.to_string(), r#"{"sst":1,"sd":"0000ff"}"#);
47/// assert_eq!(tree, serde_json::json!({"sd": "0000ff", "sst": 1}));
48/// assert_eq!(tree["sst"], 1);
49/// ```
50#[derive(Clone, Default)]
51pub enum Value {
52    /// `null`.
53    #[default]
54    Null,
55    /// `true` or `false`.
56    Bool(bool),
57    /// A number.
58    Number(Number),
59    /// A string.
60    String(String),
61    /// A list.
62    Array(Vec<Value>),
63    /// An object, its members in the order in which they were written.
64    Object(Map),
65}
66
67/// The members of an object of a tree, in the order in which they were written: a member
68/// that is added goes at the end, one that is given another value keeps its place, and
69/// one that is taken out leaves the others in theirs.
70///
71/// It is a list. An object of more than 256 members also keeps an index: the position of
72/// each member under the hash of its name, in the order of the hashes, so that a member is
73/// found by its name in a time that grows as log n, and no name is copied. Whatever builds
74/// an object of n members with [`insert`](Self::insert), finds each of them, reads one from
75/// JSON or compares two takes a time that grows as n log n. Moving or taking out a member,
76/// which moves those after it, takes a time that grows as n.
77#[derive(Clone, Default)]
78pub struct Map {
79    members: Vec<(String, Value)>,
80    /// For an object of more than [`INDEXED`] members, the hash of the name of each member
81    /// with its position. In a box, it leaves a value of a tree the size that it has
82    /// without an index.
83    #[allow(clippy::box_collection, reason = "a value of a tree keeps its size")]
84    index: Option<Box<BTreeSet<(u64, usize)>>>,
85}
86
87/// The number of members above which an object keeps an index of its names. A value of a
88/// protocol has fewer, as the 84 bits of a 5GMM capability, and a search of so few names
89/// takes less than the index: a value of NAS that has an index is read and shown a third
90/// slower than without.
91const INDEXED: usize = 256;
92
93/// The hash of a name in the index: SipHash-2-4, whose collisions of 64 bits whoever writes
94/// the names cannot find, so that no object of many members has many under one hash. Its
95/// key is fixed: a crate without `std` has no source of a random one.
96#[allow(
97    deprecated,
98    reason = "SipHasher is the SipHash of core, which has no other"
99)]
100fn hash(name: &str) -> u64 {
101    use core::hash::Hasher;
102    let mut hasher = core::hash::SipHasher::new();
103    hasher.write(name.as_bytes());
104    hasher.finish()
105}
106
107impl Map {
108    /// An object without members.
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    /// An object without members, with room for `capacity` of them.
114    pub fn with_capacity(capacity: usize) -> Self {
115        Self {
116            members: Vec::with_capacity(capacity),
117            index: None,
118        }
119    }
120
121    /// How many members it has.
122    pub fn len(&self) -> usize {
123        self.members.len()
124    }
125
126    /// Whether it has none.
127    pub fn is_empty(&self) -> bool {
128        self.members.is_empty()
129    }
130
131    /// Take every member out.
132    pub fn clear(&mut self) {
133        self.members.clear();
134        self.index = None;
135    }
136
137    /// The position of the member of this name.
138    #[inline]
139    fn position(&self, name: &str) -> Option<usize> {
140        match &self.index {
141            Some(index) => {
142                let hash = hash(name);
143                let under = index.range((hash, 0)..=(hash, usize::MAX));
144                under
145                    .map(|(_, position)| *position)
146                    .find(|position| self.members[*position].0 == name)
147            }
148            None => self.members.iter().position(|(known, _)| known == name),
149        }
150    }
151
152    /// Add a member of a name that the object does not have, at the end.
153    #[inline]
154    fn push(&mut self, name: String, value: Value) {
155        match self.index.is_none() && self.members.len() < INDEXED {
156            true => self.members.push((name, value)),
157            false => self.push_indexed(name, value),
158        }
159    }
160
161    /// Add a member at the end of an object that has an index, or that has one with it.
162    #[cold]
163    #[inline(never)]
164    fn push_indexed(&mut self, name: String, value: Value) {
165        if let Some(index) = &mut self.index {
166            index.insert((hash(&name), self.members.len()));
167        }
168        self.members.push((name, value));
169        if self.index.is_none() && self.members.len() > INDEXED {
170            self.reindex();
171        }
172    }
173
174    /// Make the index of the members, or leave it out for an object of [`INDEXED`]
175    /// members or fewer.
176    fn reindex(&mut self) {
177        self.index = (self.members.len() > INDEXED).then(|| {
178            let members = self.members.iter().enumerate();
179            Box::new(members.map(|(at, (name, _))| (hash(name), at)).collect())
180        });
181    }
182
183    /// Move the positions of the index from `from` by one, after a member was put at
184    /// `from` (`up`) or taken out of it, which keeps the order of the index: a time that
185    /// grows as n, without a hash.
186    fn moved(&mut self, from: usize, up: bool) {
187        if self.members.len() <= INDEXED {
188            self.index = None;
189            return;
190        }
191        let Some(index) = self.index.take() else {
192            return self.reindex();
193        };
194        let entries = index.into_iter().map(|(hash, at)| match (at >= from, up) {
195            (false, _) => (hash, at),
196            (true, true) => (hash, at + 1),
197            (true, false) => (hash, at - 1),
198        });
199        self.index = Some(Box::new(entries.collect()));
200    }
201
202    /// The member of this name.
203    pub fn get(&self, name: &str) -> Option<&Value> {
204        self.get_key_value(name).map(|(_, value)| value)
205    }
206
207    /// The member of this name, to change.
208    pub fn get_mut(&mut self, name: &str) -> Option<&mut Value> {
209        let member = match &self.index {
210            Some(_) => {
211                let position = self.position(name)?;
212                self.members.get_mut(position)
213            }
214            None => self.members.iter_mut().find(|(known, _)| known == name),
215        };
216        member.map(|(_, value)| value)
217    }
218
219    /// The member of this name, with its name as the object has it.
220    pub fn get_key_value(&self, name: &str) -> Option<(&String, &Value)> {
221        let member = match &self.index {
222            Some(_) => self.members.get(self.position(name)?),
223            None => self.members.iter().find(|(known, _)| known == name),
224        };
225        member.map(|(name, value)| (name, value))
226    }
227
228    /// Whether it has a member of this name.
229    pub fn contains_key(&self, name: &str) -> bool {
230        self.position(name).is_some()
231    }
232
233    /// Give the member `name` the value `value`: at its place when the object has it,
234    /// and at the end otherwise. The value that it had, if any.
235    pub fn insert(&mut self, name: String, value: Value) -> Option<Value> {
236        match self.get_mut(&name) {
237            Some(was) => Some(core::mem::replace(was, value)),
238            None => {
239                self.push(name, value);
240                None
241            }
242        }
243    }
244
245    /// Give the member `name` the value `value` at `position`, or at the end for a position
246    /// past it: the member moves there when the object has it. The value that it had, if
247    /// any.
248    pub fn shift_insert(&mut self, position: usize, name: String, value: Value) -> Option<Value> {
249        let was = self.shift_remove(&name);
250        let position = position.min(self.members.len());
251        let hashed = self.index.is_some().then(|| hash(&name));
252        self.members.insert(position, (name, value));
253        self.moved(position, true);
254        if let (Some(index), Some(hash)) = (&mut self.index, hashed) {
255            index.insert((hash, position));
256        }
257        was
258    }
259
260    /// Take the member `name` out, and leave the others in their order.
261    pub fn shift_remove(&mut self, name: &str) -> Option<Value> {
262        let position = self.position(name)?;
263        let (name, value) = self.members.remove(position);
264        if let Some(index) = &mut self.index {
265            index.remove(&(hash(&name), position));
266        }
267        self.moved(position, false);
268        Some(value)
269    }
270
271    /// Take the member `name` out, and leave the others in their order: as
272    /// [`shift_remove`](Self::shift_remove), which keeps the order of the members, and
273    /// not as the `swap_remove` of an `IndexMap`.
274    pub fn remove(&mut self, name: &str) -> Option<Value> {
275        self.shift_remove(name)
276    }
277
278    /// The member `name`, to give it a value when it has none.
279    pub fn entry(&mut self, name: impl Into<String>) -> Entry<'_> {
280        let name = name.into();
281        match self.position(&name) {
282            Some(position) => Entry::Occupied(&mut self.members[position].1),
283            None => Entry::Vacant(self, name),
284        }
285    }
286
287    /// Keep the members for which `keep` says so.
288    pub fn retain(&mut self, mut keep: impl FnMut(&String, &mut Value) -> bool) {
289        let before = self.members.len();
290        self.members.retain_mut(|(name, value)| keep(name, value));
291        if self.members.len() != before {
292            self.reindex();
293        }
294    }
295
296    /// The members, in their order.
297    pub fn iter(&self) -> impl DoubleEndedIterator<Item = (&String, &Value)> + ExactSizeIterator {
298        self.members.iter().map(|(name, value)| (name, value))
299    }
300
301    /// The members, in their order, to change their values.
302    pub fn iter_mut(
303        &mut self,
304    ) -> impl DoubleEndedIterator<Item = (&String, &mut Value)> + ExactSizeIterator {
305        self.members.iter_mut().map(|(name, value)| (&*name, value))
306    }
307
308    /// The names of the members, in their order.
309    pub fn keys(&self) -> impl DoubleEndedIterator<Item = &String> + ExactSizeIterator {
310        self.members.iter().map(|(name, _)| name)
311    }
312
313    /// The values of the members, in their order.
314    pub fn values(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator {
315        self.members.iter().map(|(_, value)| value)
316    }
317
318    /// The values of the members, in their order, to change them.
319    pub fn values_mut(
320        &mut self,
321    ) -> impl DoubleEndedIterator<Item = &mut Value> + ExactSizeIterator {
322        self.members.iter_mut().map(|(_, value)| value)
323    }
324
325    /// The members, from the first, which have each their own name.
326    pub(crate) fn from_members(members: Vec<(String, Value)>) -> Self {
327        let mut map = Self {
328            members,
329            index: None,
330        };
331        map.reindex();
332        map
333    }
334
335    /// The positions of the members, in the order of their names, and in that of the
336    /// object for one name.
337    fn by_name(&self) -> Vec<usize> {
338        let mut order: Vec<usize> = (0..self.members.len()).collect();
339        order.sort_by(|a, b| self.members[*a].0.cmp(&self.members[*b].0));
340        order
341    }
342}
343
344/// A member of an object, which has a value or none yet: [`Map::entry`].
345pub enum Entry<'m> {
346    /// The member has this value.
347    Occupied(&'m mut Value),
348    /// The object has no member of this name.
349    Vacant(&'m mut Map, String),
350}
351
352impl<'m> Entry<'m> {
353    /// The value of the member, which is `value` when the object had none.
354    pub fn or_insert(self, value: Value) -> &'m mut Value {
355        self.or_insert_with(|| value)
356    }
357
358    /// The value of the member, which `value` gives when the object had none.
359    pub fn or_insert_with(self, value: impl FnOnce() -> Value) -> &'m mut Value {
360        match self {
361            Entry::Occupied(value) => value,
362            Entry::Vacant(map, name) => {
363                map.push(name, value());
364                &mut map
365                    .members
366                    .last_mut()
367                    .expect("the member that was pushed")
368                    .1
369            }
370        }
371    }
372
373    /// The value of the member, which is `null` when the object had none.
374    pub fn or_default(self) -> &'m mut Value {
375        self.or_insert(Value::Null)
376    }
377}
378
379impl PartialEq for Map {
380    /// Two objects are equal when they have the same members, whatever their order.
381    fn eq(&self, other: &Self) -> bool {
382        if self.len() != other.len() {
383            return false;
384        }
385        // In the same order, as two trees of one type are: a member after the other.
386        let mut pairs = self.members.iter().zip(&other.members);
387        if pairs.all(|((a, _), (b, _))| a == b) {
388            return self
389                .members
390                .iter()
391                .zip(&other.members)
392                .all(|((_, a), (_, b))| a == b);
393        }
394        // Otherwise by the order of the names (each name is there once).
395        let (mine, theirs) = (self.by_name(), other.by_name());
396        mine.iter().zip(&theirs).all(|(a, b)| {
397            let ((a_name, a), (b_name, b)) = (&self.members[*a], &other.members[*b]);
398            a_name == b_name && a == b
399        })
400    }
401}
402
403impl Eq for Map {}
404
405impl fmt::Debug for Map {
406    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
407        formatter.debug_map().entries(self.iter()).finish()
408    }
409}
410
411impl<'m> IntoIterator for &'m Map {
412    type Item = (&'m String, &'m Value);
413    type IntoIter = core::iter::Map<
414        core::slice::Iter<'m, (String, Value)>,
415        fn(&'m (String, Value)) -> (&'m String, &'m Value),
416    >;
417
418    fn into_iter(self) -> Self::IntoIter {
419        self.members.iter().map(|(name, value)| (name, value))
420    }
421}
422
423impl<'m> IntoIterator for &'m mut Map {
424    type Item = (&'m String, &'m mut Value);
425    type IntoIter = core::iter::Map<
426        core::slice::IterMut<'m, (String, Value)>,
427        fn(&'m mut (String, Value)) -> (&'m String, &'m mut Value),
428    >;
429
430    fn into_iter(self) -> Self::IntoIter {
431        self.members.iter_mut().map(|(name, value)| (&*name, value))
432    }
433}
434
435impl IntoIterator for Map {
436    type Item = (String, Value);
437    type IntoIter = alloc::vec::IntoIter<(String, Value)>;
438
439    fn into_iter(self) -> Self::IntoIter {
440        self.members.into_iter()
441    }
442}
443
444impl FromIterator<(String, Value)> for Map {
445    /// The members in the order of the iterator; a name that comes again gives its member
446    /// the last value, at the place of the first.
447    fn from_iter<I: IntoIterator<Item = (String, Value)>>(members: I) -> Self {
448        let members = members.into_iter();
449        let mut map = Map::with_capacity(members.size_hint().0);
450        map.extend(members);
451        map
452    }
453}
454
455impl Extend<(String, Value)> for Map {
456    /// The members after those of the object, as [`insert`](Map::insert) adds them one
457    /// after the other.
458    fn extend<I: IntoIterator<Item = (String, Value)>>(&mut self, members: I) {
459        let members = members.into_iter();
460        self.members.reserve(members.size_hint().0);
461        for (name, value) in members {
462            self.insert(name, value);
463        }
464    }
465}
466
467impl ops::Index<&str> for Map {
468    type Output = Value;
469
470    /// # Panics
471    ///
472    /// When the object has no member of this name.
473    fn index(&self, name: &str) -> &Value {
474        self.get(name).expect("no member of this name")
475    }
476}
477
478impl ops::IndexMut<&str> for Map {
479    /// # Panics
480    ///
481    /// When the object has no member of this name.
482    fn index_mut(&mut self, name: &str) -> &mut Value {
483        self.get_mut(name).expect("no member of this name")
484    }
485}
486
487// ── The value ───────────────────────────────────────────────────────────────
488
489static NULL: Value = Value::Null;
490
491impl Value {
492    /// Whether it is `null`.
493    pub fn is_null(&self) -> bool {
494        matches!(self, Value::Null)
495    }
496
497    /// Whether it is `true` or `false`.
498    pub fn is_boolean(&self) -> bool {
499        matches!(self, Value::Bool(_))
500    }
501
502    /// Whether it is a number.
503    pub fn is_number(&self) -> bool {
504        matches!(self, Value::Number(_))
505    }
506
507    /// Whether it is a whole number that a `u64` holds.
508    pub fn is_u64(&self) -> bool {
509        matches!(self, Value::Number(number) if number.is_u64())
510    }
511
512    /// Whether it is a whole number that an `i64` holds.
513    pub fn is_i64(&self) -> bool {
514        matches!(self, Value::Number(number) if number.is_i64())
515    }
516
517    /// Whether it is a number with a fraction or an exponent.
518    pub fn is_f64(&self) -> bool {
519        matches!(self, Value::Number(number) if number.is_f64())
520    }
521
522    /// Whether it is a string.
523    pub fn is_string(&self) -> bool {
524        matches!(self, Value::String(_))
525    }
526
527    /// Whether it is a list.
528    pub fn is_array(&self) -> bool {
529        matches!(self, Value::Array(_))
530    }
531
532    /// Whether it is an object.
533    pub fn is_object(&self) -> bool {
534        matches!(self, Value::Object(_))
535    }
536
537    /// `()` for `null`.
538    pub fn as_null(&self) -> Option<()> {
539        self.is_null().then_some(())
540    }
541
542    /// The boolean that it is.
543    pub fn as_bool(&self) -> Option<bool> {
544        match self {
545            Value::Bool(boolean) => Some(*boolean),
546            _ => None,
547        }
548    }
549
550    /// The number that it is.
551    pub fn as_number(&self) -> Option<&Number> {
552        match self {
553            Value::Number(number) => Some(number),
554            _ => None,
555        }
556    }
557
558    /// The whole number that it is, when a `u64` holds it.
559    pub fn as_u64(&self) -> Option<u64> {
560        self.as_number().and_then(Number::as_u64)
561    }
562
563    /// The whole number that it is, when an `i64` holds it.
564    pub fn as_i64(&self) -> Option<i64> {
565        self.as_number().and_then(Number::as_i64)
566    }
567
568    /// The number that it is, as an `f64`.
569    pub fn as_f64(&self) -> Option<f64> {
570        self.as_number().and_then(Number::as_f64)
571    }
572
573    /// The string that it is.
574    pub fn as_str(&self) -> Option<&str> {
575        match self {
576            Value::String(text) => Some(text),
577            _ => None,
578        }
579    }
580
581    /// The list that it is.
582    pub fn as_array(&self) -> Option<&Vec<Value>> {
583        match self {
584            Value::Array(entries) => Some(entries),
585            _ => None,
586        }
587    }
588
589    /// The list that it is, to change.
590    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
591        match self {
592            Value::Array(entries) => Some(entries),
593            _ => None,
594        }
595    }
596
597    /// The object that it is.
598    pub fn as_object(&self) -> Option<&Map> {
599        match self {
600            Value::Object(members) => Some(members),
601            _ => None,
602        }
603    }
604
605    /// The object that it is, to change.
606    pub fn as_object_mut(&mut self) -> Option<&mut Map> {
607        match self {
608            Value::Object(members) => Some(members),
609            _ => None,
610        }
611    }
612
613    /// The member of an object by its name, or the entry of a list by its position.
614    pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
615        index.index_into(self)
616    }
617
618    /// The member of an object by its name, or the entry of a list by its position, to
619    /// change.
620    pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
621        index.index_into_mut(self)
622    }
623
624    /// The value at a JSON pointer (RFC 6901), as `"/message/protocolIEs/0"`: the empty
625    /// pointer is the value itself.
626    pub fn pointer(&self, pointer: &str) -> Option<&Value> {
627        if pointer.is_empty() {
628            return Some(self);
629        }
630        let rest = pointer.strip_prefix('/')?;
631        rest.split('/').try_fold(self, |value, token| {
632            let token = token.replace("~1", "/").replace("~0", "~");
633            match value {
634                Value::Object(members) => members.get(&token),
635                Value::Array(entries) => entries.get(super::position(&token)?),
636                _ => None,
637            }
638        })
639    }
640
641    /// The value at a JSON pointer, to change.
642    pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value> {
643        if pointer.is_empty() {
644            return Some(self);
645        }
646        let rest = pointer.strip_prefix('/')?;
647        rest.split('/').try_fold(self, |value, token| {
648            let token = token.replace("~1", "/").replace("~0", "~");
649            match value {
650                Value::Object(members) => members.get_mut(&token),
651                Value::Array(entries) => entries.get_mut(super::position(&token)?),
652                _ => None,
653            }
654        })
655    }
656
657    /// The value, which `null` takes the place of.
658    pub fn take(&mut self) -> Value {
659        core::mem::take(self)
660    }
661}
662
663/// What indexes a value: the name of a member, or the position of an entry.
664pub trait Index: private::Sealed {
665    #[doc(hidden)]
666    fn index_into<'v>(&self, value: &'v Value) -> Option<&'v Value>;
667    #[doc(hidden)]
668    fn index_into_mut<'v>(&self, value: &'v mut Value) -> Option<&'v mut Value>;
669    #[doc(hidden)]
670    fn index_or_insert<'v>(&self, value: &'v mut Value) -> &'v mut Value;
671}
672
673mod private {
674    pub trait Sealed {}
675    impl Sealed for usize {}
676    impl Sealed for str {}
677    impl Sealed for alloc::string::String {}
678    impl<T: Sealed + ?Sized> Sealed for &T {}
679}
680
681impl Index for usize {
682    fn index_into<'v>(&self, value: &'v Value) -> Option<&'v Value> {
683        value.as_array()?.get(*self)
684    }
685
686    fn index_into_mut<'v>(&self, value: &'v mut Value) -> Option<&'v mut Value> {
687        value.as_array_mut()?.get_mut(*self)
688    }
689
690    fn index_or_insert<'v>(&self, value: &'v mut Value) -> &'v mut Value {
691        match value {
692            Value::Array(entries) => {
693                let length = entries.len();
694                entries.get_mut(*self).unwrap_or_else(|| {
695                    panic!("cannot access index {self} of a list of length {length}")
696                })
697            }
698            _ => panic!("cannot access index {self} of a value that is no list"),
699        }
700    }
701}
702
703impl Index for str {
704    fn index_into<'v>(&self, value: &'v Value) -> Option<&'v Value> {
705        value.as_object()?.get(self)
706    }
707
708    fn index_into_mut<'v>(&self, value: &'v mut Value) -> Option<&'v mut Value> {
709        value.as_object_mut()?.get_mut(self)
710    }
711
712    fn index_or_insert<'v>(&self, value: &'v mut Value) -> &'v mut Value {
713        if value.is_null() {
714            *value = Value::Object(Map::new());
715        }
716        match value {
717            Value::Object(members) => members.entry(self.to_owned()).or_default(),
718            _ => panic!("cannot access member {self:?} of a value that is no object"),
719        }
720    }
721}
722
723impl Index for String {
724    fn index_into<'v>(&self, value: &'v Value) -> Option<&'v Value> {
725        self.as_str().index_into(value)
726    }
727
728    fn index_into_mut<'v>(&self, value: &'v mut Value) -> Option<&'v mut Value> {
729        self.as_str().index_into_mut(value)
730    }
731
732    fn index_or_insert<'v>(&self, value: &'v mut Value) -> &'v mut Value {
733        self.as_str().index_or_insert(value)
734    }
735}
736
737impl<T: Index + ?Sized> Index for &T {
738    fn index_into<'v>(&self, value: &'v Value) -> Option<&'v Value> {
739        (**self).index_into(value)
740    }
741
742    fn index_into_mut<'v>(&self, value: &'v mut Value) -> Option<&'v mut Value> {
743        (**self).index_into_mut(value)
744    }
745
746    fn index_or_insert<'v>(&self, value: &'v mut Value) -> &'v mut Value {
747        (**self).index_or_insert(value)
748    }
749}
750
751impl<I: Index> ops::Index<I> for Value {
752    type Output = Value;
753
754    /// The member or the entry, and `null` where there is none.
755    fn index(&self, index: I) -> &Value {
756        index.index_into(self).unwrap_or(&NULL)
757    }
758}
759
760impl<I: Index> ops::IndexMut<I> for Value {
761    /// The member, which an object takes as `null` when it has none, and which `null`
762    /// takes as an object with that member; or the entry.
763    ///
764    /// # Panics
765    ///
766    /// For a position past the end of a list, and for a value of another kind.
767    fn index_mut(&mut self, index: I) -> &mut Value {
768        index.index_or_insert(self)
769    }
770}
771
772// ── Equality ────────────────────────────────────────────────────────────────
773
774impl PartialEq for Value {
775    fn eq(&self, other: &Self) -> bool {
776        match (self, other) {
777            (Value::Null, Value::Null) => true,
778            (Value::Bool(a), Value::Bool(b)) => a == b,
779            (Value::Number(a), Value::Number(b)) => a == b,
780            (Value::String(a), Value::String(b)) => a == b,
781            (Value::Array(a), Value::Array(b)) => a == b,
782            (Value::Object(a), Value::Object(b)) => a == b,
783            _ => false,
784        }
785    }
786}
787
788impl Eq for Value {}
789
790impl PartialEq<serde_json::Value> for Value {
791    /// Whether the two are the same JSON: objects whatever the order of their members.
792    fn eq(&self, other: &serde_json::Value) -> bool {
793        match (self, other) {
794            (Value::Null, serde_json::Value::Null) => true,
795            (Value::Bool(a), serde_json::Value::Bool(b)) => a == b,
796            (Value::Number(a), serde_json::Value::Number(b)) => a == b,
797            (Value::String(a), serde_json::Value::String(b)) => a == b,
798            (Value::Array(a), serde_json::Value::Array(b)) => {
799                a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a == b)
800            }
801            (Value::Object(a), serde_json::Value::Object(b)) => {
802                a.len() == b.len()
803                    && a.iter()
804                        .all(|(name, value)| b.get(name).is_some_and(|b| value == b))
805            }
806            _ => false,
807        }
808    }
809}
810
811impl PartialEq<Value> for serde_json::Value {
812    fn eq(&self, other: &Value) -> bool {
813        other == self
814    }
815}
816
817macro_rules! equal_to {
818    ($($ty:ty => $as:ident as $wide:ty),* $(,)?) => {$(
819        impl PartialEq<$ty> for Value {
820            fn eq(&self, other: &$ty) -> bool {
821                self.$as().is_some_and(|value| value == *other as $wide)
822            }
823        }
824        impl PartialEq<$ty> for &Value {
825            fn eq(&self, other: &$ty) -> bool {
826                (**self) == *other
827            }
828        }
829        impl PartialEq<Value> for $ty {
830            fn eq(&self, other: &Value) -> bool {
831                other == self
832            }
833        }
834    )*};
835}
836
837equal_to! {
838    u8 => as_u64 as u64, u16 => as_u64 as u64, u32 => as_u64 as u64, u64 => as_u64 as u64,
839    usize => as_u64 as u64, i8 => as_i64 as i64, i16 => as_i64 as i64, i32 => as_i64 as i64,
840    i64 => as_i64 as i64, isize => as_i64 as i64, f64 => as_f64 as f64, bool => as_bool as bool,
841}
842
843impl PartialEq<str> for Value {
844    fn eq(&self, other: &str) -> bool {
845        self.as_str() == Some(other)
846    }
847}
848
849impl PartialEq<&str> for Value {
850    fn eq(&self, other: &&str) -> bool {
851        self.as_str() == Some(*other)
852    }
853}
854
855impl PartialEq<String> for Value {
856    fn eq(&self, other: &String) -> bool {
857        self.as_str() == Some(other.as_str())
858    }
859}
860
861impl PartialEq<Value> for str {
862    fn eq(&self, other: &Value) -> bool {
863        other == self
864    }
865}
866
867impl PartialEq<Value> for &str {
868    fn eq(&self, other: &Value) -> bool {
869        other == self
870    }
871}
872
873impl PartialEq<Value> for String {
874    fn eq(&self, other: &Value) -> bool {
875        other == self
876    }
877}
878
879// ── Conversions ─────────────────────────────────────────────────────────────
880
881macro_rules! from_number {
882    ($($ty:ty),* $(,)?) => {$(
883        impl From<$ty> for Value {
884            fn from(number: $ty) -> Self {
885                Value::Number(number.into())
886            }
887        }
888        impl From<&$ty> for Value {
889            fn from(number: &$ty) -> Self {
890                Value::Number((*number).into())
891            }
892        }
893    )*};
894}
895
896from_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
897
898impl From<&f64> for Value {
899    fn from(number: &f64) -> Self {
900        Value::from(*number)
901    }
902}
903
904impl From<&bool> for Value {
905    fn from(boolean: &bool) -> Self {
906        Value::Bool(*boolean)
907    }
908}
909
910impl From<&&str> for Value {
911    fn from(text: &&str) -> Self {
912        Value::String((*text).into())
913    }
914}
915
916impl From<f64> for Value {
917    /// The number, and `null` for one that JSON has not: an infinity or no number.
918    fn from(number: f64) -> Self {
919        Number::from_f64(number).map_or(Value::Null, Value::Number)
920    }
921}
922
923impl From<bool> for Value {
924    fn from(boolean: bool) -> Self {
925        Value::Bool(boolean)
926    }
927}
928
929impl From<Number> for Value {
930    fn from(number: Number) -> Self {
931        Value::Number(number)
932    }
933}
934
935impl From<String> for Value {
936    fn from(text: String) -> Self {
937        Value::String(text)
938    }
939}
940
941impl From<&str> for Value {
942    fn from(text: &str) -> Self {
943        Value::String(text.to_string())
944    }
945}
946
947impl From<&String> for Value {
948    fn from(text: &String) -> Self {
949        Value::String(text.clone())
950    }
951}
952
953impl From<&Value> for Value {
954    fn from(value: &Value) -> Self {
955        value.clone()
956    }
957}
958
959impl<T: Clone + Into<Value>> From<&[T]> for Value {
960    fn from(entries: &[T]) -> Self {
961        Value::Array(entries.iter().cloned().map(Into::into).collect())
962    }
963}
964
965impl<T: Into<Value>, const N: usize> From<[T; N]> for Value {
966    fn from(entries: [T; N]) -> Self {
967        Value::Array(entries.into_iter().map(Into::into).collect())
968    }
969}
970
971impl From<Map> for Value {
972    fn from(members: Map) -> Self {
973        Value::Object(members)
974    }
975}
976
977impl<T: Into<Value>> From<Vec<T>> for Value {
978    fn from(entries: Vec<T>) -> Self {
979        Value::Array(entries.into_iter().map(Into::into).collect())
980    }
981}
982
983impl<T: Into<Value>> From<Option<T>> for Value {
984    /// The value, and `null` for none.
985    fn from(value: Option<T>) -> Self {
986        value.map_or(Value::Null, Into::into)
987    }
988}
989
990impl From<()> for Value {
991    fn from((): ()) -> Self {
992        Value::Null
993    }
994}
995
996impl<T: Into<Value>> FromIterator<T> for Value {
997    /// A list of the values.
998    fn from_iter<I: IntoIterator<Item = T>>(entries: I) -> Self {
999        Value::Array(entries.into_iter().map(Into::into).collect())
1000    }
1001}
1002
1003impl From<serde_json::Value> for Value {
1004    /// The same JSON. The members of an object come in the order in which
1005    /// `serde_json::Map` iterates them: by their names, unless a crate of the program
1006    /// turns on `serde_json/preserve_order`.
1007    fn from(value: serde_json::Value) -> Self {
1008        match value {
1009            serde_json::Value::Null => Value::Null,
1010            serde_json::Value::Bool(boolean) => Value::Bool(boolean),
1011            serde_json::Value::Number(number) => Value::Number(number),
1012            serde_json::Value::String(text) => Value::String(text),
1013            serde_json::Value::Array(entries) => {
1014                Value::Array(entries.into_iter().map(Value::from).collect())
1015            }
1016            serde_json::Value::Object(members) => Value::Object(Map::from_members(
1017                members
1018                    .into_iter()
1019                    .map(|(name, value)| (name, Value::from(value)))
1020                    .collect(),
1021            )),
1022        }
1023    }
1024}
1025
1026impl From<&serde_json::Value> for Value {
1027    fn from(value: &serde_json::Value) -> Self {
1028        Value::from(value.clone())
1029    }
1030}
1031
1032impl From<Value> for serde_json::Value {
1033    /// The same JSON. A `serde_json::Map` keeps the order of the members only where a
1034    /// crate of the program turns on `serde_json/preserve_order`, and sorts them by their
1035    /// names otherwise.
1036    fn from(value: Value) -> Self {
1037        match value {
1038            Value::Null => serde_json::Value::Null,
1039            Value::Bool(boolean) => serde_json::Value::Bool(boolean),
1040            Value::Number(number) => serde_json::Value::Number(number),
1041            Value::String(text) => serde_json::Value::String(text),
1042            Value::Array(entries) => {
1043                serde_json::Value::Array(entries.into_iter().map(Into::into).collect())
1044            }
1045            Value::Object(members) => serde_json::Value::Object(
1046                members
1047                    .into_iter()
1048                    .map(|(name, value)| (name, value.into()))
1049                    .collect(),
1050            ),
1051        }
1052    }
1053}
1054
1055impl From<&Value> for serde_json::Value {
1056    fn from(value: &Value) -> Self {
1057        value.clone().into()
1058    }
1059}
1060
1061// ── Text ────────────────────────────────────────────────────────────────────
1062
1063impl core::str::FromStr for Value {
1064    type Err = serde_json::Error;
1065
1066    /// The tree that a JSON text writes, its members in the order of the text. A name
1067    /// that an object has twice is refused.
1068    fn from_str(text: &str) -> Result<Self, Self::Err> {
1069        serde_json::from_str(text)
1070    }
1071}
1072
1073impl fmt::Display for Value {
1074    /// The JSON text of the tree, its members in their order: compact, or indented with
1075    /// `{:#}`.
1076    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1077        let text = match formatter.alternate() {
1078            true => serde_json::to_string_pretty(self),
1079            false => serde_json::to_string(self),
1080        };
1081        formatter.write_str(&text.map_err(|_| fmt::Error)?)
1082    }
1083}
1084
1085impl fmt::Debug for Value {
1086    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1087        match self {
1088            Value::Null => formatter.write_str("Null"),
1089            Value::Bool(boolean) => write!(formatter, "Bool({boolean})"),
1090            Value::Number(number) => write!(formatter, "Number({number})"),
1091            Value::String(text) => write!(formatter, "String({text:?})"),
1092            Value::Array(entries) => {
1093                formatter.write_str("Array ")?;
1094                formatter.debug_list().entries(entries).finish()
1095            }
1096            Value::Object(members) => {
1097                formatter.write_str("Object ")?;
1098                fmt::Debug::fmt(members, formatter)
1099            }
1100        }
1101    }
1102}
1103
1104// ── serde ───────────────────────────────────────────────────────────────────
1105
1106impl serde_core::Serialize for Value {
1107    /// The value in any format of serde, the members of an object in their order.
1108    fn serialize<S: serde_core::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1109        use serde_core::ser::{SerializeMap, SerializeSeq};
1110        match self {
1111            Value::Null => serializer.serialize_unit(),
1112            Value::Bool(boolean) => serializer.serialize_bool(*boolean),
1113            Value::Number(number) => number.serialize(serializer),
1114            Value::String(text) => serializer.serialize_str(text),
1115            Value::Array(entries) => {
1116                let mut list = serializer.serialize_seq(Some(entries.len()))?;
1117                for entry in entries {
1118                    list.serialize_element(entry)?;
1119                }
1120                list.end()
1121            }
1122            Value::Object(members) => {
1123                let mut object = serializer.serialize_map(Some(members.len()))?;
1124                for (name, value) in members {
1125                    object.serialize_entry(name, value)?;
1126                }
1127                object.end()
1128            }
1129        }
1130    }
1131}
1132
1133impl<'de> serde_core::Deserialize<'de> for Value {
1134    /// The value that a self-describing format writes, the members of an object in the
1135    /// order in which it writes them. A name that an object has twice is refused: JSON
1136    /// leaves what it means open, and a reader of a tree takes no guess.
1137    fn deserialize<D: serde_core::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1138        deserializer.deserialize_any(Visitor)
1139    }
1140}
1141
1142struct Visitor;
1143
1144impl<'de> serde_core::de::Visitor<'de> for Visitor {
1145    type Value = Value;
1146
1147    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1148        formatter.write_str("a JSON value")
1149    }
1150
1151    fn visit_bool<E>(self, boolean: bool) -> Result<Value, E> {
1152        Ok(Value::Bool(boolean))
1153    }
1154
1155    fn visit_i64<E>(self, number: i64) -> Result<Value, E> {
1156        Ok(number.into())
1157    }
1158
1159    fn visit_u64<E>(self, number: u64) -> Result<Value, E> {
1160        Ok(number.into())
1161    }
1162
1163    fn visit_i128<E: serde_core::de::Error>(self, number: i128) -> Result<Value, E> {
1164        match (i64::try_from(number), u64::try_from(number)) {
1165            (Ok(number), _) => Ok(number.into()),
1166            (_, Ok(number)) => Ok(number.into()),
1167            _ => Err(E::custom("a number that 64 bits do not hold")),
1168        }
1169    }
1170
1171    fn visit_u128<E: serde_core::de::Error>(self, number: u128) -> Result<Value, E> {
1172        u64::try_from(number)
1173            .map(Value::from)
1174            .map_err(|_| E::custom("a number that 64 bits do not hold"))
1175    }
1176
1177    fn visit_f64<E>(self, number: f64) -> Result<Value, E> {
1178        Ok(number.into())
1179    }
1180
1181    fn visit_str<E>(self, text: &str) -> Result<Value, E> {
1182        Ok(Value::String(text.to_string()))
1183    }
1184
1185    fn visit_string<E>(self, text: String) -> Result<Value, E> {
1186        Ok(Value::String(text))
1187    }
1188
1189    fn visit_none<E>(self) -> Result<Value, E> {
1190        Ok(Value::Null)
1191    }
1192
1193    fn visit_some<D: serde_core::Deserializer<'de>>(self, value: D) -> Result<Value, D::Error> {
1194        serde_core::Deserialize::deserialize(value)
1195    }
1196
1197    fn visit_unit<E>(self) -> Result<Value, E> {
1198        Ok(Value::Null)
1199    }
1200
1201    fn visit_seq<A: serde_core::de::SeqAccess<'de>>(self, mut list: A) -> Result<Value, A::Error> {
1202        let mut entries = Vec::with_capacity(list.size_hint().unwrap_or(0).min(4096));
1203        while let Some(entry) = list.next_element()? {
1204            entries.push(entry);
1205        }
1206        Ok(Value::Array(entries))
1207    }
1208
1209    fn visit_map<A: serde_core::de::MapAccess<'de>>(
1210        self,
1211        mut object: A,
1212    ) -> Result<Value, A::Error> {
1213        use serde_core::de::Error as _;
1214        let mut members: Vec<(String, Value)> =
1215            Vec::with_capacity(object.size_hint().unwrap_or(0).min(4096));
1216        while let Some((name, value)) = object.next_entry::<String, Value>()? {
1217            members.push((name, value));
1218        }
1219        // A name that comes twice, found in the order of the names: a time that grows
1220        // as n log n, for an object of any size.
1221        let mut names: Vec<&str> = members.iter().map(|(name, _)| name.as_str()).collect();
1222        names.sort_unstable();
1223        if let Some(twice) = names.windows(2).find(|pair| pair[0] == pair[1]) {
1224            return Err(A::Error::custom(alloc::format!(
1225                "the member {:?} is written twice in an object",
1226                twice[0]
1227            )));
1228        }
1229        Ok(Value::Object(Map::from_members(members)))
1230    }
1231}