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