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