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};
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)), for instance with
179/// the `track_locations` option of `deser-json`.
180#[derive(Clone)]
181pub struct Span {
182    range: Range<usize>,
183    // for maps and sequences: the end of the start event and the start of
184    // the end event.
185    pub(crate) inner: Option<(usize, usize)>,
186    source: Arc<str>,
187}
188
189impl Span {
190    /// Creates a span of a range in a source.
191    pub fn new(range: Range<usize>, source: Arc<str>) -> Span {
192        Span {
193            range,
194            inner: None,
195            source,
196        }
197    }
198
199    /// Returns the byte range in the source.
200    pub fn range(&self) -> Range<usize> {
201        self.range.clone()
202    }
203
204    /// Returns the source.
205    pub fn source(&self) -> &Arc<str> {
206        &self.source
207    }
208
209    /// Returns the text of the span in the source.
210    pub fn text(&self) -> Option<&str> {
211        self.source.get(self.range.clone())
212    }
213
214    /// Returns the position (with line and column) of the start of the span.
215    pub fn start(&self) -> Position {
216        Position::of(self.source.as_bytes(), self.range.start)
217    }
218
219    /// Returns the position (with line and column) of the end of the span.
220    ///
221    /// The end is exclusive.
222    pub fn end(&self) -> Position {
223        Position::of(self.source.as_bytes(), self.range.end)
224    }
225
226    pub(crate) fn start_range(&self) -> (usize, usize) {
227        match self.inner {
228            Some((start_end, _)) => (self.range.start, start_end),
229            None => (self.range.start, self.range.end),
230        }
231    }
232
233    pub(crate) fn end_range(&self) -> Option<(usize, usize)> {
234        self.inner.map(|(_, end_start)| (end_start, self.range.end))
235    }
236
237    pub(crate) fn set_end(&mut self, end_start: usize, end: usize) {
238        self.inner = Some((self.range.end, end_start));
239        self.range.end = end;
240    }
241}
242
243impl fmt::Debug for Span {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.debug_struct("Span")
246            .field("range", &self.range)
247            .finish_non_exhaustive()
248    }
249}
250
251static NULL: Value = Value::null();
252
253impl Value {
254    /// Creates a null value.
255    pub const fn null() -> Value {
256        Value {
257            kind: Kind::Null,
258            meta: None,
259        }
260    }
261
262    /// Creates a value from its kind.
263    pub const fn new(kind: Kind) -> Value {
264        Value { kind, meta: None }
265    }
266
267    /// Creates a value holding an extension value.
268    ///
269    /// ```
270    /// use deser::ext::Uuid;
271    /// use deser_value::Value;
272    ///
273    /// let value = Value::ext(Uuid([0; 16]));
274    /// assert!(value.downcast_ext::<Uuid>().is_some());
275    /// ```
276    pub fn ext<T: Extension>(value: T) -> Value {
277        Value::from(ExtValue::owned(value))
278    }
279
280    /// Creates a value holding bytes.
281    pub fn bytes<B: Into<Vec<u8>>>(data: B) -> Value {
282        Value::new(Kind::Bytes(Bytes::new(data.into())))
283    }
284
285    /// Returns the kind of the value.
286    pub fn kind(&self) -> &Kind {
287        &self.kind
288    }
289
290    /// Returns the kind of the value mutably.
291    pub fn kind_mut(&mut self) -> &mut Kind {
292        &mut self.kind
293    }
294
295    /// Converts the value into its kind, discarding the meta data.
296    pub fn into_kind(self) -> Kind {
297        self.kind
298    }
299
300    /// Converts the value into its kind and meta data.
301    pub fn into_parts(self) -> (Kind, Option<Meta>) {
302        (self.kind, self.meta.map(|meta| *meta))
303    }
304
305    /// Returns the meta data of the value, if there is any.
306    pub fn meta(&self) -> Option<&Meta> {
307        self.meta.as_deref()
308    }
309
310    /// Returns the meta data of the value mutably.
311    ///
312    /// Empty meta data is created if the value has none.
313    pub fn meta_mut(&mut self) -> &mut Meta {
314        self.meta.get_or_insert_with(Default::default)
315    }
316
317    /// Removes the meta data of the value and returns it.
318    pub fn take_meta(&mut self) -> Option<Meta> {
319        self.meta.take().map(|meta| *meta)
320    }
321
322    /// Sets the meta data of the value.
323    pub fn set_meta(&mut self, meta: Option<Meta>) {
324        self.meta = meta.filter(|meta| !meta.is_empty()).map(Box::new);
325    }
326
327    /// Sets the meta data of the value and returns it.
328    pub fn with_meta(mut self, meta: Meta) -> Value {
329        self.set_meta(Some(meta));
330        self
331    }
332
333    /// Returns the span of the value in the input.
334    ///
335    /// This is a shortcut for the span of the [`Meta`].
336    pub fn span(&self) -> Option<&Span> {
337        self.meta().and_then(Meta::span)
338    }
339
340    /// Returns the event data of the value.
341    ///
342    /// This is a shortcut for the event data of the [`Meta`].
343    pub fn event_data(&self) -> Option<&EventData> {
344        self.meta().map(Meta::event_data)
345    }
346
347    /// Takes the value out, leaving null in its place.
348    pub fn take(&mut self) -> Value {
349        std::mem::take(self)
350    }
351}
352
353impl Default for Value {
354    fn default() -> Value {
355        Value::null()
356    }
357}
358
359impl Deref for Value {
360    type Target = Kind;
361
362    fn deref(&self) -> &Kind {
363        &self.kind
364    }
365}
366
367impl DerefMut for Value {
368    fn deref_mut(&mut self) -> &mut Kind {
369        &mut self.kind
370    }
371}
372
373impl Clone for Value {
374    fn clone(&self) -> Value {
375        Value {
376            kind: self.kind.clone(),
377            meta: self.meta.clone(),
378        }
379    }
380}
381
382impl PartialEq for Value {
383    fn eq(&self, other: &Value) -> bool {
384        tree::eq_kind(&self.kind, &other.kind)
385    }
386}
387
388impl Eq for Value {}
389
390impl Hash for Value {
391    fn hash<H: Hasher>(&self, state: &mut H) {
392        tree::hash_kind(&self.kind, state);
393    }
394}
395
396impl fmt::Debug for Value {
397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398        tree::fmt_kind(&self.kind, f)
399    }
400}
401
402impl<I: ValueIndex> std::ops::Index<I> for Value {
403    type Output = Value;
404
405    /// Looks up a value in a sequence (by index) or a map (by key).
406    ///
407    /// Returns null if the value does not exist.
408    fn index(&self, index: I) -> &Value {
409        index.index_into(&self.kind).unwrap_or(&NULL)
410    }
411}
412
413impl<I: ValueIndex> std::ops::IndexMut<I> for Value {
414    /// Looks up a value in a sequence (by index) or a map (by key) mutably.
415    ///
416    /// Keys that do not exist are inserted with null and a null value turns
417    /// into a map if it's indexed by a key.
418    ///
419    /// # Panics
420    ///
421    /// Panics if the index is out of bounds, or if the value cannot be
422    /// indexed by the index.
423    fn index_mut(&mut self, index: I) -> &mut Value {
424        index.index_or_insert(self)
425    }
426}
427
428impl Kind {
429    /// Returns the human readable name of the kind.
430    pub fn name(&self) -> &str {
431        match self {
432            Kind::Null => "null",
433            Kind::Bool(_) => "bool",
434            Kind::U64(_) => "unsigned integer",
435            Kind::I64(_) => "signed integer",
436            Kind::F32(_) | Kind::F64(_) => "float",
437            Kind::Char(_) => "char",
438            Kind::Str(_) | Kind::Lexical(_) => "string",
439            Kind::Bytes(_) => "bytes",
440            Kind::Ext(ext) => ext.name(),
441            Kind::Implicit(value) => value.value().name(),
442            Kind::Seq(_) => "sequence",
443            Kind::Map(_) => "map",
444        }
445    }
446
447    /// Returns `true` if this is null.
448    ///
449    /// Extension values that fall back to null count as null.
450    pub fn is_null(&self) -> bool {
451        match self {
452            Kind::Null => true,
453            Kind::Ext(ext) => matches!(ext.fallback(), Atom::Null),
454            Kind::Implicit(value) => value.value() == ImplicitValue::Null,
455            _ => false,
456        }
457    }
458
459    /// Returns the value of a bool.
460    pub fn as_bool(&self) -> Option<bool> {
461        match self {
462            Kind::Bool(value) => Some(*value),
463            Kind::Ext(ext) => match ext.fallback() {
464                Atom::Bool(value) => Some(value),
465                _ => None,
466            },
467            Kind::Implicit(value) => Kind::from_implicit(value.value()).as_bool(),
468            _ => None,
469        }
470    }
471
472    /// Returns the value of an integer if it fits into `u64`.
473    pub fn as_u64(&self) -> Option<u64> {
474        self.as_i128().and_then(|value| u64::try_from(value).ok())
475    }
476
477    /// Returns the value of an integer if it fits into `i64`.
478    pub fn as_i64(&self) -> Option<i64> {
479        self.as_i128().and_then(|value| i64::try_from(value).ok())
480    }
481
482    /// Returns the value of an integer if it fits into `u128`.
483    pub fn as_u128(&self) -> Option<u128> {
484        match self {
485            Kind::Ext(ext) if ext.is::<u128>() => ext.downcast_ref::<u128>().copied(),
486            _ => self.as_i128().and_then(|value| u128::try_from(value).ok()),
487        }
488    }
489
490    /// Returns the value of an integer if it fits into `i128`.
491    pub fn as_i128(&self) -> Option<i128> {
492        match self {
493            Kind::U64(value) => Some(i128::from(*value)),
494            Kind::I64(value) => Some(i128::from(*value)),
495            Kind::Implicit(value) => Kind::from_implicit(value.value()).as_i128(),
496            Kind::Ext(ext) => {
497                if let Some(value) = ext.downcast_ref::<i128>() {
498                    Some(*value)
499                } else if let Some(value) = ext.downcast_ref::<u128>() {
500                    i128::try_from(*value).ok()
501                } else {
502                    match ext.fallback() {
503                        Atom::U64(value) => Some(i128::from(value)),
504                        Atom::I64(value) => Some(i128::from(value)),
505                        _ => None,
506                    }
507                }
508            }
509            _ => None,
510        }
511    }
512
513    /// Returns the value of a number as `f64`.
514    ///
515    /// Integers are converted, which can lose precision.
516    pub fn as_f64(&self) -> Option<f64> {
517        match self {
518            Kind::F64(value) => Some(*value),
519            Kind::F32(value) => Some(f64::from(*value)),
520            Kind::U64(value) => Some(*value as f64),
521            Kind::I64(value) => Some(*value as f64),
522            Kind::Implicit(value) => Kind::from_implicit(value.value()).as_f64(),
523            Kind::Ext(ext) => match ext.fallback() {
524                Atom::F64(value) => Some(value),
525                Atom::F32(value) => Some(f64::from(value)),
526                Atom::U64(value) => Some(value as f64),
527                Atom::I64(value) => Some(value as f64),
528                _ => None,
529            },
530            _ => None,
531        }
532    }
533
534    /// Returns the value of a char.
535    pub fn as_char(&self) -> Option<char> {
536        match self {
537            Kind::Char(value) => Some(*value),
538            _ => None,
539        }
540    }
541
542    /// Returns the value of a string.
543    ///
544    /// For extension values this returns the fallback if it's a string
545    /// that borrows from the value.
546    pub fn as_str(&self) -> Option<&str> {
547        match self {
548            Kind::Str(value) | Kind::Lexical(value) => Some(value),
549            Kind::Ext(ext) => match ext.fallback() {
550                Atom::Str(value) => value.borrowed_str(),
551                _ => None,
552            },
553            _ => None,
554        }
555    }
556
557    /// Returns the data of bytes.
558    pub fn as_bytes(&self) -> Option<&[u8]> {
559        match self {
560            Kind::Bytes(value) => Some(value.data()),
561            _ => None,
562        }
563    }
564
565    /// Returns the sequence.
566    pub fn as_seq(&self) -> Option<&Seq> {
567        match self {
568            Kind::Seq(value) => Some(value),
569            _ => None,
570        }
571    }
572
573    /// Returns the sequence mutably.
574    pub fn as_seq_mut(&mut self) -> Option<&mut Seq> {
575        match self {
576            Kind::Seq(value) => Some(value),
577            _ => None,
578        }
579    }
580
581    /// Returns the map.
582    pub fn as_map(&self) -> Option<&Map> {
583        match self {
584            Kind::Map(value) => Some(value),
585            _ => None,
586        }
587    }
588
589    /// Returns the map mutably.
590    pub fn as_map_mut(&mut self) -> Option<&mut Map> {
591        match self {
592            Kind::Map(value) => Some(value),
593            _ => None,
594        }
595    }
596
597    /// Returns the extension value.
598    pub fn as_ext(&self) -> Option<&ExtValue<'static>> {
599        match self {
600            Kind::Ext(value) => Some(value),
601            _ => None,
602        }
603    }
604
605    /// Returns the extension value if it's of type `T`.
606    ///
607    /// For extensions that borrow, use
608    /// [`downcast_ext_value`](Self::downcast_ext_value).
609    pub fn downcast_ext<T: Extension>(&self) -> Option<&T> {
610        self.as_ext().and_then(|ext| ext.downcast_ref::<T>())
611    }
612
613    /// Returns the extension value if it's of the extension with the key `K`.
614    ///
615    /// See [`BorrowedExtension`].
616    ///
617    /// ```
618    /// use deser::ext::Number;
619    /// use deser_value::Value;
620    ///
621    /// let value: Value =
622    ///     deser_json::from_str("0.10000000000000000001").unwrap();
623    /// let number = value.downcast_ext_value::<Number>().unwrap();
624    /// assert_eq!(number.as_str(), "0.10000000000000000001");
625    /// ```
626    pub fn downcast_ext_value<K: BorrowedExtension>(&self) -> Option<&K::Value<'_>> {
627        self.as_ext().and_then(|ext| ext.downcast_value_ref::<K>())
628    }
629
630    /// Returns `true` if this is a string.
631    ///
632    /// This is also `true` for [lexical](Kind::Lexical) values.
633    pub fn is_str(&self) -> bool {
634        matches!(self, Kind::Str(_) | Kind::Lexical(_))
635    }
636
637    /// Returns `true` if this is a [lexical](Kind::Lexical) value.
638    pub fn is_lexical(&self) -> bool {
639        matches!(self, Kind::Lexical(_))
640    }
641
642    /// Returns `true` if this is a sequence.
643    pub fn is_seq(&self) -> bool {
644        matches!(self, Kind::Seq(_))
645    }
646
647    /// Returns `true` if this is a map.
648    pub fn is_map(&self) -> bool {
649        matches!(self, Kind::Map(_))
650    }
651
652    /// Looks up a value in a sequence (by index) or a map (by key).
653    ///
654    /// ```
655    /// use deser_value::value;
656    ///
657    /// let value = value!({"items": [1, 2], 42: "answer"});
658    /// assert_eq!(value.get("items").and_then(|x| x.get(1)), Some(&value!(2)));
659    /// assert_eq!(value.get(&value!(42)), Some(&value!("answer")));
660    /// assert_eq!(value.get("missing"), None);
661    /// ```
662    pub fn get<I: ValueIndex>(&self, index: I) -> Option<&Value> {
663        index.index_into(self)
664    }
665
666    /// Looks up a value in a sequence (by index) or a map (by key) mutably.
667    pub fn get_mut<I: ValueIndex>(&mut self, index: I) -> Option<&mut Value> {
668        index.index_into_mut(self)
669    }
670
671    /// Returns `true` for maps and sequences that are not empty.
672    #[inline]
673    pub(crate) fn has_children(&self) -> bool {
674        match self {
675            Kind::Seq(seq) => !seq.is_empty(),
676            Kind::Map(map) => !map.is_empty(),
677            _ => false,
678        }
679    }
680}
681
682impl Clone for Kind {
683    fn clone(&self) -> Kind {
684        tree::clone_kind(self)
685    }
686}
687
688impl PartialEq for Kind {
689    fn eq(&self, other: &Kind) -> bool {
690        tree::eq_kind(self, other)
691    }
692}
693
694impl Eq for Kind {}
695
696impl Hash for Kind {
697    fn hash<H: Hasher>(&self, state: &mut H) {
698        tree::hash_kind(self, state);
699    }
700}
701
702impl fmt::Debug for Kind {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        tree::fmt_kind(self, f)
705    }
706}
707
708impl From<Kind> for Value {
709    fn from(kind: Kind) -> Value {
710        Value::new(kind)
711    }
712}
713
714impl From<()> for Value {
715    fn from(_: ()) -> Value {
716        Value::null()
717    }
718}
719
720impl From<bool> for Value {
721    fn from(value: bool) -> Value {
722        Value::new(Kind::Bool(value))
723    }
724}
725
726impl From<char> for Value {
727    fn from(value: char) -> Value {
728        Value::new(Kind::Char(value))
729    }
730}
731
732macro_rules! from_unsigned {
733    ($($ty:ty),*) => {
734        $(
735            impl From<$ty> for Value {
736                fn from(value: $ty) -> Value {
737                    Value::new(Kind::U64(value as u64))
738                }
739            }
740        )*
741    };
742}
743
744macro_rules! from_signed {
745    ($($ty:ty),*) => {
746        $(
747            impl From<$ty> for Value {
748                fn from(value: $ty) -> Value {
749                    Value::new(Kind::from_i64(value as i64))
750                }
751            }
752        )*
753    };
754}
755
756from_unsigned!(u8, u16, u32, u64, usize);
757from_signed!(i8, i16, i32, i64, isize);
758
759impl Kind {
760    /// Creates an integer, non-negative integers are held as `U64`.
761    pub(crate) fn from_i64(value: i64) -> Kind {
762        match u64::try_from(value) {
763            Ok(value) => Kind::U64(value),
764            Err(_) => Kind::I64(value),
765        }
766    }
767
768    /// Creates the kind of the value of an implicit atom.
769    pub(crate) fn from_implicit(value: ImplicitValue) -> Kind {
770        match value {
771            ImplicitValue::Null => Kind::Null,
772            ImplicitValue::Bool(value) => Kind::Bool(value),
773            ImplicitValue::U64(value) => Kind::U64(value),
774            ImplicitValue::I64(value) => Kind::from_i64(value),
775            ImplicitValue::F64(value) => Kind::F64(value),
776            _ => Kind::Null,
777        }
778    }
779
780    /// Creates a kind from an extension value.
781    ///
782    /// Integers of extensions which fit into 64 bits are converted.
783    pub(crate) fn from_ext(ext: ExtValue<'_>) -> Kind {
784        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 owned = Bytes::new(bytes.into_owned());
916    match fallback {
917        Some(format) => owned.with_fallback(format),
918        None => owned,
919    }
920}
921
922impl PartialEq<str> for Value {
923    fn eq(&self, other: &str) -> bool {
924        matches!(self.kind, Kind::Str(ref value) | Kind::Lexical(ref value) if value == other)
925    }
926}
927
928impl PartialEq<&str> for Value {
929    fn eq(&self, other: &&str) -> bool {
930        *self == **other
931    }
932}
933
934impl PartialEq<String> for Value {
935    fn eq(&self, other: &String) -> bool {
936        *self == **other
937    }
938}
939
940impl PartialEq<bool> for Value {
941    fn eq(&self, other: &bool) -> bool {
942        matches!(self.kind, Kind::Bool(value) if value == *other)
943    }
944}
945
946impl PartialEq<f64> for Value {
947    fn eq(&self, other: &f64) -> bool {
948        match self.kind {
949            Kind::F64(value) => value == *other,
950            Kind::F32(value) => f64::from(value) == *other,
951            _ => false,
952        }
953    }
954}
955
956impl PartialEq<f32> for Value {
957    fn eq(&self, other: &f32) -> bool {
958        *self == f64::from(*other)
959    }
960}
961
962macro_rules! eq_int {
963    ($($ty:ty),*) => {
964        $(
965            impl PartialEq<$ty> for Value {
966                fn eq(&self, other: &$ty) -> bool {
967                    match self.kind {
968                        Kind::U64(value) => i128::from(value) == *other as i128,
969                        Kind::I64(value) => i128::from(value) == *other as i128,
970                        _ => false,
971                    }
972                }
973            }
974        )*
975    };
976}
977
978eq_int!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);