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