Skip to main content

deser_core/
event.rs

1use alloc::borrow::Cow;
2use alloc::format;
3use alloc::string::String;
4use alloc::vec::Vec;
5use core::fmt;
6use core::ops::Deref;
7
8use crate::BytesFormat;
9use crate::error::{Error, ErrorKind};
10use crate::ext::ExtValue;
11use crate::text::{Slice, Text};
12
13/// An atom is a primitive value for serialization and deserialization.
14///
15/// Atoms are values that are sent directly to a serializer or deserializer.
16/// Examples for this are booleans or integers.  This is in contrast to
17/// compound values like maps, structs or sequences.
18///
19/// Atoms are non exhaustive which means that new variants might appear
20/// in the future.  Deser tries to build around this restriction for instance
21/// through APIs like [`unexpected_atom`](crate::de::Sink::unexpected_atom) so that
22/// one always have something to call.
23///
24/// Values which are not part of the core data model are represented as
25/// [`Atom::Ext`].  For more information see [`ext`](crate::ext).
26///
27/// [`Bytes`] can carry a representation for formats without native bytes
28/// which formats with native bytes ignore.
29///
30/// Floats are [`F32`](Atom::F32) or [`F64`](Atom::F64) depending on their
31/// precision.  A single precision float is a value of its own as its
32/// shortest text differs from the one of the same value as `f64` (`0.1f32`
33/// is `0.1`, as `f64` it's `0.10000000149011612`).  Consumers that do not
34/// care about the precision can [widen](Atom::widen_float) it.
35///
36/// Text whose type the format cannot express is [`Lexical`](Atom::Lexical).
37/// It's a string for everybody who does not care, see there for more
38/// information.  A value whose type the format inferred from its text is
39/// [`Implicit`](Atom::Implicit), it carries the text for types that do not
40/// accept the value.
41#[derive(Debug, PartialEq, Clone)]
42#[non_exhaustive]
43// The tag is a full word in front of the values: moving atoms (which
44// happens for every value) then copies whole words.  With a byte sized tag
45// small values are stored next to the tag and atoms are written and read
46// in pieces of different sizes, which stalls loads (and was 5-15% slower
47// for numbers in binary formats).
48#[repr(C, u64)]
49pub enum Atom<'a> {
50    Null,
51    Bool(bool),
52    Str(Text<'a>),
53    /// The lexical form of a value whose type the format cannot express.
54    ///
55    /// Some formats cannot say what type a piece of text is: everything in
56    /// a query string is text, and so are the keys of JSON objects.  Such
57    /// text is emitted as a lexical atom and the sink it's delivered to
58    /// decides what it means: numbers and booleans parse it, strings take
59    /// it as it is.  Text that is known to be a string (like a string value
60    /// in JSON, where the number `42` could have been written instead of
61    /// `"42"`) is [`Str`](Atom::Str).
62    ///
63    /// Sinks receive it as [`Str`](Atom::Str) unless they handle it (see
64    /// [`Sink::unexpected_atom`](crate::de::Sink::unexpected_atom)).  Sinks
65    /// that borrow strings have to handle it themselves, the fallback does
66    /// not borrow for the lifetime of the input.  Serializers write it as
67    /// string.
68    ///
69    /// Integers and floats parse lexical atoms with [`str::parse`], how
70    /// booleans are spelled, if empty text is a missing value and if text is
71    /// a sequence of one element depends on the
72    /// [`LexicalRules`](crate::de::LexicalRules) of the deserialization,
73    /// which the format sets.  All other types that accept strings accept
74    /// lexical atoms as string.
75    Lexical(Text<'a>),
76    Bytes(Bytes<'a>),
77    Char(char),
78    U64(u64),
79    I64(i64),
80    /// A single precision float.
81    ///
82    /// Formats write it with the precision of an `f32`, for instance text
83    /// formats with the shortest text that reads back as the same `f32`.
84    /// Formats do not produce it when they read floats (the precision of
85    /// a float in the input is unknown or, like in CBOR, an encoding
86    /// detail).  Sinks receive it as [`F64`](Atom::F64) unless they handle
87    /// it (see [`Sink::unexpected_atom`](crate::de::Sink::unexpected_atom)).
88    F32(f32),
89    /// A double precision float.
90    F64(f64),
91    /// A value that extends the data model.
92    ///
93    /// See [`ext`](crate::ext) for more information.
94    Ext(ExtValue<'a>),
95    /// A value whose type the format inferred from its text.
96    ///
97    /// See [`Implicit`] for more information.
98    Implicit(Implicit<'a>),
99}
100
101impl<'a> Atom<'a> {
102    /// Makes a static clone of the atom decoupling the lifetimes.
103    pub fn to_static(&self) -> Atom<'static> {
104        match *self {
105            Atom::Null => Atom::Null,
106            Atom::Bool(v) => Atom::Bool(v),
107            Atom::Str(ref v) => Atom::Str(v.to_static()),
108            Atom::Lexical(ref v) => Atom::Lexical(v.to_static()),
109            Atom::Bytes(ref v) => Atom::Bytes(v.to_static()),
110            Atom::Char(v) => Atom::Char(v),
111            Atom::U64(v) => Atom::U64(v),
112            Atom::I64(v) => Atom::I64(v),
113            Atom::F32(v) => Atom::F32(v),
114            Atom::F64(v) => Atom::F64(v),
115            Atom::Ext(ref v) => Atom::Ext(v.to_static()),
116            Atom::Implicit(ref v) => Atom::Implicit(v.to_static()),
117        }
118    }
119
120    /// Returns an atom borrowing from this one.
121    ///
122    /// This is useful to pass a stored atom on without cloning its data.
123    pub fn as_borrowed(&self) -> Atom<'_> {
124        match *self {
125            Atom::Null => Atom::Null,
126            Atom::Bool(v) => Atom::Bool(v),
127            Atom::Str(ref v) => Atom::Str(v.as_borrowed()),
128            Atom::Lexical(ref v) => Atom::Lexical(v.as_borrowed()),
129            Atom::Bytes(ref v) => Atom::Bytes(v.as_borrowed()),
130            Atom::Char(v) => Atom::Char(v),
131            Atom::U64(v) => Atom::U64(v),
132            Atom::I64(v) => Atom::I64(v),
133            Atom::F32(v) => Atom::F32(v),
134            Atom::F64(v) => Atom::F64(v),
135            Atom::Ext(ref v) => Atom::Ext(v.as_borrowed()),
136            Atom::Implicit(ref v) => Atom::Implicit(v.as_borrowed()),
137        }
138    }
139
140    /// Widens an [`F32`](Atom::F32) into an [`F64`](Atom::F64).
141    ///
142    /// Other atoms are returned unchanged.  This is useful for consumers
143    /// which do not distinguish the precision of floats.
144    ///
145    /// ```
146    /// use deser::Atom;
147    ///
148    /// assert_eq!(Atom::F32(1.5).widen_float(), Atom::F64(1.5));
149    /// assert_eq!(Atom::U64(1).widen_float(), Atom::U64(1));
150    /// ```
151    #[inline]
152    pub fn widen_float(self) -> Atom<'a> {
153        match self {
154            Atom::F32(v) => Atom::F64(f64::from(v)),
155            other => other,
156        }
157    }
158
159    /// Returns the text of a [`Str`](Atom::Str) or [`Lexical`](Atom::Lexical)
160    /// atom.
161    ///
162    /// ```
163    /// use deser::Atom;
164    ///
165    /// assert_eq!(Atom::Lexical("42".into()).as_str(), Some("42"));
166    /// assert_eq!(Atom::Str("42".into()).as_str(), Some("42"));
167    /// assert_eq!(Atom::U64(42).as_str(), None);
168    /// ```
169    #[inline]
170    pub fn as_str(&self) -> Option<&str> {
171        match self {
172            Atom::Str(v) | Atom::Lexical(v) => Some(v),
173            _ => None,
174        }
175    }
176
177    /// Returns the human readable name of the atom.
178    pub fn name(&self) -> &str {
179        match *self {
180            Atom::Null => "null",
181            Atom::Bool(_) => "bool",
182            Atom::Str(_) | Atom::Lexical(_) => "string",
183            Atom::Bytes(_) => "bytes",
184            Atom::Char(_) => "char",
185            Atom::U64(_) => "unsigned integer",
186            Atom::I64(_) => "signed integer",
187            Atom::F32(_) | Atom::F64(_) => "float",
188            Atom::Ext(ref v) => v.name(),
189            Atom::Implicit(ref v) => v.value().name(),
190        }
191    }
192
193    /// Creates an "unexpected" error.
194    ///
195    /// This is useful when implementing sinks that do not want to deal with an
196    /// atom of a specific type.  The default implementation of a
197    /// [`Sink`](crate::de::Sink) uses this method as follows:
198    ///
199    /// ```
200    /// # use deser::{Atom, Error, State, de::Sink};
201    /// # struct MySink;
202    /// impl<'de> Sink<'de> for MySink {
203    ///     fn atom(
204    ///         &mut self,
205    ///         atom: Atom,
206    ///         _state: &mut State,
207    ///     ) -> Result<(), Error> {
208    ///         Err(atom.unexpected_error(&self.expecting()))
209    ///     }
210    /// }
211    /// ```
212    pub fn unexpected_error(&self, expectation: &str) -> Error {
213        Error::new(
214            ErrorKind::Unexpected,
215            format!("unexpected {}, expected {}", self.name(), expectation),
216        )
217    }
218}
219
220/// A value whose type the format inferred from its text.
221///
222/// Some formats write values as text and infer their type from it: in YAML
223/// `42` is an integer, `1.10` a float, `true` a boolean and `~` null, but
224/// only because these plain scalars look like it.  The format resolves the
225/// value with its own rules (which are not the ones of Rust, `0x1F` is an
226/// integer in YAML) and emits it together with its text.
227///
228/// Types that accept the value receive it, types that reject it receive
229/// the text as [`Str`](Atom::Str) instead (see
230/// [`Sink::unexpected_atom`](crate::de::Sink::unexpected_atom)).  This
231/// means that a `u32` is `31` for `0x1F` while a `String` is `"0x1F"` and an
232/// `Option<String>` is `None` for `~` while a `String` is `"~"`.  If both are
233/// rejected, the error is the one of the value.  Enums look up their
234/// variants by the value and then by the text.  Types that take any value
235/// (like dynamic values) keep both.  Serializers write the text if it's
236/// the same value in their format (`1.10` stays `1.10` in JSON and YAML,
237/// `0x1F` stays `0x1F` in YAML), otherwise they write the value.
238///
239/// ```
240/// use deser::{Atom, Implicit, ImplicitValue};
241///
242/// let atom = Atom::Implicit(Implicit::new("0x1F", ImplicitValue::U64(31)));
243/// let mut out = None::<u32>;
244/// deser::de::DeserializeDriver::new(&mut out).emit(atom.clone()).unwrap();
245/// assert_eq!(out, Some(31));
246///
247/// let mut out = None::<String>;
248/// deser::de::DeserializeDriver::new(&mut out).emit(atom).unwrap();
249/// assert_eq!(out.as_deref(), Some("0x1F"));
250/// ```
251#[derive(Clone)]
252pub struct Implicit<'a> {
253    // the kind of the value is the tag of the text (see `ImplicitValue::kind`)
254    text: Text<'a>,
255    // the value (see `ImplicitValue::bits`)
256    bits: u64,
257}
258
259impl<'a> Implicit<'a> {
260    /// Creates a value from its text and the value inferred from it.
261    #[inline]
262    pub fn new<T: Into<Text<'a>>>(text: T, value: ImplicitValue) -> Implicit<'a> {
263        let (kind, bits) = value.pack();
264        Implicit {
265            text: text.into().with_tag(kind),
266            bits,
267        }
268    }
269
270    /// Returns the text of the value.
271    #[inline]
272    pub fn text(&self) -> &Text<'a> {
273        &self.text
274    }
275
276    /// Returns the inferred value.
277    #[inline]
278    pub fn value(&self) -> ImplicitValue {
279        ImplicitValue::unpack(self.text.tag(), self.bits)
280    }
281
282    /// Splits the value into its text and the inferred value.
283    #[inline]
284    pub fn into_parts(self) -> (Text<'a>, ImplicitValue) {
285        let value = self.value();
286        (self.text.with_tag(0), value)
287    }
288
289    /// Returns a value borrowing from this one.
290    #[inline]
291    pub fn as_borrowed(&self) -> Implicit<'_> {
292        Implicit {
293            text: self.text.as_borrowed().with_tag(self.text.tag()),
294            bits: self.bits,
295        }
296    }
297
298    /// Makes a static clone decoupling the lifetimes.
299    #[inline]
300    pub fn to_static(&self) -> Implicit<'static> {
301        Implicit {
302            text: self.text.to_static().with_tag(self.text.tag()),
303            bits: self.bits,
304        }
305    }
306}
307
308impl fmt::Debug for Implicit<'_> {
309    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310        f.debug_struct("Implicit")
311            .field("text", &self.text)
312            .field("value", &self.value())
313            .finish()
314    }
315}
316
317impl PartialEq for Implicit<'_> {
318    fn eq(&self, other: &Self) -> bool {
319        self.text == other.text && self.value() == other.value()
320    }
321}
322
323/// The value of an [`Implicit`] atom.
324///
325/// These are the types formats infer from text.
326#[derive(Debug, Clone, Copy, PartialEq)]
327#[non_exhaustive]
328pub enum ImplicitValue {
329    Null,
330    Bool(bool),
331    U64(u64),
332    I64(i64),
333    F64(f64),
334}
335
336impl ImplicitValue {
337    /// Splits the value into a kind (`0` to `7`, stored in the tag of the
338    /// text of an [`Implicit`]) and the bits of the value.
339    #[inline]
340    fn pack(self) -> (u8, u64) {
341        match self {
342            ImplicitValue::Null => (0, 0),
343            ImplicitValue::Bool(value) => (1, value as u64),
344            ImplicitValue::U64(value) => (2, value),
345            ImplicitValue::I64(value) => (3, value as u64),
346            ImplicitValue::F64(value) => (4, value.to_bits()),
347        }
348    }
349
350    /// Joins a value split with [`pack`](Self::pack).
351    #[inline]
352    fn unpack(kind: u8, bits: u64) -> ImplicitValue {
353        match kind {
354            1 => ImplicitValue::Bool(bits != 0),
355            2 => ImplicitValue::U64(bits),
356            3 => ImplicitValue::I64(bits as i64),
357            4 => ImplicitValue::F64(f64::from_bits(bits)),
358            _ => ImplicitValue::Null,
359        }
360    }
361
362    /// Returns the value for an atom if it's one of the inferred types.
363    pub fn from_atom(atom: &Atom<'_>) -> Option<ImplicitValue> {
364        match *atom {
365            Atom::Null => Some(ImplicitValue::Null),
366            Atom::Bool(value) => Some(ImplicitValue::Bool(value)),
367            Atom::U64(value) => Some(ImplicitValue::U64(value)),
368            Atom::I64(value) => Some(ImplicitValue::I64(value)),
369            Atom::F64(value) => Some(ImplicitValue::F64(value)),
370            _ => None,
371        }
372    }
373
374    /// Returns the value as atom.
375    #[inline]
376    pub fn to_atom(self) -> Atom<'static> {
377        match self {
378            ImplicitValue::Null => Atom::Null,
379            ImplicitValue::Bool(value) => Atom::Bool(value),
380            ImplicitValue::U64(value) => Atom::U64(value),
381            ImplicitValue::I64(value) => Atom::I64(value),
382            ImplicitValue::F64(value) => Atom::F64(value),
383        }
384    }
385
386    /// Returns `true` if both are the same value.
387    ///
388    /// Unlike `==`, floats are compared by their bits: `NaN` is the same
389    /// as `NaN` and `0.0` is not the same as `-0.0`.  This is useful to
390    /// check if text reads back as the same value.
391    ///
392    /// ```
393    /// use deser::ImplicitValue;
394    ///
395    /// assert!(
396    ///     ImplicitValue::F64(f64::NAN).is_same(ImplicitValue::F64(f64::NAN))
397    /// );
398    /// assert!(!ImplicitValue::F64(0.0).is_same(ImplicitValue::F64(-0.0)));
399    /// assert!(!ImplicitValue::U64(1).is_same(ImplicitValue::F64(1.0)));
400    /// ```
401    pub fn is_same(self, other: ImplicitValue) -> bool {
402        match (self, other) {
403            (ImplicitValue::F64(a), ImplicitValue::F64(b)) => a.to_bits() == b.to_bits(),
404            (a, b) => a == b,
405        }
406    }
407
408    /// Returns the human readable name of the value.
409    pub fn name(&self) -> &'static str {
410        match *self {
411            ImplicitValue::Null => "null",
412            ImplicitValue::Bool(_) => "bool",
413            ImplicitValue::U64(_) => "unsigned integer",
414            ImplicitValue::I64(_) => "signed integer",
415            ImplicitValue::F64(_) => "float",
416        }
417    }
418}
419
420macro_rules! impl_from {
421    ($ty:ty, $atom:ident) => {
422        impl From<$ty> for Event<'static> {
423            fn from(value: $ty) -> Self {
424                Event::Atom(Atom::$atom(value as _))
425            }
426        }
427    };
428}
429
430impl_from!(u64, U64);
431impl_from!(i64, I64);
432impl_from!(usize, U64);
433impl_from!(isize, I64);
434impl_from!(bool, Bool);
435impl_from!(char, Char);
436
437impl From<f64> for Event<'static> {
438    fn from(value: f64) -> Self {
439        Event::Atom(Atom::F64(value))
440    }
441}
442
443impl From<f32> for Event<'static> {
444    fn from(value: f32) -> Self {
445        Event::Atom(Atom::F32(value))
446    }
447}
448
449impl From<u128> for Event<'static> {
450    fn from(value: u128) -> Self {
451        Event::Atom(Atom::Ext(ExtValue::owned(value)))
452    }
453}
454
455impl From<i128> for Event<'static> {
456    fn from(value: i128) -> Self {
457        Event::Atom(Atom::Ext(ExtValue::owned(value)))
458    }
459}
460
461impl From<()> for Event<'static> {
462    fn from(_: ()) -> Event<'static> {
463        Event::Atom(Atom::Null)
464    }
465}
466
467impl<'a> From<&'a str> for Event<'a> {
468    fn from(value: &'a str) -> Event<'a> {
469        Event::Atom(Atom::Str(Text::borrowed(value)))
470    }
471}
472
473impl<'a> From<Cow<'a, str>> for Event<'a> {
474    fn from(value: Cow<'a, str>) -> Event<'a> {
475        Event::Atom(Atom::Str(value.into()))
476    }
477}
478
479impl<'a> From<Text<'a>> for Event<'a> {
480    fn from(value: Text<'a>) -> Event<'a> {
481        Event::Atom(Atom::Str(value))
482    }
483}
484
485impl<'a> From<&'a [u8]> for Event<'a> {
486    fn from(value: &'a [u8]) -> Event<'a> {
487        Event::Atom(Atom::Bytes(Bytes::borrowed(value)))
488    }
489}
490
491impl From<String> for Event<'static> {
492    fn from(value: String) -> Event<'static> {
493        Event::Atom(Atom::Str(value.into()))
494    }
495}
496
497impl<'a> From<Atom<'a>> for Event<'a> {
498    fn from(atom: Atom<'a>) -> Self {
499        Event::Atom(atom)
500    }
501}
502
503/// An event represents an atomic serialization and deserialization event.
504///
505/// ## Serialization
506///
507/// [`Event`] and [`Chunk`](crate::ser::Chunk) are two close relatives.  A chunk
508/// is stateful whereas [`Event`] represents a single event from a chunk.
509/// Atomic chunks directly create an event whereas compound chunks keep emitting
510/// more chunks which again can produce events.  To go from chunks to events use
511/// the [`SerializeDriver`](crate::ser::SerializeDriver) method.
512///
513/// ## Deserialization
514///
515/// During deserialization events are passed to a
516/// [`DeserializeDriver`](crate::de::DeserializeDriver) to drive the deserialization.
517///
518/// The start events of maps and sequences carry the [`ContainerShape`].
519#[derive(PartialEq, Clone)]
520pub enum Event<'a> {
521    Atom(Atom<'a>),
522    MapStart(ContainerShape),
523    MapEnd,
524    SeqStart(ContainerShape),
525    SeqEnd,
526}
527
528impl<'a> Event<'a> {
529    /// Creates the start event of a map with the default shape.
530    pub const fn map_start() -> Event<'static> {
531        Event::MapStart(ContainerShape::new())
532    }
533
534    /// Creates the start event of a sequence with the default shape.
535    pub const fn seq_start() -> Event<'static> {
536        Event::SeqStart(ContainerShape::new())
537    }
538
539    /// Returns an event borrowing from this one.
540    pub fn as_borrowed(&self) -> Event<'_> {
541        match *self {
542            Event::Atom(ref atom) => Event::Atom(atom.as_borrowed()),
543            Event::MapStart(shape) => Event::MapStart(shape),
544            Event::MapEnd => Event::MapEnd,
545            Event::SeqStart(shape) => Event::SeqStart(shape),
546            Event::SeqEnd => Event::SeqEnd,
547        }
548    }
549
550    /// Makes a static clone of the event decoupling the lifetimes.
551    pub fn to_static(&self) -> Event<'static> {
552        match *self {
553            Event::Atom(ref atom) => Event::Atom(atom.to_static()),
554            Event::MapStart(shape) => Event::MapStart(shape),
555            Event::MapEnd => Event::MapEnd,
556            Event::SeqStart(shape) => Event::SeqStart(shape),
557            Event::SeqEnd => Event::SeqEnd,
558        }
559    }
560}
561
562impl fmt::Debug for Event<'_> {
563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564        // the default shape is left out to keep the output short
565        let (name, shape) = match *self {
566            Event::Atom(ref atom) => return f.debug_tuple("Atom").field(atom).finish(),
567            Event::MapStart(shape) => ("MapStart", shape),
568            Event::MapEnd => return f.write_str("MapEnd"),
569            Event::SeqStart(shape) => ("SeqStart", shape),
570            Event::SeqEnd => return f.write_str("SeqEnd"),
571        };
572        if shape == ContainerShape::new() {
573            f.write_str(name)
574        } else {
575            f.debug_tuple(name).field(&shape).finish()
576        }
577    }
578}
579
580/// Bytes in the data model.
581///
582/// The data is borrowed or owned, like a `Cow<'a, [u8]>` but with a more
583/// compact representation (see [`Text`]).
584///
585/// Bytes can carry a [`BytesFormat`] as fallback which formats without
586/// native bytes (such as JSON) use instead of their configured format.
587/// Formats with native bytes ignore it.  This is set by
588/// [`BytesFallback`](crate::adapters::BytesFallback).
589#[derive(Clone)]
590#[non_exhaustive]
591pub struct Bytes<'a> {
592    data: Slice<'a>,
593    /// The format used by formats without native bytes, if any.
594    pub fallback: Option<&'static BytesFormat>,
595}
596
597impl<'a> Bytes<'a> {
598    /// Creates bytes from borrowed or owned data.
599    #[inline]
600    pub fn new<D: Into<Cow<'a, [u8]>>>(data: D) -> Bytes<'a> {
601        Bytes {
602            data: Slice::from_cow(data.into()),
603            fallback: None,
604        }
605    }
606
607    /// Creates bytes borrowing the data.
608    #[inline]
609    pub const fn borrowed(data: &'a [u8]) -> Bytes<'a> {
610        Bytes {
611            data: Slice::borrowed(data),
612            fallback: None,
613        }
614    }
615
616    /// Sets the format that is used by formats without native bytes.
617    #[inline]
618    pub fn with_fallback(mut self, format: &'static BytesFormat) -> Bytes<'a> {
619        self.fallback = Some(format);
620        self
621    }
622
623    /// Returns the data.
624    #[inline]
625    pub fn data(&self) -> &[u8] {
626        self.data.as_slice()
627    }
628
629    /// Returns `true` if the data borrows for `'a`.
630    #[inline]
631    pub fn is_borrowed(&self) -> bool {
632        !self.data.is_owned()
633    }
634
635    /// Returns the data if it borrows for `'a`.
636    ///
637    /// This is used by types which borrow from the data that is
638    /// deserialized (like `&'de [u8]`).
639    #[inline]
640    pub fn borrowed_data(&self) -> Option<&'a [u8]> {
641        self.data.borrowed_slice()
642    }
643
644    /// Returns the data, borrowed or owned.
645    #[inline]
646    pub fn into_data(self) -> Cow<'a, [u8]> {
647        self.data.into_cow()
648    }
649
650    /// Returns the data as owned vector.
651    #[inline]
652    pub fn into_owned(self) -> Vec<u8> {
653        self.data.into_box().into_vec()
654    }
655
656    /// Returns bytes borrowing from these.
657    pub fn as_borrowed(&self) -> Bytes<'_> {
658        Bytes {
659            data: self.data.reborrow(),
660            fallback: self.fallback,
661        }
662    }
663
664    /// Makes a static clone decoupling the lifetimes.
665    pub fn to_static(&self) -> Bytes<'static> {
666        Bytes {
667            data: self.data.to_static(),
668            fallback: self.fallback,
669        }
670    }
671}
672
673impl PartialEq for Bytes<'_> {
674    fn eq(&self, other: &Self) -> bool {
675        self.data() == other.data() && self.fallback == other.fallback
676    }
677}
678
679impl Deref for Bytes<'_> {
680    type Target = [u8];
681
682    #[inline]
683    fn deref(&self) -> &[u8] {
684        self.data()
685    }
686}
687
688impl AsRef<[u8]> for Bytes<'_> {
689    #[inline]
690    fn as_ref(&self) -> &[u8] {
691        self.data()
692    }
693}
694
695impl<'a> From<&'a [u8]> for Bytes<'a> {
696    fn from(data: &'a [u8]) -> Bytes<'a> {
697        Bytes::borrowed(data)
698    }
699}
700
701impl From<Vec<u8>> for Bytes<'static> {
702    fn from(data: Vec<u8>) -> Bytes<'static> {
703        Bytes::new(data)
704    }
705}
706
707impl<'a> From<Cow<'a, [u8]>> for Bytes<'a> {
708    fn from(data: Cow<'a, [u8]>) -> Bytes<'a> {
709        Bytes::new(data)
710    }
711}
712
713impl fmt::Debug for Bytes<'_> {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        fmt::Debug::fmt(self.data(), f)?;
716        if let Some(format) = self.fallback {
717            write!(f, " as {}", format.name())?;
718        }
719        Ok(())
720    }
721}
722
723/// How significant the order of the elements of a container is.
724///
725/// The default ([`Order::Natural`]) means the natural semantics of the
726/// container: the order of sequences is significant, the order of maps is
727/// not but the emitted order is kept.  Only deviations are marked.
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
729#[non_exhaustive]
730pub enum Order {
731    /// The natural semantics of the container.
732    #[default]
733    Natural,
734    /// The order is not significant and the elements are emitted in an
735    /// arbitrary order that can change between runs (`HashMap`, `HashSet`).
736    Arbitrary,
737    /// The order is not significant and the elements are sorted
738    /// (`BTreeMap`, `BTreeSet`).
739    Sorted,
740    /// The order is significant, also for maps.
741    Significant,
742}
743
744impl Order {
745    const fn to_bits(self) -> u32 {
746        match self {
747            Order::Natural => 0,
748            Order::Arbitrary => 1,
749            Order::Sorted => 2,
750            Order::Significant => 3,
751        }
752    }
753
754    const fn from_bits(bits: u32) -> Order {
755        match bits & ORDER_MASK {
756            1 => Order::Arbitrary,
757            2 => Order::Sorted,
758            3 => Order::Significant,
759            _ => Order::Natural,
760        }
761    }
762}
763
764const ORDER_MASK: u32 = 0b11;
765const MULTIMAP: u32 = 0b100;
766const UNKNOWN_LEN: usize = usize::MAX;
767
768/// Facts about a map or sequence.
769///
770/// The shape is carried by [`Event::MapStart`] and [`Event::SeqStart`].  It
771/// holds information that formats can use to encode or decode a container,
772/// all of which can be ignored:
773///
774/// * [`order`](Self::order): how significant the order of the elements is.
775/// * [`len`](Self::len): the number of elements (entries for maps) if known.
776/// * [`is_multimap`](Self::is_multimap): the keys of the map can be given
777///   more than once.
778///
779/// ```
780/// use deser::{ContainerShape, Order};
781///
782/// const SHAPE: ContainerShape =
783///     ContainerShape::new().with_order(Order::Sorted);
784/// assert_eq!(SHAPE.order(), Order::Sorted);
785/// assert_eq!(SHAPE.len(), None);
786/// ```
787#[derive(Clone, Copy, PartialEq, Eq, Hash)]
788pub struct ContainerShape {
789    len: usize,
790    flags: u32,
791}
792
793impl ContainerShape {
794    /// Creates the default shape: unknown length and natural order.
795    #[inline]
796    pub const fn new() -> ContainerShape {
797        ContainerShape {
798            len: UNKNOWN_LEN,
799            flags: 0,
800        }
801    }
802
803    /// Sets the number of elements.
804    #[inline]
805    pub const fn with_len(mut self, len: usize) -> ContainerShape {
806        self.len = len;
807        self
808    }
809
810    /// Sets the order.
811    #[inline]
812    pub const fn with_order(mut self, order: Order) -> ContainerShape {
813        self.flags = (self.flags & !ORDER_MASK) | order.to_bits();
814        self
815    }
816
817    /// Returns the number of elements (entries for maps) if known.
818    #[inline]
819    #[allow(clippy::len_without_is_empty)]
820    pub const fn len(&self) -> Option<usize> {
821        if self.len == UNKNOWN_LEN {
822            None
823        } else {
824            Some(self.len)
825        }
826    }
827
828    /// Returns how significant the order of the elements is.
829    #[inline]
830    pub const fn order(&self) -> Order {
831        Order::from_bits(self.flags)
832    }
833
834    /// Marks a map as a multimap: its keys can be given more than once.
835    ///
836    /// Formats where keys can repeat (like query strings with `a=1&a=2`,
837    /// the elements of XML or the columns of CSV files) emit their maps
838    /// with this flag and pass on every occurrence of a key as an entry of
839    /// its own, in the order of the input.  How repeated keys are resolved
840    /// is up to the type that receives the map:
841    ///
842    /// * The fields of derived structs and the values of maps whose type is
843    ///   a collection (like `Vec<T>` or `HashSet<T>`) collect the values
844    ///   of all occurrences of their key.  A key that is given once is a
845    ///   collection of one value and a key that is missing is an empty
846    ///   collection.
847    /// * Other fields and values receive a single value,
848    ///   [`DuplicateKeys`](crate::de::DuplicateKeys) in the
849    ///   [`State`](crate::State) decides which one: the last one, the first
850    ///   one or an error (the default).
851    ///
852    /// Types that do not know about multimaps receive the entries like
853    /// those of any other map.  See [`State::is_multimap`](crate::State::is_multimap).
854    ///
855    /// ```
856    /// use deser::de::DeserializeDriver;
857    /// use deser::{Atom, ContainerShape, Deserialize, Event};
858    ///
859    /// #[derive(Deserialize, Debug, PartialEq)]
860    /// struct Query {
861    ///     tag: Vec<String>,
862    ///     page: u32,
863    ///     user: Vec<String>,
864    /// }
865    ///
866    /// let mut out = None::<Query>;
867    /// let mut driver = DeserializeDriver::new(&mut out);
868    /// driver
869    ///     .emit(Event::MapStart(ContainerShape::new().with_multimap(true)))
870    ///     .unwrap();
871    /// for (key, value) in [("tag", "a"), ("page", "1"), ("tag", "b")] {
872    ///     driver.emit(key).unwrap();
873    ///     driver.emit(Atom::Lexical(value.into())).unwrap();
874    /// }
875    /// driver.emit(Event::MapEnd).unwrap();
876    /// drop(driver);
877    /// assert_eq!(out, Some(Query {
878    ///     tag: vec!["a".into(), "b".into()],
879    ///     page: 1,
880    ///     user: vec![],
881    /// }));
882    /// ```
883    #[inline]
884    pub const fn with_multimap(mut self, yes: bool) -> ContainerShape {
885        if yes {
886            self.flags |= MULTIMAP;
887        } else {
888            self.flags &= !MULTIMAP;
889        }
890        self
891    }
892
893    /// Returns `true` if the keys of the map can be given more than once.
894    ///
895    /// See [`with_multimap`](Self::with_multimap).
896    #[inline]
897    pub const fn is_multimap(&self) -> bool {
898        self.flags & MULTIMAP != 0
899    }
900}
901
902impl Default for ContainerShape {
903    fn default() -> ContainerShape {
904        ContainerShape::new()
905    }
906}
907
908impl fmt::Debug for ContainerShape {
909    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
910        let mut s = f.debug_struct("ContainerShape");
911        s.field("len", &self.len()).field("order", &self.order());
912        // rare, only shown if set
913        if self.is_multimap() {
914            s.field("is_multimap", &true);
915        }
916        s.finish()
917    }
918}
919
920/// Removes the length from container starts, for tests.
921#[cfg(test)]
922pub(crate) fn without_len(event: Event<'static>) -> Event<'static> {
923    match event {
924        Event::MapStart(shape) => Event::MapStart(
925            ContainerShape::new()
926                .with_order(shape.order())
927                .with_multimap(shape.is_multimap()),
928        ),
929        Event::SeqStart(shape) => Event::SeqStart(ContainerShape::new().with_order(shape.order())),
930        event => event,
931    }
932}
933
934// Every value goes through atoms and events, they have to stay small.
935#[cfg(target_pointer_width = "64")]
936const _: () = {
937    assert!(core::mem::size_of::<Atom<'static>>() == 32);
938    assert!(core::mem::size_of::<Event<'static>>() == 32);
939    assert!(core::mem::size_of::<Implicit<'static>>() == 24);
940};
941#[cfg(target_pointer_width = "32")]
942const _: () = {
943    assert!(core::mem::size_of::<Atom<'static>>() == 24);
944    assert!(core::mem::size_of::<Event<'static>>() == 24);
945    assert!(core::mem::size_of::<Implicit<'static>>() == 16);
946};
947
948#[test]
949fn test_implicit_packing() {
950    for value in [
951        ImplicitValue::Null,
952        ImplicitValue::Bool(false),
953        ImplicitValue::Bool(true),
954        ImplicitValue::U64(u64::MAX),
955        ImplicitValue::I64(i64::MIN),
956        ImplicitValue::I64(-1),
957        ImplicitValue::F64(-0.0),
958        ImplicitValue::F64(f64::NAN),
959        ImplicitValue::F64(1.1),
960    ] {
961        for implicit in [
962            Implicit::new("text", value),
963            Implicit::new(String::from("text"), value),
964        ] {
965            let borrowed = implicit.text().is_borrowed();
966            assert!(implicit.value().is_same(value));
967            assert_eq!(implicit.text(), "text");
968            assert_eq!(implicit.text().len(), 4);
969            assert!(implicit.clone().value().is_same(value));
970            assert!(implicit.as_borrowed().value().is_same(value));
971            assert!(implicit.to_static().value().is_same(value));
972            assert_eq!(implicit.clone().text().is_borrowed(), borrowed);
973            let (text, inner) = implicit.into_parts();
974            assert_eq!(text, "text");
975            assert_eq!(text.tag(), 0);
976            assert!(inner.is_same(value));
977        }
978    }
979}