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