Skip to main content

jsonx_lib/
value.rs

1//! The document model.
2
3use alloc::{
4    borrow::Cow,
5    string::{String, ToString},
6    vec::Vec,
7};
8use core::{
9    fmt,
10    hash::{Hash, Hasher},
11    ops::Index,
12};
13
14use crate::{Array, Number, Object, tree};
15
16/// The `null` that indexing returns for a missing member or item.
17pub(crate) static NULL: Value<'static> = Value::Null;
18
19/// A JSON value, borrowing from the text it was parsed from.
20///
21/// Strings without escape sequences borrow their bytes from the input
22/// (`Cow::Borrowed`); only a string that had to be unescaped owns a copy.
23/// Numbers keep their exact text (see [`Number`]). Object members keep their
24/// document order. The lifetime `'a` is the input's; [`into_owned`](Self::into_owned)
25/// detaches a value from it, and a value built in code from `'static` data is
26/// a `Value<'static>`.
27///
28/// Every operation on a `Value` (drop, clone, comparison, writing) uses a
29/// bounded amount of stack whatever the depth, so a value of any depth is safe
30/// to use.
31///
32/// Equality is structural and exact: numbers compare by text (`1` and `1.0`
33/// differ), and object members compare in order. A `Value` also compares
34/// directly with Rust strings, booleans, and numbers, which is what
35/// `assert_eq!(doc["id"], 7)` uses.
36///
37/// # Examples
38///
39/// ```
40/// use jsonx_lib::{parse, Value};
41///
42/// let doc = parse(r#"{"user": {"name": "ada", "langs": ["en", "fr"]}, "admin": false}"#)?;
43///
44/// // Index freely: a missing member or item reads as `null`.
45/// assert_eq!(doc["user"]["name"], "ada");
46/// assert_eq!(doc["user"]["langs"][1], "fr");
47/// assert!(doc["nope"][3].is_null());
48///
49/// // Or ask with typed accessors that say whether the shape matched.
50/// assert_eq!(doc["admin"].as_bool(), Some(false));
51/// assert_eq!(doc.pointer("/user/langs/0").and_then(Value::as_str), Some("en"));
52/// # Ok::<(), jsonx_lib::Error>(())
53/// ```
54#[derive(Default)]
55pub enum Value<'a> {
56    /// `null`.
57    #[default]
58    Null,
59    /// `true` or `false`.
60    Bool(bool),
61    /// A number, kept as its exact text.
62    Number(Number<'a>),
63    /// A string: borrowed from the input when it had no escapes, owned otherwise.
64    String(Cow<'a, str>),
65    /// An array.
66    Array(Array<'a>),
67    /// An object.
68    Object(Object<'a>),
69}
70
71/// Which of JSON's six kinds of value a [`Value`] is.
72///
73/// Useful for error messages ("expected a string, found an array").
74///
75/// # Examples
76///
77/// ```
78/// use jsonx_lib::{parse, Kind};
79///
80/// let doc = parse("[1]")?;
81/// assert_eq!(doc.kind(), Kind::Array);
82/// assert_eq!(doc[0].kind().to_string(), "number");
83/// # Ok::<(), jsonx_lib::Error>(())
84/// ```
85#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
86pub enum Kind {
87    /// `null`.
88    Null,
89    /// `true` or `false`.
90    Bool,
91    /// A number.
92    Number,
93    /// A string.
94    String,
95    /// An array.
96    Array,
97    /// An object.
98    Object,
99}
100
101impl Kind {
102    /// The kind's name in lowercase: `null`, `boolean`, `number`, `string`,
103    /// `array`, or `object`.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// assert_eq!(jsonx_lib::Kind::Bool.name(), "boolean");
109    /// ```
110    #[must_use]
111    pub const fn name(self) -> &'static str {
112        match self {
113            Self::Null => "null",
114            Self::Bool => "boolean",
115            Self::Number => "number",
116            Self::String => "string",
117            Self::Array => "array",
118            Self::Object => "object",
119        }
120    }
121}
122
123impl fmt::Display for Kind {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str(self.name())
126    }
127}
128
129impl<'a> Value<'a> {
130    /// Which kind of value this is.
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// use jsonx_lib::{json, Kind};
136    ///
137    /// assert_eq!(json!({}).kind(), Kind::Object);
138    /// ```
139    #[must_use]
140    pub const fn kind(&self) -> Kind {
141        match self {
142            Self::Null => Kind::Null,
143            Self::Bool(_) => Kind::Bool,
144            Self::Number(_) => Kind::Number,
145            Self::String(_) => Kind::String,
146            Self::Array(_) => Kind::Array,
147            Self::Object(_) => Kind::Object,
148        }
149    }
150
151    /// Whether the value is `null`.
152    ///
153    /// # Examples
154    ///
155    /// ```
156    /// assert!(jsonx_lib::parse("null")?.is_null());
157    /// # Ok::<(), jsonx_lib::Error>(())
158    /// ```
159    #[inline]
160    #[must_use]
161    pub const fn is_null(&self) -> bool {
162        matches!(self, Self::Null)
163    }
164
165    /// Whether the value is `true` or `false`.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// assert!(jsonx_lib::json!(false).is_bool());
171    /// ```
172    #[inline]
173    #[must_use]
174    pub const fn is_bool(&self) -> bool {
175        matches!(self, Self::Bool(_))
176    }
177
178    /// Whether the value is a number.
179    ///
180    /// # Examples
181    ///
182    /// ```
183    /// assert!(jsonx_lib::json!(1.5).is_number());
184    /// ```
185    #[inline]
186    #[must_use]
187    pub const fn is_number(&self) -> bool {
188        matches!(self, Self::Number(_))
189    }
190
191    /// Whether the value is a string.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// assert!(jsonx_lib::json!("s").is_string());
197    /// ```
198    #[inline]
199    #[must_use]
200    pub const fn is_string(&self) -> bool {
201        matches!(self, Self::String(_))
202    }
203
204    /// Whether the value is an array.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// assert!(jsonx_lib::json!([]).is_array());
210    /// ```
211    #[inline]
212    #[must_use]
213    pub const fn is_array(&self) -> bool {
214        matches!(self, Self::Array(_))
215    }
216
217    /// Whether the value is an object.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// assert!(jsonx_lib::json!({}).is_object());
223    /// ```
224    #[inline]
225    #[must_use]
226    pub const fn is_object(&self) -> bool {
227        matches!(self, Self::Object(_))
228    }
229
230    /// The boolean, if the value is one.
231    ///
232    /// # Examples
233    ///
234    /// ```
235    /// assert_eq!(jsonx_lib::parse("true")?.as_bool(), Some(true));
236    /// assert_eq!(jsonx_lib::parse("1")?.as_bool(), None);
237    /// # Ok::<(), jsonx_lib::Error>(())
238    /// ```
239    #[inline]
240    #[must_use]
241    pub const fn as_bool(&self) -> Option<bool> {
242        match self {
243            Self::Bool(b) => Some(*b),
244            _ => None,
245        }
246    }
247
248    /// The number, if the value is one.
249    ///
250    /// # Examples
251    ///
252    /// ```
253    /// let doc = jsonx_lib::parse("6.02e23")?;
254    /// assert_eq!(doc.as_number().map(|n| n.as_str()), Some("6.02e23"));
255    /// # Ok::<(), jsonx_lib::Error>(())
256    /// ```
257    #[inline]
258    #[must_use]
259    pub const fn as_number(&self) -> Option<&Number<'a>> {
260        match self {
261            Self::Number(n) => Some(n),
262            _ => None,
263        }
264    }
265
266    /// The value as an `i64`: see [`Number::as_i64`]. `None` for anything but
267    /// an integer number in range.
268    ///
269    /// # Examples
270    ///
271    /// ```
272    /// let doc = jsonx_lib::parse("[-5, 5.5, \"5\"]")?;
273    /// assert_eq!(doc[0].as_i64(), Some(-5));
274    /// assert_eq!(doc[1].as_i64(), None);
275    /// assert_eq!(doc[2].as_i64(), None);
276    /// # Ok::<(), jsonx_lib::Error>(())
277    /// ```
278    #[must_use]
279    pub fn as_i64(&self) -> Option<i64> {
280        self.as_number().and_then(Number::as_i64)
281    }
282
283    /// The value as a `u64`: see [`Number::as_u64`].
284    ///
285    /// # Examples
286    ///
287    /// ```
288    /// assert_eq!(jsonx_lib::parse("42")?.as_u64(), Some(42));
289    /// assert_eq!(jsonx_lib::parse("-42")?.as_u64(), None);
290    /// # Ok::<(), jsonx_lib::Error>(())
291    /// ```
292    #[must_use]
293    pub fn as_u64(&self) -> Option<u64> {
294        self.as_number().and_then(Number::as_u64)
295    }
296
297    /// The value as an `i128`: see [`Number::as_i128`].
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// let doc = jsonx_lib::parse("-170141183460469231731687303715884105728")?;
303    /// assert_eq!(doc.as_i128(), Some(i128::MIN));
304    /// # Ok::<(), jsonx_lib::Error>(())
305    /// ```
306    #[must_use]
307    pub fn as_i128(&self) -> Option<i128> {
308        self.as_number().and_then(Number::as_i128)
309    }
310
311    /// The value as a `u128`: see [`Number::as_u128`].
312    ///
313    /// # Examples
314    ///
315    /// ```
316    /// let doc = jsonx_lib::parse("340282366920938463463374607431768211455")?;
317    /// assert_eq!(doc.as_u128(), Some(u128::MAX));
318    /// # Ok::<(), jsonx_lib::Error>(())
319    /// ```
320    #[must_use]
321    pub fn as_u128(&self) -> Option<u128> {
322        self.as_number().and_then(Number::as_u128)
323    }
324
325    /// The value as an `f64`: see [`Number::as_f64`]. Integers convert too.
326    ///
327    /// # Examples
328    ///
329    /// ```
330    /// assert_eq!(jsonx_lib::parse("2")?.as_f64(), Some(2.0));
331    /// assert_eq!(jsonx_lib::parse("\"2\"")?.as_f64(), None);
332    /// # Ok::<(), jsonx_lib::Error>(())
333    /// ```
334    #[must_use]
335    pub fn as_f64(&self) -> Option<f64> {
336        self.as_number().and_then(Number::as_f64)
337    }
338
339    /// The string, if the value is one.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// assert_eq!(jsonx_lib::parse(r#""a\tb""#)?.as_str(), Some("a\tb"));
345    /// # Ok::<(), jsonx_lib::Error>(())
346    /// ```
347    #[inline]
348    #[must_use]
349    pub fn as_str(&self) -> Option<&str> {
350        match self {
351            Self::String(s) => Some(s),
352            _ => None,
353        }
354    }
355
356    /// The array, if the value is one.
357    ///
358    /// # Examples
359    ///
360    /// ```
361    /// let doc = jsonx_lib::parse("[1, 2, 3]")?;
362    /// assert_eq!(doc.as_array().map(|a| a.len()), Some(3));
363    /// # Ok::<(), jsonx_lib::Error>(())
364    /// ```
365    #[inline]
366    #[must_use]
367    pub const fn as_array(&self) -> Option<&Array<'a>> {
368        match self {
369            Self::Array(a) => Some(a),
370            _ => None,
371        }
372    }
373
374    /// The array, mutably, if the value is one.
375    ///
376    /// # Examples
377    ///
378    /// ```
379    /// let mut v = jsonx_lib::json!([1]);
380    /// v.as_array_mut().unwrap().push(2.into());
381    /// assert_eq!(v.to_string(), "[1,2]");
382    /// ```
383    #[inline]
384    #[must_use]
385    pub fn as_array_mut(&mut self) -> Option<&mut Array<'a>> {
386        match self {
387            Self::Array(a) => Some(a),
388            _ => None,
389        }
390    }
391
392    /// The object, if the value is one.
393    ///
394    /// # Examples
395    ///
396    /// ```
397    /// let doc = jsonx_lib::parse(r#"{"k": 1}"#)?;
398    /// assert!(doc.as_object().is_some_and(|o| o.contains_key("k")));
399    /// # Ok::<(), jsonx_lib::Error>(())
400    /// ```
401    #[inline]
402    #[must_use]
403    pub const fn as_object(&self) -> Option<&Object<'a>> {
404        match self {
405            Self::Object(o) => Some(o),
406            _ => None,
407        }
408    }
409
410    /// The object, mutably, if the value is one.
411    ///
412    /// # Examples
413    ///
414    /// ```
415    /// let mut v = jsonx_lib::json!({});
416    /// v.as_object_mut().unwrap().insert("k", "v");
417    /// assert_eq!(v.to_string(), r#"{"k":"v"}"#);
418    /// ```
419    #[inline]
420    #[must_use]
421    pub fn as_object_mut(&mut self) -> Option<&mut Object<'a>> {
422        match self {
423            Self::Object(o) => Some(o),
424            _ => None,
425        }
426    }
427
428    /// The value of the member named `key`, if this is an object that has one.
429    ///
430    /// # Examples
431    ///
432    /// ```
433    /// let doc = jsonx_lib::parse(r#"{"jsonrpc": "2.0", "id": 1}"#)?;
434    /// assert_eq!(doc.get("jsonrpc").and_then(|v| v.as_str()), Some("2.0"));
435    /// assert!(doc.get("method").is_none());
436    /// # Ok::<(), jsonx_lib::Error>(())
437    /// ```
438    #[must_use]
439    pub fn get(&self, key: &str) -> Option<&Value<'a>> {
440        self.as_object().and_then(|o| o.get(key))
441    }
442
443    /// A mutable reference to the member named `key`, if this is an object
444    /// that has one.
445    ///
446    /// # Examples
447    ///
448    /// ```
449    /// let mut v = jsonx_lib::json!({ "n": 1 });
450    /// if let Some(n) = v.get_mut("n") {
451    ///     *n = 2.into();
452    /// }
453    /// assert_eq!(v["n"], 2);
454    /// ```
455    #[must_use]
456    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'a>> {
457        self.as_object_mut().and_then(|o| o.get_mut(key))
458    }
459
460    /// The item at `index`, if this is an array that long.
461    ///
462    /// # Examples
463    ///
464    /// ```
465    /// let doc = jsonx_lib::parse("[10, 20]")?;
466    /// assert_eq!(doc.get_index(1).and_then(|v| v.as_i64()), Some(20));
467    /// assert!(doc.get_index(2).is_none());
468    /// # Ok::<(), jsonx_lib::Error>(())
469    /// ```
470    #[must_use]
471    pub fn get_index(&self, index: usize) -> Option<&Value<'a>> {
472        self.as_array().and_then(|a| a.get(index))
473    }
474
475    /// Looks a value up by [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)
476    /// JSON Pointer: `""` is the whole value, `/a/0` is item 0 of member `a`,
477    /// and `~1` and `~0` stand for `/` and `~` inside a key.
478    ///
479    /// Returns `None` when the pointer is malformed (it does not start with
480    /// `/`, or has a `~` not followed by `0` or `1`) or names something that
481    /// is not there. An array index must be a plain decimal number without
482    /// leading zeros; `-` (past the end) never resolves.
483    ///
484    /// # Examples
485    ///
486    /// ```
487    /// let doc = jsonx_lib::parse(r#"{"a/b": {"c~d": [true]}}"#)?;
488    /// assert_eq!(doc.pointer("/a~1b/c~0d/0"), Some(&true.into()));
489    /// assert_eq!(doc.pointer(""), Some(&doc));
490    /// assert!(doc.pointer("/a~1b/c~0d/01").is_none());
491    /// assert!(doc.pointer("a").is_none());
492    /// # Ok::<(), jsonx_lib::Error>(())
493    /// ```
494    #[must_use]
495    pub fn pointer(&self, pointer: &str) -> Option<&Value<'a>> {
496        if pointer.is_empty() {
497            return Some(self);
498        }
499        let rest = pointer.strip_prefix('/')?;
500        let mut target = self;
501        for token in rest.split('/') {
502            let token = unescape_pointer_token(token)?;
503            target = match target {
504                Self::Object(o) => o.get(&token)?,
505                Self::Array(a) => a.get(array_index(&token)?)?,
506                _ => return None,
507            };
508        }
509        Some(target)
510    }
511
512    /// A mutable reference to the value at a JSON Pointer, as
513    /// [`pointer`](Self::pointer) finds it.
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// let mut v = jsonx_lib::json!({ "a": [1, 2] });
519    /// if let Some(item) = v.pointer_mut("/a/1") {
520    ///     *item = "two".into();
521    /// }
522    /// assert_eq!(v.to_string(), r#"{"a":[1,"two"]}"#);
523    /// assert!(v.pointer_mut("/a/9").is_none());
524    /// ```
525    #[must_use]
526    pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut Value<'a>> {
527        if pointer.is_empty() {
528            return Some(self);
529        }
530        let rest = pointer.strip_prefix('/')?;
531        let mut target = self;
532        for token in rest.split('/') {
533            let token = unescape_pointer_token(token)?;
534            target = match target {
535                Self::Object(o) => o.get_mut(&token)?,
536                Self::Array(a) => a.get_mut(array_index(&token)?)?,
537                _ => return None,
538            };
539        }
540        Some(target)
541    }
542
543    /// Takes the value out, leaving `null` in its place.
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// let mut v = jsonx_lib::json!({ "big": [1, 2, 3] });
549    /// let big = v.get_mut("big").map(|b| b.take()).unwrap_or_default();
550    /// assert_eq!(big.to_string(), "[1,2,3]");
551    /// assert!(v["big"].is_null());
552    /// ```
553    #[inline]
554    pub fn take(&mut self) -> Value<'a> {
555        core::mem::take(self)
556    }
557
558    /// Copies every borrowed key, string, and number so the value no longer
559    /// borrows from the input. Iterative at any depth.
560    ///
561    /// # Examples
562    ///
563    /// ```
564    /// use jsonx_lib::{parse, Value};
565    ///
566    /// fn load() -> Result<Value<'static>, jsonx_lib::Error> {
567    ///     let text = String::from(r#"{"kept": "after the text is gone"}"#);
568    ///     Ok(parse(&text)?.into_owned())
569    /// }
570    /// assert_eq!(load()?["kept"], "after the text is gone");
571    /// # Ok::<(), jsonx_lib::Error>(())
572    /// ```
573    #[must_use]
574    pub fn into_owned(self) -> Value<'static> {
575        tree::into_owned(self)
576    }
577}
578
579/// Decodes `~1` and `~0` in one JSON Pointer reference token.
580pub(crate) fn unescape_pointer_token(token: &str) -> Option<Cow<'_, str>> {
581    if !token.contains('~') {
582        return Some(Cow::Borrowed(token));
583    }
584    let mut out = String::with_capacity(token.len());
585    let mut chars = token.chars();
586    while let Some(c) = chars.next() {
587        if c == '~' {
588            match chars.next() {
589                Some('0') => out.push('~'),
590                Some('1') => out.push('/'),
591                _ => return None,
592            }
593        } else {
594            out.push(c);
595        }
596    }
597    Some(Cow::Owned(out))
598}
599
600/// An RFC 6901 array index: `0`, or a decimal without a leading zero.
601pub(crate) fn array_index(token: &str) -> Option<usize> {
602    let digits = token.as_bytes();
603    let canonical = !digits.is_empty()
604        && digits.iter().all(u8::is_ascii_digit)
605        && (digits.len() == 1 || digits.first() != Some(&b'0'));
606    if canonical { token.parse().ok() } else { None }
607}
608
609impl Clone for Value<'_> {
610    fn clone(&self) -> Self {
611        match self {
612            Self::Null => Self::Null,
613            Self::Bool(b) => Self::Bool(*b),
614            Self::Number(n) => Self::Number(n.clone()),
615            Self::String(s) => Self::String(s.clone()),
616            Self::Array(a) => Self::Array(a.clone()),
617            Self::Object(o) => Self::Object(o.clone()),
618        }
619    }
620}
621
622impl PartialEq for Value<'_> {
623    fn eq(&self, other: &Self) -> bool {
624        tree::eq(self, other)
625    }
626}
627
628impl Eq for Value<'_> {}
629
630impl Hash for Value<'_> {
631    /// Hashes consistently with `==`: numbers by their text, object members
632    /// in order. Iterative at any depth.
633    fn hash<H: Hasher>(&self, state: &mut H) {
634        tree::hash(self, state);
635    }
636}
637
638impl<'a> Index<&str> for Value<'a> {
639    type Output = Value<'a>;
640
641    /// The member named `key`, or `null` if this is not an object or has no
642    /// such member. Never panics.
643    fn index(&self, key: &str) -> &Value<'a> {
644        self.get(key).unwrap_or(&NULL)
645    }
646}
647
648impl<'a> Index<usize> for Value<'a> {
649    type Output = Value<'a>;
650
651    /// The item at `index`, or `null` if this is not an array or is shorter.
652    /// Never panics.
653    fn index(&self, index: usize) -> &Value<'a> {
654        self.get_index(index).unwrap_or(&NULL)
655    }
656}
657
658// ---- Conversions into `Value` ------------------------------------------------
659
660impl From<bool> for Value<'_> {
661    #[inline]
662    fn from(b: bool) -> Self {
663        Self::Bool(b)
664    }
665}
666
667macro_rules! from_integer {
668    ($($t:ty),*) => {$(
669        impl From<$t> for Value<'_> {
670            #[inline]
671            fn from(n: $t) -> Self {
672                Self::Number(Number::from(n))
673            }
674        }
675    )*};
676}
677
678from_integer!(
679    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
680);
681
682impl From<f64> for Value<'_> {
683    /// A number in shortest round-trip form (see [`Number::from_f64`]), or
684    /// `null` for NaN and the infinities, which JSON cannot represent.
685    fn from(x: f64) -> Self {
686        Number::from_f64(x).map_or(Self::Null, Self::Number)
687    }
688}
689
690impl From<f32> for Value<'_> {
691    /// The `f32` widened to `f64` (exactly), then as `From<f64>`.
692    fn from(x: f32) -> Self {
693        Self::from(f64::from(x))
694    }
695}
696
697impl<'a> From<Number<'a>> for Value<'a> {
698    #[inline]
699    fn from(n: Number<'a>) -> Self {
700        Self::Number(n)
701    }
702}
703
704impl<'a> From<&'a str> for Value<'a> {
705    #[inline]
706    fn from(s: &'a str) -> Self {
707        Self::String(Cow::Borrowed(s))
708    }
709}
710
711impl<'a> From<&'a String> for Value<'a> {
712    #[inline]
713    fn from(s: &'a String) -> Self {
714        Self::String(Cow::Borrowed(s))
715    }
716}
717
718impl From<String> for Value<'_> {
719    #[inline]
720    fn from(s: String) -> Self {
721        Self::String(Cow::Owned(s))
722    }
723}
724
725impl<'a> From<Cow<'a, str>> for Value<'a> {
726    #[inline]
727    fn from(s: Cow<'a, str>) -> Self {
728        Self::String(s)
729    }
730}
731
732impl From<char> for Value<'_> {
733    #[inline]
734    fn from(c: char) -> Self {
735        Self::String(Cow::Owned(c.to_string()))
736    }
737}
738
739impl<'a> From<Array<'a>> for Value<'a> {
740    #[inline]
741    fn from(a: Array<'a>) -> Self {
742        Self::Array(a)
743    }
744}
745
746impl<'a> From<Object<'a>> for Value<'a> {
747    #[inline]
748    fn from(o: Object<'a>) -> Self {
749        Self::Object(o)
750    }
751}
752
753impl<'a, T: Into<Value<'a>>> From<Vec<T>> for Value<'a> {
754    fn from(items: Vec<T>) -> Self {
755        Self::Array(items.into_iter().collect())
756    }
757}
758
759impl<'a, T: Into<Value<'a>>> From<Option<T>> for Value<'a> {
760    /// `None` is `null`.
761    fn from(value: Option<T>) -> Self {
762        value.map_or(Self::Null, Into::into)
763    }
764}
765
766impl From<()> for Value<'_> {
767    /// `()` is `null`.
768    #[inline]
769    fn from((): ()) -> Self {
770        Self::Null
771    }
772}
773
774impl<'a, T: Into<Value<'a>>> FromIterator<T> for Value<'a> {
775    /// Collects into an array.
776    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
777        Self::Array(iter.into_iter().collect())
778    }
779}
780
781// ---- Comparisons with Rust values --------------------------------------------
782
783impl PartialEq<str> for Value<'_> {
784    fn eq(&self, other: &str) -> bool {
785        self.as_str() == Some(other)
786    }
787}
788
789impl PartialEq<&str> for Value<'_> {
790    fn eq(&self, other: &&str) -> bool {
791        self.as_str() == Some(*other)
792    }
793}
794
795impl PartialEq<String> for Value<'_> {
796    fn eq(&self, other: &String) -> bool {
797        self.as_str() == Some(other.as_str())
798    }
799}
800
801impl PartialEq<bool> for Value<'_> {
802    fn eq(&self, other: &bool) -> bool {
803        self.as_bool() == Some(*other)
804    }
805}
806
807impl PartialEq<f32> for Value<'_> {
808    /// Compares the number's value, read as an `f32` (see
809    /// [`Number::as_f32`]).
810    fn eq(&self, other: &f32) -> bool {
811        self.as_number().and_then(Number::as_f32) == Some(*other)
812    }
813}
814
815impl PartialEq<i128> for Value<'_> {
816    /// True when the value is an integer number equal to `other`.
817    fn eq(&self, other: &i128) -> bool {
818        self.as_i128() == Some(*other)
819    }
820}
821
822impl PartialEq<u128> for Value<'_> {
823    /// True when the value is an integer number equal to `other`.
824    fn eq(&self, other: &u128) -> bool {
825        self.as_u128() == Some(*other)
826    }
827}
828
829impl PartialEq<f64> for Value<'_> {
830    /// Compares the number's value, so `1.0`, `1`, and `1e0` all equal `1.0`.
831    fn eq(&self, other: &f64) -> bool {
832        self.as_f64() == Some(*other)
833    }
834}
835
836macro_rules! eq_signed {
837    ($($t:ty),*) => {$(
838        impl PartialEq<$t> for Value<'_> {
839            /// True when the value is an integer number equal to `other`.
840            fn eq(&self, other: &$t) -> bool {
841                self.as_i64() == Some(i64::from(*other))
842            }
843        }
844    )*};
845}
846
847macro_rules! eq_unsigned {
848    ($($t:ty),*) => {$(
849        impl PartialEq<$t> for Value<'_> {
850            /// True when the value is an integer number equal to `other`.
851            fn eq(&self, other: &$t) -> bool {
852                self.as_u64() == Some(u64::from(*other))
853            }
854        }
855    )*};
856}
857
858eq_signed!(i8, i16, i32, i64);
859eq_unsigned!(u8, u16, u32, u64);
860
861impl PartialEq<isize> for Value<'_> {
862    /// True when the value is an integer number equal to `other`.
863    fn eq(&self, other: &isize) -> bool {
864        i64::try_from(*other).is_ok_and(|n| self.as_i64() == Some(n))
865    }
866}
867
868impl PartialEq<usize> for Value<'_> {
869    /// True when the value is an integer number equal to `other`.
870    fn eq(&self, other: &usize) -> bool {
871        u64::try_from(*other).is_ok_and(|n| self.as_u64() == Some(n))
872    }
873}
874
875#[cfg(test)]
876mod tests {
877    use super::*;
878
879    #[test]
880    fn test_value_is_four_words() {
881        assert!(core::mem::size_of::<Value<'_>>() <= 4 * core::mem::size_of::<usize>());
882    }
883
884    #[test]
885    fn test_pointer_tokens() {
886        assert_eq!(array_index("0"), Some(0));
887        assert_eq!(array_index("10"), Some(10));
888        assert_eq!(array_index("01"), None);
889        assert_eq!(array_index("-"), None);
890        assert_eq!(array_index(""), None);
891        assert_eq!(array_index("+1"), None);
892        assert_eq!(unescape_pointer_token("a~1b~0c").as_deref(), Some("a/b~c"));
893        assert_eq!(unescape_pointer_token("~2"), None);
894        assert_eq!(unescape_pointer_token("~"), None);
895    }
896
897    #[test]
898    fn test_predicates_wide_integers_and_comparisons() {
899        let v = crate::json!([null, true, 1, "s", [], {}]);
900        let kinds: alloc::vec::Vec<[bool; 5]> = v
901            .as_array()
902            .map(|a| {
903                a.iter()
904                    .map(|x| {
905                        [
906                            x.is_bool(),
907                            x.is_number(),
908                            x.is_string(),
909                            x.is_array(),
910                            x.is_object(),
911                        ]
912                    })
913                    .collect()
914            })
915            .unwrap_or_default();
916        assert_eq!(kinds.iter().filter(|k| k.iter().any(|&b| b)).count(), 5);
917        assert!(v[0].is_null() && !v[1].is_null());
918        assert_eq!(Value::from(u128::MAX), u128::MAX);
919        assert_eq!(Value::from(i128::MIN), i128::MIN);
920        assert_ne!(Value::from(1), 2i128);
921        assert_eq!(Value::from(0.5), 0.5f32);
922        assert_ne!(Value::from("0.5"), 0.5f32);
923        assert_eq!(Value::from(-1).as_u128(), None);
924    }
925
926    /// FNV-1a, so the test needs nothing from `std`.
927    struct Fnv(u64);
928
929    impl Hasher for Fnv {
930        fn finish(&self) -> u64 {
931            self.0
932        }
933        fn write(&mut self, bytes: &[u8]) {
934            for &b in bytes {
935                self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
936            }
937        }
938    }
939
940    #[test]
941    fn test_hash_agrees_with_eq() {
942        let h = |v: &Value<'_>| {
943            let mut state = Fnv(0xcbf2_9ce4_8422_2325);
944            v.hash(&mut state);
945            state.finish()
946        };
947        let a = crate::json!({ "k": [1, { "x": "y" }], "m": null });
948        let b = crate::parse(r#"{"k":[1,{"x":"y"}],"m":null}"#).unwrap_or_default();
949        assert_eq!(a, b);
950        assert_eq!(h(&a), h(&b));
951        let reordered = crate::parse(r#"{"m":null,"k":[1,{"x":"y"}]}"#).unwrap_or_default();
952        assert_ne!(h(&a), h(&reordered));
953        assert_ne!(
954            h(&Value::from(1)),
955            h(&crate::parse("1.0").unwrap_or_default())
956        );
957        assert_ne!(h(&crate::json!([[]])), h(&crate::json!([[], []])));
958        assert_ne!(h(&crate::json!(["a"])), h(&crate::json!({ "a": null })));
959    }
960
961    #[test]
962    fn test_index_out_of_shape_is_null() {
963        let v = Value::from(3);
964        assert!(v["k"].is_null());
965        assert!(v[0].is_null());
966    }
967}