Skip to main content

deser_value/
value.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::hash::{Hash, Hasher};
4use std::ops::{Deref, DerefMut, Range};
5use std::sync::Arc;
6
7use deser_core::ext::{BorrowedExtension, ExtValue, Extension, RawInput};
8use deser_core::{Atom, Bytes, EventData, Implicit, ImplicitValue, Position};
9
10use crate::index::ValueIndex;
11use crate::map::Map;
12use crate::seq::Seq;
13use crate::tree;
14
15/// A dynamic value.
16///
17/// A value is made of its [`Kind`], which holds the actual data, and
18/// optional [`Meta`] data.  The value dereferences to its kind, which is
19/// where the accessors are defined and what is matched on:
20///
21/// ```
22/// use deser_value::{value, Kind};
23///
24/// let value = value!({"name": "Jane", "roles": ["admin"]});
25/// assert_eq!(value["name"].as_str(), Some("Jane"));
26///
27/// match &*value["roles"] {
28///     Kind::Seq(roles) => assert_eq!(roles.len(), 1),
29///     _ => unreachable!(),
30/// }
31/// ```
32///
33/// # Meta Data
34///
35/// Values retain information that is not part of the data model.  This is
36/// held in the [`Meta`] of a value, which is only allocated if there is
37/// such information:
38///
39/// * The [event data](deser_core::State::event) of the value, for instance CBOR
40///   tags or formatting hints.  It's captured when the value is
41///   deserialized and attached again when it's serialized.
42/// * The [`Span`] of the value in the input, if the format tracks
43///   locations.  Values that are deserialized from a value with spans report
44///   errors at the original location.
45///
46/// Meta data is ignored when values are compared or hashed and it's not
47/// shown in the debug output.
48///
49/// # Numbers
50///
51/// Integers are held as [`Kind::U64`] and [`Kind::I64`].  Values created by
52/// this crate hold non-negative integers as `U64` and integers which do not
53/// fit into 64 bits (`u128` and `i128`) as [`Kind::Ext`].  Integers compare
54/// by their value: `I64(1)` is equal to `U64(1)`.  Floats compare by
55/// their bits, which means that `NaN` is equal to itself and `-0.0` is not
56/// equal to `0.0`.
57///
58/// # Extensions
59///
60/// Values which extend the data model (see [`deser::ext`](deser_core::ext)) are held as
61/// [`Kind::Ext`].  They retain their type and are serialized as extension
62/// values again.  The accessors (such as [`as_str`](Kind::as_str)) look at
63/// them through their fallback.
64///
65/// # Nesting
66///
67/// All operations on values (including dropping, cloning, comparing and
68/// formatting) are implemented without recursion, deeply nested values do
69/// not overflow the stack.
70pub struct Value {
71    pub(crate) kind: Kind,
72    pub(crate) meta: Option<Box<Meta>>,
73}
74
75/// The data of a [`Value`].
76///
77/// See [`Value`] for more information.
78#[non_exhaustive]
79pub enum Kind {
80    Null,
81    Bool(bool),
82    /// An unsigned integer.
83    U64(u64),
84    /// A signed integer.
85    ///
86    /// Values created by this crate only use this for negative integers.
87    I64(i64),
88    /// A single precision float.
89    ///
90    /// It keeps the precision for serialization (`0.1f32` is written as
91    /// `0.1`), otherwise it behaves like the same value as `F64`: they
92    /// compare equal and hash the same.
93    F32(f32),
94    /// A double precision float.
95    F64(f64),
96    Char(char),
97    Str(String),
98    /// The lexical form of a value whose type the format cannot express.
99    ///
100    /// This is created from [`Atom::Lexical`], for instance for the keys of
101    /// JSON objects.  It's serialized as lexical atom again, so types that
102    /// parse lexical atoms (like numbers) can be deserialized from it.
103    /// Otherwise it behaves like a string: it compares equal to and hashes
104    /// like the same [`Str`](Kind::Str) and the accessors for strings
105    /// return it.
106    Lexical(String),
107    Bytes(Bytes<'static>),
108    /// A value extending the data model.
109    Ext(ExtValue<'static>),
110    /// A value whose type the format inferred from its text.
111    ///
112    /// This is created from [`Atom::Implicit`], for instance for the plain
113    /// scalars of YAML (`42`, `1.10`, `true` or `~`).  It's serialized as
114    /// implicit atom again, so types that do not accept the value (like
115    /// strings) can be deserialized from its text.  Otherwise it behaves
116    /// like its value: it compares equal to and hashes like the same
117    /// value, the accessors (like [`as_f64`](Kind::as_f64)) return it and
118    /// [`as_str`](Kind::as_str) does not return the text.
119    Implicit(Implicit<'static>),
120    Seq(Seq),
121    Map(Map),
122}
123
124/// Meta data of a [`Value`].
125///
126/// See [`Value`] for more information.
127#[derive(Clone, Default, Debug)]
128pub struct Meta {
129    event_data: EventData,
130    span: Option<Span>,
131}
132
133impl Meta {
134    /// Creates empty meta data.
135    pub fn new() -> Meta {
136        Meta::default()
137    }
138
139    /// Returns the event data of the value.
140    ///
141    /// See [`EventData`] and [`deser::State::event`](deser_core::State::event).
142    pub fn event_data(&self) -> &EventData {
143        &self.event_data
144    }
145
146    /// Returns the event data of the value mutably.
147    pub fn event_data_mut(&mut self) -> &mut EventData {
148        &mut self.event_data
149    }
150
151    /// Returns the span of the value in the input.
152    pub fn span(&self) -> Option<&Span> {
153        self.span.as_ref()
154    }
155
156    /// Sets the span of the value.
157    pub fn set_span(&mut self, span: Option<Span>) {
158        self.span = span;
159    }
160
161    /// Returns `true` if the meta data is empty.
162    pub fn is_empty(&self) -> bool {
163        self.event_data.is_empty() && self.span.is_none()
164    }
165
166    pub(crate) fn from_parts(event_data: EventData, span: Option<Span>) -> Meta {
167        Meta { event_data, span }
168    }
169
170    pub(crate) fn span_mut(&mut self) -> Option<&mut Span> {
171        self.span.as_mut()
172    }
173}
174
175/// The location of a value in its input.
176///
177/// Spans are captured when values are deserialized from a format that
178/// tracks locations (see [`deser::Source`](deser_core::Source)), which is
179/// requested with [`TrackLocations`](deser_core::TrackLocations) in the
180/// context.
181#[derive(Clone)]
182pub struct Span {
183    range: Range<usize>,
184    // for maps and sequences: the end of the start event and the start of
185    // the end event.
186    pub(crate) inner: Option<(usize, usize)>,
187    source: Arc<str>,
188}
189
190impl Span {
191    /// Creates a span of a range in a source.
192    pub fn new(range: Range<usize>, source: Arc<str>) -> Span {
193        Span {
194            range,
195            inner: None,
196            source,
197        }
198    }
199
200    /// Returns the byte range in the source.
201    pub fn range(&self) -> Range<usize> {
202        self.range.clone()
203    }
204
205    /// Returns the source.
206    pub fn source(&self) -> &Arc<str> {
207        &self.source
208    }
209
210    /// Returns the text of the span in the source.
211    pub fn text(&self) -> Option<&str> {
212        self.source.get(self.range.clone())
213    }
214
215    /// Returns the position (with line and column) of the start of the span.
216    pub fn start(&self) -> Position {
217        Position::of(self.source.as_bytes(), self.range.start)
218    }
219
220    /// Returns the position (with line and column) of the end of the span.
221    ///
222    /// The end is exclusive.
223    pub fn end(&self) -> Position {
224        Position::of(self.source.as_bytes(), self.range.end)
225    }
226
227    pub(crate) fn start_range(&self) -> (usize, usize) {
228        match self.inner {
229            Some((start_end, _)) => (self.range.start, start_end),
230            None => (self.range.start, self.range.end),
231        }
232    }
233
234    pub(crate) fn end_range(&self) -> Option<(usize, usize)> {
235        self.inner.map(|(_, end_start)| (end_start, self.range.end))
236    }
237
238    pub(crate) fn set_end(&mut self, end_start: usize, end: usize) {
239        self.inner = Some((self.range.end, end_start));
240        self.range.end = end;
241    }
242}
243
244impl fmt::Debug for Span {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        f.debug_struct("Span")
247            .field("range", &self.range)
248            .finish_non_exhaustive()
249    }
250}
251
252static NULL: Value = Value::null();
253
254impl Value {
255    /// Creates a null value.
256    pub const fn null() -> Value {
257        Value {
258            kind: Kind::Null,
259            meta: None,
260        }
261    }
262
263    /// Creates a value from its kind.
264    pub const fn new(kind: Kind) -> Value {
265        Value { kind, meta: None }
266    }
267
268    /// Creates a value holding an extension value.
269    ///
270    /// ```
271    /// use deser::ext::Uuid;
272    /// use deser_value::Value;
273    ///
274    /// let value = Value::ext(Uuid([0; 16]));
275    /// assert!(value.downcast_ext::<Uuid>().is_some());
276    /// ```
277    pub fn ext<T: Extension>(value: T) -> Value {
278        Value::from(ExtValue::owned(value))
279    }
280
281    /// Creates a value holding bytes.
282    pub fn bytes<B: Into<Vec<u8>>>(data: B) -> Value {
283        Value::new(Kind::Bytes(Bytes::new(data.into())))
284    }
285
286    /// Returns the kind of the value.
287    pub fn kind(&self) -> &Kind {
288        &self.kind
289    }
290
291    /// Returns the kind of the value mutably.
292    pub fn kind_mut(&mut self) -> &mut Kind {
293        &mut self.kind
294    }
295
296    /// Converts the value into its kind, discarding the meta data.
297    pub fn into_kind(self) -> Kind {
298        self.kind
299    }
300
301    /// Converts the value into its kind and meta data.
302    pub fn into_parts(self) -> (Kind, Option<Meta>) {
303        (self.kind, self.meta.map(|meta| *meta))
304    }
305
306    /// Returns the meta data of the value, if there is any.
307    pub fn meta(&self) -> Option<&Meta> {
308        self.meta.as_deref()
309    }
310
311    /// Returns the meta data of the value mutably.
312    ///
313    /// Empty meta data is created if the value has none.
314    pub fn meta_mut(&mut self) -> &mut Meta {
315        self.meta.get_or_insert_with(Default::default)
316    }
317
318    /// Removes the meta data of the value and returns it.
319    pub fn take_meta(&mut self) -> Option<Meta> {
320        self.meta.take().map(|meta| *meta)
321    }
322
323    /// Sets the meta data of the value.
324    pub fn set_meta(&mut self, meta: Option<Meta>) {
325        self.meta = meta.filter(|meta| !meta.is_empty()).map(Box::new);
326    }
327
328    /// Returns the span of the value in the input.
329    ///
330    /// This is a shortcut for the span of the [`Meta`].
331    pub fn span(&self) -> Option<&Span> {
332        self.meta().and_then(Meta::span)
333    }
334
335    /// Returns the event data of the value.
336    ///
337    /// This is a shortcut for the event data of the [`Meta`].
338    pub fn event_data(&self) -> Option<&EventData> {
339        self.meta().map(Meta::event_data)
340    }
341
342    /// Takes the value out, leaving null in its place.
343    pub fn take(&mut self) -> Value {
344        std::mem::take(self)
345    }
346}
347
348impl Default for Value {
349    fn default() -> Value {
350        Value::null()
351    }
352}
353
354impl Deref for Value {
355    type Target = Kind;
356
357    fn deref(&self) -> &Kind {
358        &self.kind
359    }
360}
361
362impl DerefMut for Value {
363    fn deref_mut(&mut self) -> &mut Kind {
364        &mut self.kind
365    }
366}
367
368impl Clone for Value {
369    fn clone(&self) -> Value {
370        Value {
371            kind: self.kind.clone(),
372            meta: self.meta.clone(),
373        }
374    }
375}
376
377impl PartialEq for Value {
378    fn eq(&self, other: &Value) -> bool {
379        tree::eq_kind(&self.kind, &other.kind)
380    }
381}
382
383impl Eq for Value {}
384
385impl Hash for Value {
386    fn hash<H: Hasher>(&self, state: &mut H) {
387        tree::hash_kind(&self.kind, state);
388    }
389}
390
391impl fmt::Debug for Value {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        tree::fmt_kind(&self.kind, f)
394    }
395}
396
397impl<I: ValueIndex> std::ops::Index<I> for Value {
398    type Output = Value;
399
400    /// Looks up a value in a sequence (by index) or a map (by key).
401    ///
402    /// Returns null if the value does not exist.
403    fn index(&self, index: I) -> &Value {
404        index.index_into(&self.kind).unwrap_or(&NULL)
405    }
406}
407
408impl<I: ValueIndex> std::ops::IndexMut<I> for Value {
409    /// Looks up a value in a sequence (by index) or a map (by key) mutably.
410    ///
411    /// Keys that do not exist are inserted with null and a null value turns
412    /// into a map if it's indexed by a key.
413    ///
414    /// # Panics
415    ///
416    /// Panics if the index is out of bounds, or if the value cannot be
417    /// indexed by the index.
418    fn index_mut(&mut self, index: I) -> &mut Value {
419        index.index_or_insert(self)
420    }
421}
422
423impl Kind {
424    /// Returns the human readable name of the kind.
425    pub fn name(&self) -> &str {
426        match self {
427            Kind::Null => "null",
428            Kind::Bool(_) => "bool",
429            Kind::U64(_) => "unsigned integer",
430            Kind::I64(_) => "signed integer",
431            Kind::F32(_) | Kind::F64(_) => "float",
432            Kind::Char(_) => "char",
433            Kind::Str(_) | Kind::Lexical(_) => "string",
434            Kind::Bytes(_) => "bytes",
435            Kind::Ext(ext) => ext.name(),
436            Kind::Implicit(value) => value.value().name(),
437            Kind::Seq(_) => "sequence",
438            Kind::Map(_) => "map",
439        }
440    }
441
442    /// Returns `true` if this is null.
443    ///
444    /// Extension values that fall back to null count as null.
445    pub fn is_null(&self) -> bool {
446        match self {
447            Kind::Null => true,
448            Kind::Ext(ext) => matches!(ext.fallback(), Atom::Null),
449            Kind::Implicit(value) => value.value() == ImplicitValue::Null,
450            _ => false,
451        }
452    }
453
454    /// Returns the value of a bool.
455    pub fn as_bool(&self) -> Option<bool> {
456        match self {
457            Kind::Bool(value) => Some(*value),
458            Kind::Ext(ext) => match ext.fallback() {
459                Atom::Bool(value) => Some(value),
460                _ => None,
461            },
462            Kind::Implicit(value) => Kind::from_implicit(value.value()).as_bool(),
463            _ => None,
464        }
465    }
466
467    /// Returns the value of an integer if it fits into `u64`.
468    pub fn as_u64(&self) -> Option<u64> {
469        self.as_i128().and_then(|value| u64::try_from(value).ok())
470    }
471
472    /// Returns the value of an integer if it fits into `i64`.
473    pub fn as_i64(&self) -> Option<i64> {
474        self.as_i128().and_then(|value| i64::try_from(value).ok())
475    }
476
477    /// Returns the value of an integer if it fits into `u128`.
478    pub fn as_u128(&self) -> Option<u128> {
479        match self {
480            Kind::Ext(ext) if ext.is::<u128>() => ext.downcast_ref::<u128>().copied(),
481            _ => self.as_i128().and_then(|value| u128::try_from(value).ok()),
482        }
483    }
484
485    /// Returns the value of an integer if it fits into `i128`.
486    pub fn as_i128(&self) -> Option<i128> {
487        match self {
488            Kind::U64(value) => Some(i128::from(*value)),
489            Kind::I64(value) => Some(i128::from(*value)),
490            Kind::Implicit(value) => Kind::from_implicit(value.value()).as_i128(),
491            Kind::Ext(ext) => {
492                if let Some(value) = ext.downcast_ref::<i128>() {
493                    Some(*value)
494                } else if let Some(value) = ext.downcast_ref::<u128>() {
495                    i128::try_from(*value).ok()
496                } else {
497                    match ext.fallback() {
498                        Atom::U64(value) => Some(i128::from(value)),
499                        Atom::I64(value) => Some(i128::from(value)),
500                        _ => None,
501                    }
502                }
503            }
504            _ => None,
505        }
506    }
507
508    /// Returns the value of a number as `f64`.
509    ///
510    /// Integers are converted, which can lose precision.
511    pub fn as_f64(&self) -> Option<f64> {
512        match self {
513            Kind::F64(value) => Some(*value),
514            Kind::F32(value) => Some(f64::from(*value)),
515            Kind::U64(value) => Some(*value as f64),
516            Kind::I64(value) => Some(*value as f64),
517            Kind::Implicit(value) => Kind::from_implicit(value.value()).as_f64(),
518            Kind::Ext(ext) => match ext.fallback() {
519                Atom::F64(value) => Some(value),
520                Atom::F32(value) => Some(f64::from(value)),
521                Atom::U64(value) => Some(value as f64),
522                Atom::I64(value) => Some(value as f64),
523                _ => None,
524            },
525            _ => None,
526        }
527    }
528
529    /// Returns the value of a char.
530    pub fn as_char(&self) -> Option<char> {
531        match self {
532            Kind::Char(value) => Some(*value),
533            _ => None,
534        }
535    }
536
537    /// Returns the value of a string.
538    ///
539    /// For extension values this returns the fallback if it's a string
540    /// that borrows from the value.
541    pub fn as_str(&self) -> Option<&str> {
542        match self {
543            Kind::Str(value) | Kind::Lexical(value) => Some(value),
544            Kind::Ext(ext) => match ext.fallback() {
545                Atom::Str(value) => value.borrowed_str(),
546                _ => None,
547            },
548            _ => None,
549        }
550    }
551
552    /// Returns the data of bytes.
553    pub fn as_bytes(&self) -> Option<&[u8]> {
554        match self {
555            Kind::Bytes(value) => Some(value.data()),
556            _ => None,
557        }
558    }
559
560    /// Returns the sequence.
561    pub fn as_seq(&self) -> Option<&Seq> {
562        match self {
563            Kind::Seq(value) => Some(value),
564            _ => None,
565        }
566    }
567
568    /// Returns the sequence mutably.
569    pub fn as_seq_mut(&mut self) -> Option<&mut Seq> {
570        match self {
571            Kind::Seq(value) => Some(value),
572            _ => None,
573        }
574    }
575
576    /// Returns the map.
577    pub fn as_map(&self) -> Option<&Map> {
578        match self {
579            Kind::Map(value) => Some(value),
580            _ => None,
581        }
582    }
583
584    /// Returns the map mutably.
585    pub fn as_map_mut(&mut self) -> Option<&mut Map> {
586        match self {
587            Kind::Map(value) => Some(value),
588            _ => None,
589        }
590    }
591
592    /// Returns the extension value.
593    pub fn as_ext(&self) -> Option<&ExtValue<'static>> {
594        match self {
595            Kind::Ext(value) => Some(value),
596            _ => None,
597        }
598    }
599
600    /// Returns the extension value if it's of type `T`.
601    ///
602    /// For extensions that borrow, use
603    /// [`downcast_ext_value`](Self::downcast_ext_value).
604    pub fn downcast_ext<T: Extension>(&self) -> Option<&T> {
605        self.as_ext().and_then(|ext| ext.downcast_ref::<T>())
606    }
607
608    /// Returns the extension value if it's of the extension with the key `K`.
609    ///
610    /// See [`BorrowedExtension`].
611    ///
612    /// ```
613    /// use deser::ext::Number;
614    /// use deser_value::Value;
615    ///
616    /// let value: Value =
617    ///     deser_json::from_str("0.10000000000000000001").unwrap();
618    /// let number = value.downcast_ext_value::<Number>().unwrap();
619    /// assert_eq!(number.as_str(), "0.10000000000000000001");
620    /// ```
621    pub fn downcast_ext_value<K: BorrowedExtension>(&self) -> Option<&K::Value<'_>> {
622        self.as_ext().and_then(|ext| ext.downcast_value_ref::<K>())
623    }
624
625    /// Returns `true` if this is a string.
626    ///
627    /// This is also `true` for [lexical](Kind::Lexical) values.
628    pub fn is_str(&self) -> bool {
629        matches!(self, Kind::Str(_) | Kind::Lexical(_))
630    }
631
632    /// Returns `true` if this is a [lexical](Kind::Lexical) value.
633    pub fn is_lexical(&self) -> bool {
634        matches!(self, Kind::Lexical(_))
635    }
636
637    /// Returns `true` if this is a sequence.
638    pub fn is_seq(&self) -> bool {
639        matches!(self, Kind::Seq(_))
640    }
641
642    /// Returns `true` if this is a map.
643    pub fn is_map(&self) -> bool {
644        matches!(self, Kind::Map(_))
645    }
646
647    /// Looks up a value in a sequence (by index) or a map (by key).
648    ///
649    /// ```
650    /// use deser_value::value;
651    ///
652    /// let value = value!({"items": [1, 2], 42: "answer"});
653    /// assert_eq!(value.get("items").and_then(|x| x.get(1)), Some(&value!(2)));
654    /// assert_eq!(value.get(&value!(42)), Some(&value!("answer")));
655    /// assert_eq!(value.get("missing"), None);
656    /// ```
657    pub fn get<I: ValueIndex>(&self, index: I) -> Option<&Value> {
658        index.index_into(self)
659    }
660
661    /// Looks up a value in a sequence (by index) or a map (by key) mutably.
662    pub fn get_mut<I: ValueIndex>(&mut self, index: I) -> Option<&mut Value> {
663        index.index_into_mut(self)
664    }
665
666    /// Returns `true` for maps and sequences that are not empty.
667    #[inline]
668    pub(crate) fn has_children(&self) -> bool {
669        match self {
670            Kind::Seq(seq) => !seq.is_empty(),
671            Kind::Map(map) => !map.is_empty(),
672            _ => false,
673        }
674    }
675}
676
677impl Clone for Kind {
678    fn clone(&self) -> Kind {
679        tree::clone_kind(self)
680    }
681}
682
683impl PartialEq for Kind {
684    fn eq(&self, other: &Kind) -> bool {
685        tree::eq_kind(self, other)
686    }
687}
688
689impl Eq for Kind {}
690
691impl Hash for Kind {
692    fn hash<H: Hasher>(&self, state: &mut H) {
693        tree::hash_kind(self, state);
694    }
695}
696
697impl fmt::Debug for Kind {
698    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699        tree::fmt_kind(self, f)
700    }
701}
702
703impl From<Kind> for Value {
704    fn from(kind: Kind) -> Value {
705        Value::new(kind)
706    }
707}
708
709impl From<()> for Value {
710    fn from(_: ()) -> Value {
711        Value::null()
712    }
713}
714
715impl From<bool> for Value {
716    fn from(value: bool) -> Value {
717        Value::new(Kind::Bool(value))
718    }
719}
720
721impl From<char> for Value {
722    fn from(value: char) -> Value {
723        Value::new(Kind::Char(value))
724    }
725}
726
727macro_rules! from_unsigned {
728    ($($ty:ty),*) => {
729        $(
730            impl From<$ty> for Value {
731                fn from(value: $ty) -> Value {
732                    Value::new(Kind::U64(value as u64))
733                }
734            }
735        )*
736    };
737}
738
739macro_rules! from_signed {
740    ($($ty:ty),*) => {
741        $(
742            impl From<$ty> for Value {
743                fn from(value: $ty) -> Value {
744                    Value::new(Kind::from_i64(value as i64))
745                }
746            }
747        )*
748    };
749}
750
751from_unsigned!(u8, u16, u32, u64, usize);
752from_signed!(i8, i16, i32, i64, isize);
753
754impl Kind {
755    /// Creates an integer, non-negative integers are held as `U64`.
756    pub(crate) fn from_i64(value: i64) -> Kind {
757        match u64::try_from(value) {
758            Ok(value) => Kind::U64(value),
759            Err(_) => Kind::I64(value),
760        }
761    }
762
763    /// Creates the kind of the value of an implicit atom.
764    pub(crate) fn from_implicit(value: ImplicitValue) -> Kind {
765        match value {
766            ImplicitValue::Null => Kind::Null,
767            ImplicitValue::Bool(value) => Kind::Bool(value),
768            ImplicitValue::U64(value) => Kind::U64(value),
769            ImplicitValue::I64(value) => Kind::from_i64(value),
770            ImplicitValue::F64(value) => Kind::F64(value),
771            _ => Kind::Null,
772        }
773    }
774
775    /// Creates a kind from an extension value.
776    ///
777    /// Integers of extensions which fit into 64 bits are converted, the
778    /// input of raw values is parsed into the value it holds.
779    pub(crate) fn from_ext(ext: ExtValue<'_>) -> Kind {
780        if let Some(input) = ext.downcast_value_ref::<RawInput>() {
781            if let Ok(value) = input.deserialize::<Value>() {
782                return value.kind;
783            }
784        } else if let Some(&value) = ext.downcast_ref::<u128>() {
785            if let Ok(value) = u64::try_from(value) {
786                return Kind::U64(value);
787            }
788        } else if let Some(&value) = ext.downcast_ref::<i128>()
789            && let Ok(value) = i64::try_from(value)
790        {
791            return Kind::from_i64(value);
792        }
793        Kind::Ext(ext.to_static())
794    }
795}
796
797impl From<u128> for Value {
798    fn from(value: u128) -> Value {
799        Value::new(match u64::try_from(value) {
800            Ok(value) => Kind::U64(value),
801            Err(_) => Kind::Ext(ExtValue::owned(value)),
802        })
803    }
804}
805
806impl From<i128> for Value {
807    fn from(value: i128) -> Value {
808        Value::new(match i64::try_from(value) {
809            Ok(value) => Kind::from_i64(value),
810            Err(_) => Kind::Ext(ExtValue::owned(value)),
811        })
812    }
813}
814
815impl From<f32> for Value {
816    fn from(value: f32) -> Value {
817        Value::new(Kind::F32(value))
818    }
819}
820
821impl From<f64> for Value {
822    fn from(value: f64) -> Value {
823        Value::new(Kind::F64(value))
824    }
825}
826
827impl From<&str> for Value {
828    fn from(value: &str) -> Value {
829        Value::new(Kind::Str(value.to_string()))
830    }
831}
832
833impl From<String> for Value {
834    fn from(value: String) -> Value {
835        Value::new(Kind::Str(value))
836    }
837}
838
839impl From<&String> for Value {
840    fn from(value: &String) -> Value {
841        Value::new(Kind::Str(value.clone()))
842    }
843}
844
845impl From<Cow<'_, str>> for Value {
846    fn from(value: Cow<'_, str>) -> Value {
847        Value::new(Kind::Str(value.into_owned()))
848    }
849}
850
851impl From<Bytes<'_>> for Value {
852    fn from(value: Bytes<'_>) -> Value {
853        Value::new(Kind::Bytes(owned_bytes(value)))
854    }
855}
856
857impl From<ExtValue<'_>> for Value {
858    /// Creates a value from an extension value.
859    ///
860    /// Integers of extensions (`u128` and `i128`) which fit into 64 bits
861    /// are converted into `U64` and `I64`.
862    fn from(value: ExtValue<'_>) -> Value {
863        Value::new(Kind::from_ext(value))
864    }
865}
866
867impl From<Seq> for Value {
868    fn from(value: Seq) -> Value {
869        Value::new(Kind::Seq(value))
870    }
871}
872
873impl From<Map> for Value {
874    fn from(value: Map) -> Value {
875        Value::new(Kind::Map(value))
876    }
877}
878
879impl<T: Into<Value>> From<Option<T>> for Value {
880    fn from(value: Option<T>) -> Value {
881        match value {
882            Some(value) => value.into(),
883            None => Value::null(),
884        }
885    }
886}
887
888impl<T: Into<Value>> From<Vec<T>> for Value {
889    fn from(value: Vec<T>) -> Value {
890        Value::from(value.into_iter().collect::<Seq>())
891    }
892}
893
894impl<T: Clone + Into<Value>> From<&[T]> for Value {
895    fn from(value: &[T]) -> Value {
896        Value::from(value.iter().cloned().collect::<Seq>())
897    }
898}
899
900impl<T: Into<Value>> FromIterator<T> for Value {
901    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Value {
902        Value::from(iter.into_iter().collect::<Seq>())
903    }
904}
905
906impl<K: Into<Value>, V: Into<Value>> FromIterator<(K, V)> for Value {
907    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Value {
908        Value::from(iter.into_iter().collect::<Map>())
909    }
910}
911
912/// Converts bytes into owned bytes, retaining the fallback.
913pub(crate) fn owned_bytes(bytes: Bytes<'_>) -> Bytes<'static> {
914    let fallback = bytes.fallback;
915    let mut owned = Bytes::new(bytes.into_owned());
916    owned.fallback = fallback;
917    owned
918}
919
920impl PartialEq<str> for Value {
921    fn eq(&self, other: &str) -> bool {
922        matches!(self.kind, Kind::Str(ref value) | Kind::Lexical(ref value) if value == other)
923    }
924}
925
926impl PartialEq<&str> for Value {
927    fn eq(&self, other: &&str) -> bool {
928        *self == **other
929    }
930}
931
932impl PartialEq<String> for Value {
933    fn eq(&self, other: &String) -> bool {
934        *self == **other
935    }
936}
937
938impl PartialEq<bool> for Value {
939    fn eq(&self, other: &bool) -> bool {
940        matches!(self.kind, Kind::Bool(value) if value == *other)
941    }
942}
943
944impl PartialEq<f64> for Value {
945    fn eq(&self, other: &f64) -> bool {
946        match self.kind {
947            Kind::F64(value) => value == *other,
948            Kind::F32(value) => f64::from(value) == *other,
949            _ => false,
950        }
951    }
952}
953
954impl PartialEq<f32> for Value {
955    fn eq(&self, other: &f32) -> bool {
956        *self == f64::from(*other)
957    }
958}
959
960macro_rules! eq_int {
961    ($($ty:ty),*) => {
962        $(
963            impl PartialEq<$ty> for Value {
964                fn eq(&self, other: &$ty) -> bool {
965                    match self.kind {
966                        Kind::U64(value) => i128::from(value) == *other as i128,
967                        Kind::I64(value) => i128::from(value) == *other as i128,
968                        _ => false,
969                    }
970                }
971            }
972        )*
973    };
974}
975
976eq_int!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);