Skip to main content

deser_core/
std_impls.rs

1//! `Serialize` and `Deserialize` for leaf types of the standard library.
2//!
3//! The containers and pointers are implemented next to the primitives in
4//! `ser::impls` and `de::impls`.
5use alloc::borrow::Cow;
6use alloc::boxed::Box;
7use alloc::ffi::CString;
8use alloc::format;
9use alloc::string::String;
10use alloc::string::ToString;
11use alloc::vec::Vec;
12use core::cmp::Reverse;
13use core::convert::Infallible;
14use core::ffi::CStr;
15use core::fmt::Display;
16use core::marker::PhantomData;
17use core::mem::ManuallyDrop;
18use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
19use core::num::{NonZero, Saturating, Wrapping};
20use core::ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo};
21use core::str::FromStr;
22
23use crate::State;
24use crate::Text;
25use crate::de::duplicates::duplicate_field;
26use crate::de::impls::{Via, deserialize_via};
27use crate::de::{Deserialize, Sink, SinkHandle, Slot, default_atom};
28use crate::error::{Error, ErrorKind, unknown_variant};
29use crate::event::{Atom, Bytes};
30use crate::ext::ExtValue;
31use crate::ser::{
32    Begin, Describe, Emit, Serialize, SerializeHandle, SerializeRef, StructEmitter, Variant,
33    VariantKind, VariantRepr,
34};
35
36// PhantomData
37
38/// Serializes as null like `()`.
39impl<T: ?Sized + Sync> Serialize for PhantomData<T> {
40    begin_without_finish!();
41
42    fn serialize<'a>(_value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
43        Ok(Emit::Atom(Atom::Null))
44    }
45
46    fn is_optional(_value: &Self) -> bool {
47        true
48    }
49}
50
51/// Deserializes from null.  Missing values are accepted as the value is
52/// skipped by `#[deser(skip_serializing_optionals)]`.
53impl<'de, T: ?Sized + Send> Deserialize<'de> for PhantomData<T> {
54    fn deserialize_atom(slot: &mut Slot<Self>, atom: Atom, state: &mut State) -> Result<(), Error> {
55        match atom {
56            Atom::Null => {
57                slot.set(PhantomData);
58                Ok(())
59            }
60            other => default_atom(slot, other, state),
61        }
62    }
63
64    fn expecting() -> Cow<'static, str> {
65        Cow::Borrowed("null")
66    }
67
68    fn initial_value() -> Option<Self> {
69        Some(PhantomData)
70    }
71}
72
73// Wrapping, Saturating and Reverse
74
75macro_rules! newtype_wrapper {
76    ($($ty:ident),*) => {
77        $(
78            impl<T: Serialize> Serialize for $ty<T> {
79                fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
80                    T::serialize(&value.0, state)
81                }
82
83                fn finish(value: &Self, state: &mut State) -> Result<(), Error> {
84                    T::finish(&value.0, state)
85                }
86
87                #[inline]
88                fn __private_begin<'a>(value: &'a Self, state: &mut State) -> Result<Begin<'a>, Error> {
89                    T::__private_begin(&value.0, state)
90                }
91
92                fn is_optional(value: &Self) -> bool {
93                    T::is_optional(&value.0)
94                }
95
96                fn container_shape(value: &Self) -> crate::ContainerShape {
97                    T::container_shape(&value.0)
98                }
99
100                fn describe(value: &Self, d: &mut dyn Describe) {
101                    d.newtype(stringify!($ty));
102                    T::describe(&value.0, d);
103                }
104            }
105
106            impl<T: Send> Via<T> for $ty<T> {
107                #[inline]
108                fn convert(value: T) -> Result<Self, Error> {
109                    Ok($ty(value))
110                }
111            }
112
113            deserialize_via! {
114                [T: Deserialize<'de>] $ty<T> => T {
115                    fn describe_type(d: &mut dyn Describe) {
116                        d.newtype(stringify!($ty));
117                        T::describe_type(d);
118                    }
119                };
120            }
121        )*
122    };
123}
124
125newtype_wrapper!(Wrapping, Saturating, Reverse);
126
127// ManuallyDrop
128
129/// Serializes as the inner value.
130impl<T: Serialize> Serialize for ManuallyDrop<T> {
131    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
132        T::serialize(value, state)
133    }
134
135    fn finish(value: &Self, state: &mut State) -> Result<(), Error> {
136        T::finish(value, state)
137    }
138
139    #[inline]
140    fn __private_begin<'a>(value: &'a Self, state: &mut State) -> Result<Begin<'a>, Error> {
141        T::__private_begin(value, state)
142    }
143
144    fn is_optional(value: &Self) -> bool {
145        T::is_optional(value)
146    }
147
148    fn container_shape(value: &Self) -> crate::ContainerShape {
149        T::container_shape(value)
150    }
151
152    fn describe(value: &Self, d: &mut dyn Describe) {
153        T::describe(value, d);
154    }
155}
156
157impl<T: Send> Via<T> for ManuallyDrop<T> {
158    #[inline]
159    fn convert(value: T) -> Result<Self, Error> {
160        Ok(ManuallyDrop::new(value))
161    }
162}
163
164deserialize_via! {
165    [T: Deserialize<'de>] ManuallyDrop<T> => T {
166        fn describe_type(d: &mut dyn Describe) {
167            T::describe_type(d);
168        }
169    };
170}
171
172// Infallible
173
174/// Values of `Infallible` do not exist, they are never serialized.
175impl Serialize for Infallible {
176    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
177        match *value {}
178    }
179}
180
181/// Deserializing `Infallible` always fails, for instance to rule out a
182/// variant of a generic enum (`Result<T, Infallible>`).
183impl<'de> Deserialize<'de> for Infallible {
184    fn expecting() -> Cow<'static, str> {
185        Cow::Borrowed("nothing")
186    }
187}
188
189// NonZero
190
191macro_rules! non_zero {
192    ($($ty:ty => $atom:ident),* $(,)?) => {
193        $(
194            impl Serialize for NonZero<$ty> {
195                begin_without_finish!();
196
197                fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
198                    Ok(Emit::Atom(non_zero!(@atom $atom, value.get())))
199                }
200            }
201
202            impl Via<$ty> for NonZero<$ty> {
203                #[inline]
204                fn convert(value: $ty) -> Result<Self, Error> {
205                    NonZero::new(value).ok_or_else(|| {
206                        Error::new(ErrorKind::OutOfRange, "value must be non-zero")
207                    })
208                }
209            }
210
211            deserialize_via! {
212                [] NonZero<$ty> => $ty;
213            }
214        )*
215    };
216    (@atom Ext, $value:expr) => { Atom::Ext(ExtValue::owned($value)) };
217    (@atom $atom:ident, $value:expr) => { Atom::$atom($value as _) };
218}
219
220non_zero! {
221    u8 => U64,
222    u16 => U64,
223    u32 => U64,
224    u64 => U64,
225    usize => U64,
226    u128 => Ext,
227    i8 => I64,
228    i16 => I64,
229    i32 => I64,
230    i64 => I64,
231    isize => I64,
232    i128 => Ext,
233}
234
235// Atomics
236
237macro_rules! atomic {
238    ($($cfg:literal: $ty:ident($prim:ty) => $atom:ident),* $(,)?) => {
239        $(
240            /// The value is loaded with relaxed ordering.
241            #[cfg(target_has_atomic = $cfg)]
242            impl Serialize for core::sync::atomic::$ty {
243                begin_without_finish!();
244
245                fn serialize<'a>(this: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
246                    let value = this.load(core::sync::atomic::Ordering::Relaxed);
247                    Ok(Emit::Atom(Atom::$atom(value as _)))
248                }
249            }
250
251            #[cfg(target_has_atomic = $cfg)]
252            impl Via<$prim> for core::sync::atomic::$ty {
253                #[inline]
254                fn convert(value: $prim) -> Result<Self, Error> {
255                    Ok(core::sync::atomic::$ty::new(value))
256                }
257            }
258
259            #[cfg(target_has_atomic = $cfg)]
260            deserialize_via! {
261                [] core::sync::atomic::$ty => $prim;
262            }
263        )*
264    };
265}
266
267atomic! {
268    "8": AtomicBool(bool) => Bool,
269    "8": AtomicU8(u8) => U64,
270    "8": AtomicI8(i8) => I64,
271    "16": AtomicU16(u16) => U64,
272    "16": AtomicI16(i16) => I64,
273    "32": AtomicU32(u32) => U64,
274    "32": AtomicI32(i32) => I64,
275    "64": AtomicU64(u64) => U64,
276    "64": AtomicI64(i64) => I64,
277    "ptr": AtomicUsize(usize) => U64,
278    "ptr": AtomicIsize(isize) => I64,
279}
280
281// Result
282
283/// Emits the single entry of an externally tagged `Ok` or `Err`.
284struct ResultEmitter<'a> {
285    name: &'static str,
286    value: Option<SerializeHandle<'a>>,
287}
288
289impl<'a> StructEmitter for ResultEmitter<'a> {
290    fn next(
291        &mut self,
292        _state: &mut State,
293    ) -> Result<Option<(Cow<'_, str>, SerializeHandle<'_>)>, Error> {
294        Ok(self
295            .value
296            .take()
297            .map(|value| (Cow::Borrowed(self.name), value)))
298    }
299}
300
301/// Describes a variant of a `Result`.
302fn describe_result<T, E>(value: &Result<T, E>, d: &mut dyn Describe) {
303    d.variant(&Variant::new(
304        "Result",
305        result_name(value),
306        VariantKind::Newtype,
307        VariantRepr::External,
308    ));
309}
310
311fn result_name<T, E>(value: &Result<T, E>) -> &'static str {
312    match value {
313        Ok(_) => "Ok",
314        Err(_) => "Err",
315    }
316}
317
318/// Serializes externally tagged: `{"Ok": value}` or `{"Err": error}`.
319impl<T, E, TA, EA> Serialize<Result<T, E>> for Result<TA, EA>
320where
321    T: Sync,
322    E: Sync,
323    TA: Serialize<T>,
324    EA: Serialize<E>,
325{
326    fn describe(value: &Result<T, E>, d: &mut dyn Describe) {
327        describe_result(value, d);
328    }
329
330    fn serialize<'a>(value: &'a Result<T, E>, state: &mut State) -> Result<Emit<'a>, Error> {
331        let handle = match value {
332            Ok(value) => SerializeRef::serialize_as::<TA, T>(value).into(),
333            Err(err) => SerializeRef::serialize_as::<EA, E>(err).into(),
334        };
335        Ok(Emit::structure(
336            ResultEmitter {
337                name: result_name(value),
338                value: Some(handle),
339            },
340            state,
341        ))
342    }
343
344    #[inline]
345    fn __private_begin<'a>(value: &'a Result<T, E>, state: &mut State) -> Result<Begin<'a>, Error> {
346        Ok(Begin::emit(
347            Self::serialize(value, state)?,
348            crate::ContainerShape::new(),
349            false,
350        ))
351    }
352}
353
354/// What results expect.
355const RESULT_NAME: &str = "Result";
356
357/// The variant of a `Result`.
358#[derive(Clone, Copy)]
359enum ResultVariant {
360    Ok,
361    Err,
362}
363
364impl<'de> Deserialize<'de> for ResultVariant {
365    fn deserialize_atom(slot: &mut Slot<Self>, atom: Atom, state: &mut State) -> Result<(), Error> {
366        match atom {
367            Atom::Str(ref name) => {
368                slot.set(match &**name {
369                    "Ok" => ResultVariant::Ok,
370                    "Err" => ResultVariant::Err,
371                    other => return Err(unknown_variant(Some(other), "Result", &["Ok", "Err"])),
372                });
373                Ok(())
374            }
375            other => default_atom(slot, other, state),
376        }
377    }
378
379    fn expecting() -> Cow<'static, str> {
380        Cow::Borrowed("Ok or Err")
381    }
382}
383
384/// Creates the sink for a `Result` with adapters.
385fn result_sink<'a, 'de, T, E, TA, EA>(
386    out: &'a mut Option<Result<T, E>>,
387    state: &mut State,
388) -> SinkHandle<'a, 'de>
389where
390    T: Send + 'a,
391    E: Send + 'a,
392    TA: Deserialize<'de, T>,
393    EA: Deserialize<'de, E>,
394{
395    struct ResultSink<'a, T, E, TA, EA> {
396        slot: &'a mut Option<Result<T, E>>,
397        variant: Option<ResultVariant>,
398        ok: Option<T>,
399        err: Option<E>,
400        _marker: PhantomData<fn() -> (TA, EA)>,
401    }
402
403    impl<'de, 'a, T, E, TA, EA> Sink<'de> for ResultSink<'a, T, E, TA, EA>
404    where
405        T: Send,
406        E: Send,
407        TA: Deserialize<'de, T>,
408        EA: Deserialize<'de, E>,
409    {
410        fn expecting(&self) -> Cow<'_, str> {
411            Cow::Borrowed(RESULT_NAME)
412        }
413
414        fn map(&mut self, _state: &mut State) -> Result<(), Error> {
415            Ok(())
416        }
417
418        fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
419            if self.variant.is_some() {
420                return Err(Error::new(
421                    ErrorKind::InvalidType,
422                    "expected a single entry for Result",
423                ));
424            }
425            Ok(ResultVariant::deserialize_into(&mut self.variant, state))
426        }
427
428        fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
429            Ok(match self.variant {
430                Some(ResultVariant::Ok) => TA::deserialize_into(&mut self.ok, state),
431                Some(ResultVariant::Err) => EA::deserialize_into(&mut self.err, state),
432                None => SinkHandle::null(),
433            })
434        }
435
436        fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
437            match self.variant {
438                Some(ResultVariant::Ok) => TA::__private_atom_into(&mut self.ok, atom, state),
439                Some(ResultVariant::Err) => EA::__private_atom_into(&mut self.err, atom, state),
440                None => Ok(()),
441            }
442        }
443
444        fn __private_borrowed_value_atom(
445            &mut self,
446            atom: Atom<'de>,
447            state: &mut State,
448        ) -> Result<(), Error> {
449            match self.variant {
450                Some(ResultVariant::Ok) => {
451                    TA::__private_borrowed_atom_into(&mut self.ok, atom, state)
452                }
453                Some(ResultVariant::Err) => {
454                    EA::__private_borrowed_atom_into(&mut self.err, atom, state)
455                }
456                None => Ok(()),
457            }
458        }
459
460        fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
461            *self.slot = Some(match (self.ok.take(), self.err.take()) {
462                (Some(value), _) => Ok(value),
463                (None, Some(err)) => Err(err),
464                (None, None) => {
465                    return Err(Error::new(
466                        ErrorKind::InvalidType,
467                        "expected an entry with Ok or Err",
468                    ));
469                }
470            });
471            Ok(())
472        }
473    }
474
475    // SAFETY: `TA` and `EA` are adapters, the sink only holds a marker of
476    // them
477    unsafe {
478        SinkHandle::arena_unbounded(
479            ResultSink::<T, E, TA, EA> {
480                slot: out,
481                variant: None,
482                ok: None,
483                err: None,
484                _marker: PhantomData,
485            },
486            state,
487        )
488    }
489}
490
491impl<'de, T, E, TA, EA> Deserialize<'de, Result<T, E>> for Result<TA, EA>
492where
493    T: Send,
494    E: Send,
495    TA: Deserialize<'de, T>,
496    EA: Deserialize<'de, E>,
497{
498    fn deserialize_into<'out>(
499        out: &'out mut Option<Result<T, E>>,
500        state: &mut State,
501    ) -> SinkHandle<'out, 'de> {
502        result_sink::<T, E, TA, EA>(out, state)
503    }
504
505    fn expecting() -> Cow<'static, str> {
506        Cow::Borrowed(RESULT_NAME)
507    }
508}
509
510// Types that are represented as strings
511
512/// Types that are deserialized by parsing a string.
513trait Parse: FromStr<Err: Display> + Send {
514    /// What the type expects, for error messages.
515    const EXPECTING: &'static str;
516}
517
518/// Deserializes a type that is parsed from a string.
519fn parse_atom<'de, T: Parse + Deserialize<'de>>(
520    slot: &mut Slot<T>,
521    atom: Atom,
522    state: &mut State,
523) -> Result<(), Error> {
524    match atom {
525        Atom::Str(ref value) => match value.parse::<T>() {
526            Ok(value) => {
527                slot.set(value);
528                Ok(())
529            }
530            Err(err) => Err(Error::new(
531                ErrorKind::InvalidValue,
532                format!("invalid {}: {}", T::EXPECTING, err),
533            )),
534        },
535        other => default_atom(slot, other, state),
536    }
537}
538
539macro_rules! parse_from_str {
540    ($($ty:ty => $expecting:literal),* $(,)?) => {
541        $(
542            impl Parse for $ty {
543                const EXPECTING: &'static str = $expecting;
544            }
545
546            /// Serializes as a string (with `Display`).
547            impl Serialize for $ty {
548                begin_without_finish!();
549
550                fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
551                    Ok(Emit::Atom(Atom::Str(Text::owned(value.to_string()))))
552                }
553            }
554
555            impl<'de> Deserialize<'de> for $ty {
556                fn deserialize_atom(
557                    slot: &mut Slot<Self>,
558                    atom: Atom,
559                    state: &mut State,
560                ) -> Result<(), Error> {
561                    parse_atom(slot, atom, state)
562                }
563
564                fn expecting() -> Cow<'static, str> {
565                    Cow::Borrowed(<$ty as Parse>::EXPECTING)
566                }
567
568                slot_atom_into!();
569            }
570        )*
571    };
572}
573
574parse_from_str! {
575    IpAddr => "IP address",
576    Ipv4Addr => "IPv4 address",
577    Ipv6Addr => "IPv6 address",
578    SocketAddr => "socket address",
579    SocketAddrV4 => "IPv4 socket address",
580    SocketAddrV6 => "IPv6 socket address",
581}
582
583// C strings
584
585/// Serializes as bytes (without the nul terminator).
586impl Serialize for CStr {
587    begin_without_finish!();
588
589    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
590        Ok(Emit::Atom(Atom::Bytes(Bytes::new(value.to_bytes()))))
591    }
592}
593
594impl Serialize for CString {
595    begin_without_finish!();
596
597    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
598        CStr::serialize(value.as_c_str(), state)
599    }
600}
601
602impl Via<Vec<u8>> for CString {
603    #[inline]
604    fn convert(value: Vec<u8>) -> Result<Self, Error> {
605        CString::new(value).map_err(|err| Error::new(ErrorKind::InvalidValue, err.to_string()))
606    }
607}
608
609impl Via<CString> for Box<CStr> {
610    #[inline]
611    fn convert(value: CString) -> Result<Self, Error> {
612        Ok(value.into_boxed_c_str())
613    }
614}
615
616deserialize_via! {
617    [] CString => Vec<u8>;
618    [] Box<CStr> => CString;
619}
620
621// Ranges
622
623/// Emits a fixed number of fields.
624struct FieldsEmitter<'a, const N: usize> {
625    fields: [(&'static str, SerializeRef<'a>); N],
626    index: usize,
627}
628
629impl<'a, const N: usize> FieldsEmitter<'a, N> {
630    fn emit(fields: [(&'static str, SerializeRef<'a>); N], state: &mut State) -> Emit<'a> {
631        Emit::structure(FieldsEmitter { fields, index: 0 }, state)
632    }
633}
634
635impl<'a, const N: usize> StructEmitter for FieldsEmitter<'a, N> {
636    fn next(
637        &mut self,
638        _state: &mut State,
639    ) -> Result<Option<(Cow<'_, str>, SerializeHandle<'_>)>, Error> {
640        let rv = self
641            .fields
642            .get(self.index)
643            .map(|&(name, value)| (Cow::Borrowed(name), SerializeHandle::from(value)));
644        self.index += 1;
645        Ok(rv)
646    }
647}
648
649/// Serializes as a struct with `start` and `end` like serde.
650impl<T: Serialize> Serialize for Range<T> {
651    begin_without_finish!();
652
653    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
654        Ok(FieldsEmitter::emit(
655            [
656                ("start", SerializeRef::new(&value.start)),
657                ("end", SerializeRef::new(&value.end)),
658            ],
659            state,
660        ))
661    }
662}
663
664/// Serializes as a struct with `start` and `end` like serde.
665impl<T: Serialize> Serialize for RangeInclusive<T> {
666    begin_without_finish!();
667
668    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
669        Ok(FieldsEmitter::emit(
670            [
671                ("start", SerializeRef::new(value.start())),
672                ("end", SerializeRef::new(value.end())),
673            ],
674            state,
675        ))
676    }
677}
678
679/// Serializes as a struct with `start` like serde.
680impl<T: Serialize> Serialize for RangeFrom<T> {
681    begin_without_finish!();
682
683    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
684        Ok(FieldsEmitter::emit(
685            [("start", SerializeRef::new(&value.start))],
686            state,
687        ))
688    }
689}
690
691/// Serializes as a struct with `end` like serde.
692impl<T: Serialize> Serialize for RangeTo<T> {
693    begin_without_finish!();
694
695    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
696        Ok(FieldsEmitter::emit(
697            [("end", SerializeRef::new(&value.end))],
698            state,
699        ))
700    }
701}
702
703/// What ranges expect.
704const RANGE_NAME: &str = "range";
705
706/// Deserializes the fields of a range.
707struct RangeSink<'a, T, R> {
708    slot: &'a mut Option<R>,
709    key: Option<String>,
710    start: Option<T>,
711    end: Option<T>,
712    // the fields of the range, `start` and/or `end`
713    fields: &'static [&'static str],
714    make: fn(Option<T>, Option<T>) -> R,
715}
716
717impl<'a, T, R> RangeSink<'a, T, R> {
718    fn handle<'de>(
719        slot: &'a mut Option<R>,
720        fields: &'static [&'static str],
721        make: fn(Option<T>, Option<T>) -> R,
722        state: &mut State,
723    ) -> SinkHandle<'a, 'de>
724    where
725        T: Deserialize<'de> + 'a,
726        R: Send + 'a,
727    {
728        SinkHandle::arena(
729            RangeSink {
730                slot,
731                key: None,
732                start: None,
733                end: None,
734                fields,
735                make,
736            },
737            state,
738        )
739    }
740}
741
742impl<'a, 'de, T: Deserialize<'de>, R: Send> Sink<'de> for RangeSink<'a, T, R> {
743    fn expecting(&self) -> Cow<'_, str> {
744        Cow::Borrowed(RANGE_NAME)
745    }
746
747    fn map(&mut self, _state: &mut State) -> Result<(), Error> {
748        Ok(())
749    }
750
751    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
752        Ok(String::deserialize_into(&mut self.key, state))
753    }
754
755    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
756        let key = self.key.take().unwrap_or_default();
757        Ok(self
758            .value_for_key(&key, state)?
759            .unwrap_or_else(SinkHandle::null))
760    }
761
762    fn value_for_key(
763        &mut self,
764        key: &str,
765        state: &mut State,
766    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
767        let slot = match key {
768            "start" if self.fields.contains(&"start") => &mut self.start,
769            "end" if self.fields.contains(&"end") => &mut self.end,
770            _ => return Ok(None),
771        };
772        if slot.is_some() && !duplicate_field(key, state)? {
773            return Ok(Some(SinkHandle::null()));
774        }
775        Ok(Some(T::deserialize_into(slot, state)))
776    }
777
778    fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
779        for (name, value) in [("start", self.start.is_some()), ("end", self.end.is_some())] {
780            if !value && self.fields.contains(&name) {
781                return Err(Error::new(
782                    ErrorKind::MissingField,
783                    format!("missing field `{}`", name),
784                ));
785            }
786        }
787        *self.slot = Some((self.make)(self.start.take(), self.end.take()));
788        Ok(())
789    }
790}
791
792impl<'de, T: Deserialize<'de>> Deserialize<'de> for Range<T> {
793    fn deserialize_into<'out>(
794        out: &'out mut Option<Self>,
795        state: &mut State,
796    ) -> SinkHandle<'out, 'de> {
797        RangeSink::handle(
798            out,
799            &["start", "end"],
800            |start, end| Range {
801                start: start.unwrap(),
802                end: end.unwrap(),
803            },
804            state,
805        )
806    }
807
808    fn expecting() -> Cow<'static, str> {
809        Cow::Borrowed(RANGE_NAME)
810    }
811}
812
813impl<'de, T: Deserialize<'de>> Deserialize<'de> for RangeInclusive<T> {
814    fn deserialize_into<'out>(
815        out: &'out mut Option<Self>,
816        state: &mut State,
817    ) -> SinkHandle<'out, 'de> {
818        RangeSink::handle(
819            out,
820            &["start", "end"],
821            |start, end| RangeInclusive::new(start.unwrap(), end.unwrap()),
822            state,
823        )
824    }
825
826    fn expecting() -> Cow<'static, str> {
827        Cow::Borrowed(RANGE_NAME)
828    }
829}
830
831impl<'de, T: Deserialize<'de>> Deserialize<'de> for RangeFrom<T> {
832    fn deserialize_into<'out>(
833        out: &'out mut Option<Self>,
834        state: &mut State,
835    ) -> SinkHandle<'out, 'de> {
836        RangeSink::handle(
837            out,
838            &["start"],
839            |start, _| RangeFrom {
840                start: start.unwrap(),
841            },
842            state,
843        )
844    }
845
846    fn expecting() -> Cow<'static, str> {
847        Cow::Borrowed(RANGE_NAME)
848    }
849}
850
851impl<'de, T: Deserialize<'de>> Deserialize<'de> for RangeTo<T> {
852    fn deserialize_into<'out>(
853        out: &'out mut Option<Self>,
854        state: &mut State,
855    ) -> SinkHandle<'out, 'de> {
856        RangeSink::handle(out, &["end"], |_, end| RangeTo { end: end.unwrap() }, state)
857    }
858
859    fn expecting() -> Cow<'static, str> {
860        Cow::Borrowed(RANGE_NAME)
861    }
862}
863
864// Bound
865
866/// Serializes externally tagged like serde: `"Unbounded"`, `{"Included":
867/// value}` or `{"Excluded": value}`.
868impl<T: Serialize> Serialize for Bound<T> {
869    begin_without_finish!();
870
871    fn describe(value: &Self, d: &mut dyn Describe) {
872        let (name, kind) = match value {
873            Bound::Included(_) => ("Included", VariantKind::Newtype),
874            Bound::Excluded(_) => ("Excluded", VariantKind::Newtype),
875            Bound::Unbounded => ("Unbounded", VariantKind::Unit),
876        };
877        d.variant(&Variant::new("Bound", name, kind, VariantRepr::External));
878    }
879
880    fn serialize<'a>(this: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
881        Ok(match this {
882            Bound::Included(value) => {
883                FieldsEmitter::emit([("Included", SerializeRef::new(value))], state)
884            }
885            Bound::Excluded(value) => {
886                FieldsEmitter::emit([("Excluded", SerializeRef::new(value))], state)
887            }
888            Bound::Unbounded => Emit::Atom(Atom::Str(Text::borrowed("Unbounded"))),
889        })
890    }
891}
892
893/// What bounds expect.
894const BOUND_NAME: &str = "Bound";
895
896/// Deserializes a `Bound`.
897struct BoundSink<'a, T> {
898    slot: &'a mut Option<Bound<T>>,
899    // the variant, `true` for `Included`
900    included: Option<bool>,
901    key: Option<String>,
902    value: Option<T>,
903}
904
905impl<'a, 'de, T: Deserialize<'de>> Sink<'de> for BoundSink<'a, T> {
906    fn expecting(&self) -> Cow<'_, str> {
907        Cow::Borrowed(BOUND_NAME)
908    }
909
910    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
911        match atom {
912            Atom::Str(ref name) | Atom::Lexical(ref name) => {
913                if &**name != "Unbounded" {
914                    return Err(unknown_variant(Some(name), "Bound", BOUND_VARIANTS));
915                }
916                *self.slot = Some(Bound::Unbounded);
917                Ok(())
918            }
919            other => default_atom(self, other, state),
920        }
921    }
922
923    fn map(&mut self, _state: &mut State) -> Result<(), Error> {
924        Ok(())
925    }
926
927    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
928        if self.included.is_some() {
929            return Err(Error::new(
930                ErrorKind::InvalidType,
931                "expected a map with a single key for Bound",
932            ));
933        }
934        Ok(String::deserialize_into(&mut self.key, state))
935    }
936
937    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
938        let key = self.key.take().unwrap_or_default();
939        self.included = Some(match &*key {
940            "Included" => true,
941            "Excluded" => false,
942            other => return Err(unknown_variant(Some(other), "Bound", BOUND_VARIANTS)),
943        });
944        Ok(T::deserialize_into(&mut self.value, state))
945    }
946
947    fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
948        if self.slot.is_some() {
949            return Ok(());
950        }
951        *self.slot = Some(match (self.included, self.value.take()) {
952            (Some(true), Some(value)) => Bound::Included(value),
953            (Some(false), Some(value)) => Bound::Excluded(value),
954            _ => {
955                return Err(Error::new(
956                    ErrorKind::InvalidType,
957                    "expected a map with a single key for Bound",
958                ));
959            }
960        });
961        Ok(())
962    }
963}
964
965const BOUND_VARIANTS: &[&str] = &["Unbounded", "Included", "Excluded"];
966
967impl<'de, T: Deserialize<'de>> Deserialize<'de> for Bound<T> {
968    fn deserialize_into<'out>(
969        out: &'out mut Option<Self>,
970        state: &mut State,
971    ) -> SinkHandle<'out, 'de> {
972        SinkHandle::arena(
973            BoundSink {
974                slot: out,
975                included: None,
976                key: None,
977                value: None,
978            },
979            state,
980        )
981    }
982
983    fn expecting() -> Cow<'static, str> {
984        Cow::Borrowed(BOUND_NAME)
985    }
986}