1use alloc::borrow::Cow;
4use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
5use alloc::string::String;
6use alloc::vec::Vec;
7#[cfg(feature = "std")]
8use core::hash::{BuildHasher, Hash};
9use core::marker::PhantomData;
10use core::mem::take;
11#[cfg(feature = "std")]
12use std::collections::{HashMap, HashSet};
13
14use crate::State;
15use crate::Text;
16use crate::adapted::{self, Adapted};
17use crate::adapters::Same;
18use crate::de::impls::{MapOut, MapTarget, map_sink};
19use crate::de::recording::{Capture, RecordBuf};
20use crate::de::update::Collection;
21use crate::de::{CollectedErrors, Deserialize, DuplicateKeys, Sink, SinkHandle};
22use crate::error::{Error, ErrorKind};
23use crate::event::{Atom, ContainerShape, Order};
24use crate::extensions::EventData;
25use crate::ser::impls::{MapIterEmitter, handle_as};
26use crate::ser::{Emit, IndexedSeq, IndexedSeqEmitter, SeqEmitter, Serialize, SerializeHandle};
27
28pub struct OneOrMany<A = Same, F = PreferOne>(PhantomData<fn() -> (A, F)>);
68
69pub struct PreferOne;
71
72pub struct PreferMany;
74
75mod sealed {
76 pub trait Sealed {}
77 impl Sealed for super::PreferOne {}
78 impl Sealed for super::PreferMany {}
79}
80
81pub trait OneOrManyForm: sealed::Sealed + 'static {
85 #[doc(hidden)]
86 const PREFER_ONE: bool;
87}
88
89impl OneOrManyForm for PreferOne {
90 const PREFER_ONE: bool = true;
91}
92
93impl OneOrManyForm for PreferMany {
94 const PREFER_ONE: bool = false;
95}
96
97enum OneOrManySink<'a, 'de, C> {
102 Pending(&'a mut Option<C>),
103 Active(SinkHandle<'a, 'de>),
104}
105
106impl<'a, 'de, C: Send> OneOrManySink<'a, 'de, C> {
107 fn active<T, A, M>(&mut self, many: bool, state: &mut State) -> &mut SinkHandle<'a, 'de>
113 where
114 C: Collection<T>,
115 T: Send + 'a,
116 A: Deserialize<'de, T>,
117 M: Deserialize<'de, C>,
118 {
119 if let OneOrManySink::Pending(..) = self
120 && let OneOrManySink::Pending(out) =
121 core::mem::replace(self, OneOrManySink::Active(SinkHandle::null()))
122 {
123 *self = OneOrManySink::Active(if many {
124 M::deserialize_into(out, state)
125 } else {
126 crate::de::update::collect_into::<C, T, A>(out, state)
127 });
128 }
129 match self {
130 OneOrManySink::Active(sink) => sink,
131 OneOrManySink::Pending(..) => unreachable!(),
132 }
133 }
134}
135
136fn atom_is_many<'de, T: Send, A: Deserialize<'de, T>>(atom: &Atom) -> bool {
141 A::__private_is_bytes() && matches!(atom, Atom::Bytes(_) | Atom::Str(_))
142}
143
144impl<'a, 'de, C, T, A, M> Sink<'de> for Adapted<(T, A, M), OneOrManySink<'a, 'de, C>>
145where
146 C: Collection<T>,
147 T: Send + 'a,
148 A: Deserialize<'de, T>,
149 M: Deserialize<'de, C>,
150{
151 fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
152 let many = atom_is_many::<T, A>(&atom);
153 self.active::<T, A, M>(many, state).atom(atom, state)
154 }
155
156 fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
157 let many = atom_is_many::<T, A>(&atom);
158 self.active::<T, A, M>(many, state)
159 .borrowed_atom(atom, state)
160 }
161
162 fn map(&mut self, state: &mut State) -> Result<(), Error> {
163 self.active::<T, A, M>(false, state).map(state)
164 }
165
166 fn seq(&mut self, state: &mut State) -> Result<(), Error> {
167 self.active::<T, A, M>(true, state).seq(state)
168 }
169
170 fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
171 self.active::<T, A, M>(true, state).__private_seq(state)
172 }
173
174 fn __private_inline_atom(
175 &mut self,
176 index: usize,
177 atom: Atom,
178 state: &mut State,
179 ) -> Result<(), Error> {
180 self.active::<T, A, M>(true, state)
181 .__private_inline_atom(index, atom, state)
182 }
183
184 fn __private_inline_event(
185 &mut self,
186 event: crate::de::InlineEvent,
187 state: &mut State,
188 ) -> Result<(), Error> {
189 self.active::<T, A, M>(true, state)
190 .__private_inline_event(event, state)
191 }
192
193 fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
194 self.active::<T, A, M>(false, state).next_key(state)
195 }
196
197 fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
198 self.active::<T, A, M>(false, state).next_value(state)
199 }
200
201 fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
202 self.active::<T, A, M>(false, state)
203 .__private_key_atom(atom, state)
204 }
205
206 fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
207 self.active::<T, A, M>(false, state)
208 .__private_value_atom(atom, state)
209 }
210
211 fn __private_borrowed_key_atom(
212 &mut self,
213 atom: Atom<'de>,
214 state: &mut State,
215 ) -> Result<(), Error> {
216 self.active::<T, A, M>(false, state)
217 .__private_borrowed_key_atom(atom, state)
218 }
219
220 fn __private_borrowed_value_atom(
221 &mut self,
222 atom: Atom<'de>,
223 state: &mut State,
224 ) -> Result<(), Error> {
225 self.active::<T, A, M>(false, state)
226 .__private_borrowed_value_atom(atom, state)
227 }
228
229 fn value_for_key(
230 &mut self,
231 key: &str,
232 state: &mut State,
233 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
234 self.active::<T, A, M>(false, state)
235 .value_for_key(key, state)
236 }
237
238 fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
239 self.active::<T, A, M>(false, state).recover(err, state)
240 }
241
242 fn finish(&mut self, state: &mut State) -> Result<(), Error> {
243 self.active::<T, A, M>(false, state).finish(state)
244 }
245
246 fn expecting(&self) -> Cow<'_, str> {
247 match &**self {
248 OneOrManySink::Active(sink) => sink.expecting(),
249 OneOrManySink::Pending(..) => M::expecting(),
250 }
251 }
252}
253
254macro_rules! one_or_many_impls {
260 ($([$($bound:tt)*] [$($ser_bound:tt)*] $target:ty => $many:ty;)*) => {
261 $(
262 impl<'de, $($bound)*, A: Deserialize<'de, T>, F: OneOrManyForm>
263 Deserialize<'de, $target> for OneOrMany<A, F>
264 {
265 fn deserialize_into<'out>(
266 out: &'out mut Option<$target>,
267 state: &mut State,
268 ) -> SinkHandle<'out, 'de> {
269 adapted::arena_sink::<(T, A, $many), _>(OneOrManySink::Pending(out), state)
270 }
271
272 fn expecting() -> Cow<'static, str> {
273 <$many as Deserialize<'de, $target>>::expecting()
274 }
275
276 fn initial_value() -> Option<$target> {
277 <$many as Deserialize<'de, $target>>::initial_value()
278 }
279
280 #[inline]
281 fn __private_atom_into(
282 out: &mut Option<$target>,
283 atom: Atom,
284 state: &mut State,
285 ) -> Result<(), Error> {
286 if atom_is_many::<T, A>(&atom) {
287 return <$many as Deserialize<'de, $target>>::__private_atom_into(
288 out, atom, state,
289 );
290 }
291 let mut element = None;
292 A::__private_atom_into(&mut element, atom, state)?;
293 add_element(out, element)
294 }
295
296 #[inline]
297 fn __private_borrowed_atom_into(
298 out: &mut Option<$target>,
299 atom: Atom<'de>,
300 state: &mut State,
301 ) -> Result<(), Error> {
302 if atom_is_many::<T, A>(&atom) {
303 return <$many as Deserialize<'de, $target>>::__private_borrowed_atom_into(
304 out, atom, state,
305 );
306 }
307 let mut element = None;
308 A::__private_borrowed_atom_into(&mut element, atom, state)?;
309 add_element(out, element)
310 }
311
312 fn __private_collects() -> bool {
316 <$many as Deserialize<'de, $target>>::__private_collects()
317 }
318
319 fn __private_collect_into<'out>(
320 out: &'out mut Option<$target>,
321 state: &mut State,
322 ) -> SinkHandle<'out, 'de> {
323 <$many as Deserialize<'de, $target>>::__private_collect_into(out, state)
324 }
325
326 fn __private_collect_update<'out>(
327 value: &'out mut $target,
328 first: bool,
329 state: &mut State,
330 ) -> SinkHandle<'out, 'de> {
331 <$many as Deserialize<'de, $target>>::__private_collect_update(
332 value, first, state,
333 )
334 }
335
336 fn __private_collect_empty() -> Option<$target> {
337 <$many as Deserialize<'de, $target>>::__private_collect_empty()
338 }
339 }
340
341 impl<$($ser_bound)*, A: Serialize<T>, F: OneOrManyForm> Serialize<$target>
342 for OneOrMany<A, F>
343 {
344 fn serialize<'a>(
345 value: &'a $target,
346 _state: &mut State,
347 ) -> Result<Emit<'a>, Error> {
348 let mut iter = value.iter();
349 Ok(Emit::Forward(match (iter.next(), iter.next()) {
350 (Some(element), None) if F::PREFER_ONE => handle_as::<A, T>(element),
351 _ => handle_as::<$many, $target>(value),
352 }))
353 }
354
355 fn describe(value: &$target, d: &mut dyn crate::ser::Describe) {
356 <$many as Serialize<$target>>::describe(value, d)
357 }
358 }
359 )*
360 };
361}
362
363#[inline]
365fn add_element<C: Collection<T>, T>(out: &mut Option<C>, element: Option<T>) -> Result<(), Error> {
366 if let Some(element) = element {
367 let mut collection = C::empty();
368 collection.add(element)?;
369 *out = Some(collection);
370 }
371 Ok(())
372}
373
374one_or_many_impls! {
375 [T: Send] [T: Sync] Vec<T> => Vec<A>;
376 [T: Send] [T: Sync] VecDeque<T> => VecDeque<A>;
377 [T: Ord + Send] [T: Sync] BTreeSet<T> => BTreeSet<A>;
378}
379
380#[cfg(feature = "std")]
381one_or_many_impls! {
382 [T: Hash + Eq + Send, H: BuildHasher + Default + Send]
383 [T: Sync, H: BuildHasher + Sync]
384 HashSet<T, H> => HashSet<A>;
385}
386
387pub struct PickFirst<A>(PhantomData<fn() -> A>);
417
418enum PickInput<'t, 'de> {
420 Atom(Atom<'t>),
421 Borrowed(Atom<'de>),
422 Recorded(&'t RecordBuf<'de>),
423}
424
425type Attempt<'de, T> =
427 for<'t> fn(&mut Option<T>, &PickInput<'t, 'de>, &EventData, &mut State) -> Result<(), Error>;
428
429struct Attempts<'de, T> {
431 list: [Attempt<'de, T>; 4],
432 len: usize,
433}
434
435impl<'de, T: Send> Attempts<'de, T> {
436 fn new(list: &[Attempt<'de, T>]) -> Attempts<'de, T> {
437 let mut rv = Attempts {
438 list: [list[0]; 4],
439 len: list.len(),
440 };
441 rv.list[..list.len()].copy_from_slice(list);
442 rv
443 }
444
445 fn pick(
450 &self,
451 out: &mut Option<T>,
452 input: PickInput<'_, 'de>,
453 state: &mut State,
454 ) -> Result<(), Error> {
455 let data = match input {
459 PickInput::Recorded(_) => EventData::new(),
460 _ => state.extensions().capture_event_data(),
461 };
462 for attempt in &self.list[..self.len] {
463 let mut value = None;
464 let rv = state.discard_errors(|state| attempt(&mut value, &input, &data, state));
466 if rv.is_ok() && value.is_some() {
467 *out = value;
468 return Ok(());
469 }
470 }
471 (self.list[0])(out, &input, &data, state)
472 }
473}
474
475fn pick_attempt<'de, T: Send, A: Deserialize<'de, T>>(
477 out: &mut Option<T>,
478 input: &PickInput<'_, 'de>,
479 data: &EventData,
480 state: &mut State,
481) -> Result<(), Error> {
482 if !data.is_empty() {
483 state.extensions_mut().restore_event_data(data);
484 }
485 match *input {
486 PickInput::Atom(ref atom) => A::__private_atom_into(out, atom.as_borrowed(), state),
487 PickInput::Borrowed(ref atom) => A::__private_borrowed_atom_into(out, atom.clone(), state),
488 PickInput::Recorded(buffer) => buffer.replay(A::deserialize_into(out, state), state),
489 }
490}
491
492struct PickCapture<'a, 'de, T> {
494 out: &'a mut Option<T>,
495 attempts: Attempts<'de, T>,
496 expecting: fn() -> Cow<'static, str>,
497}
498
499impl<'a, 'de, T: Send> Capture<'de, RecordBuf<'de>> for PickCapture<'a, 'de, T> {
500 fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
501 self.attempts.pick(self.out, PickInput::Atom(atom), state)
502 }
503
504 fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
505 self.attempts
506 .pick(self.out, PickInput::Borrowed(atom), state)
507 }
508
509 fn recorded(&mut self, buffer: RecordBuf<'de>, state: &mut State) -> Result<(), Error> {
510 self.attempts
511 .pick(self.out, PickInput::Recorded(&buffer), state)
512 }
513
514 fn expecting(&self) -> Cow<'_, str> {
515 (self.expecting)()
516 }
517}
518
519macro_rules! pick_first_impls {
520 ($(($first:ident $(, $adapter:ident)+);)*) => {
521 $(
522 impl<'de, T: Send, $first: Deserialize<'de, T>, $($adapter: Deserialize<'de, T>),+>
523 Deserialize<'de, T> for PickFirst<($first, $($adapter),+)>
524 {
525 fn deserialize_into<'out>(
526 out: &'out mut Option<T>,
527 state: &mut State,
528 ) -> SinkHandle<'out, 'de> {
529 RecordBuf::capture_with(
530 PickCapture {
531 out,
532 attempts: pick_first_impls!(@attempts $first $(, $adapter)+),
533 expecting: <Self as Deserialize<'de, T>>::expecting,
534 },
535 state,
536 )
537 }
538
539 fn expecting() -> Cow<'static, str> {
540 let mut rv = String::from($first::expecting());
541 $(
542 rv.push_str(" or ");
543 rv.push_str(&$adapter::expecting());
544 )+
545 Cow::Owned(rv)
546 }
547
548 fn initial_value() -> Option<T> {
549 $first::initial_value()
550 }
551
552 #[inline]
553 fn __private_atom_into(
554 out: &mut Option<T>,
555 atom: Atom,
556 state: &mut State,
557 ) -> Result<(), Error> {
558 pick_first_impls!(@attempts $first $(, $adapter)+)
559 .pick(out, PickInput::Atom(atom), state)
560 }
561
562 #[inline]
563 fn __private_borrowed_atom_into(
564 out: &mut Option<T>,
565 atom: Atom<'de>,
566 state: &mut State,
567 ) -> Result<(), Error> {
568 pick_first_impls!(@attempts $first $(, $adapter)+)
569 .pick(out, PickInput::Borrowed(atom), state)
570 }
571 }
572
573 impl<T: ?Sized, $first: Serialize<T>, $($adapter),+> Serialize<T>
574 for PickFirst<($first, $($adapter),+)>
575 {
576 fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
577 $first::serialize(value, state)
578 }
579
580 fn finish(value: &T, state: &mut State) -> Result<(), Error> {
581 $first::finish(value, state)
582 }
583
584 fn is_optional(value: &T) -> bool {
585 $first::is_optional(value)
586 }
587
588 fn container_shape(value: &T) -> ContainerShape {
589 $first::container_shape(value)
590 }
591
592 fn describe(value: &T, d: &mut dyn crate::ser::Describe) {
593 $first::describe(value, d)
594 }
595
596 #[inline]
597 fn __private_begin<'a>(
598 value: &'a T,
599 state: &mut State,
600 ) -> Result<crate::ser::Begin<'a>, Error> {
601 $first::__private_begin(value, state)
602 }
603
604 fn __private_slice_as_bytes(val: &[T]) -> Option<Cow<'_, [u8]>>
605 where
606 T: Sized,
607 {
608 $first::__private_slice_as_bytes(val)
609 }
610 }
611 )*
612 };
613 (@attempts $($adapter:ident),+) => {
614 Attempts::new(&[$(pick_attempt::<T, $adapter> as Attempt<'de, T>),+])
615 };
616}
617
618pick_first_impls! {
619 (A1, A2);
620 (A1, A2, A3);
621 (A1, A2, A3, A4);
622}
623
624#[cfg_attr(
656 not(feature = "std"),
657 doc = "[`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html"
658)]
659pub struct MapAsPairs<KA = Same, VA = Same>(PhantomData<fn() -> (KA, VA)>);
660
661pub struct PairsAsMap<KA = Same, VA = Same>(PhantomData<fn() -> (KA, VA)>);
691
692enum MapAsPairsSink<'a, 'de, M, K, V> {
694 Pending(&'a mut Option<M>),
695 Map(SinkHandle<'a, 'de>),
697 Pairs(PairsSink<'a, M, K, V>),
699}
700
701struct PairsSink<'a, M, K, V> {
703 out: &'a mut Option<M>,
704 map: M,
705 pair: Option<(K, V)>,
706 duplicate_keys: DuplicateKeys,
707 errors: CollectedErrors,
708}
709
710impl<'a, M: MapTarget<K, V>, K, V> PairsSink<'a, M, K, V> {
711 fn flush(&mut self, state: &mut State) -> Result<(), Error> {
716 if let Some((key, value)) = self.pair.take() {
717 let replace = self.duplicate_keys != DuplicateKeys::First;
718 if self.map.insert_entry(key, value, replace)
719 && let Err(err) = self
720 .duplicate_keys
721 .resolve(|| "duplicate key in map".into())
722 {
723 return self.errors.collect(err, state);
724 }
725 }
726 Ok(())
727 }
728}
729
730impl<'a, 'de, M, K, V> MapAsPairsSink<'a, 'de, M, K, V>
731where
732 M: MapTarget<K, V>,
733 K: Send + 'a,
734 V: Send + 'a,
735{
736 fn map_sink<KA, VA>(&mut self, state: &mut State) -> Result<&mut SinkHandle<'a, 'de>, Error>
738 where
739 KA: Deserialize<'de, K>,
740 VA: Deserialize<'de, V>,
741 {
742 if let MapAsPairsSink::Pending(..) = self
743 && let MapAsPairsSink::Pending(out) =
744 core::mem::replace(self, MapAsPairsSink::Map(SinkHandle::null()))
745 {
746 *self = MapAsPairsSink::Map(map_sink::<M, K, V, KA, VA>(MapOut::Slot(out), state));
747 }
748 match self {
749 MapAsPairsSink::Map(sink) => Ok(sink),
750 _ => Err(Error::new(
751 ErrorKind::InvalidState,
752 "the value is not a map",
753 )),
754 }
755 }
756}
757
758impl<'a, 'de, M, K, V, KA, VA> Sink<'de> for Adapted<(KA, VA), MapAsPairsSink<'a, 'de, M, K, V>>
759where
760 M: MapTarget<K, V>,
761 K: Send + 'a,
762 V: Send + 'a,
763 KA: Deserialize<'de, K>,
764 VA: Deserialize<'de, V>,
765{
766 fn expecting(&self) -> Cow<'_, str> {
767 Cow::Borrowed(M::NAME)
768 }
769
770 fn map(&mut self, state: &mut State) -> Result<(), Error> {
771 self.map_sink::<KA, VA>(state)?.map(state)
772 }
773
774 fn seq(&mut self, state: &mut State) -> Result<(), Error> {
775 if let MapAsPairsSink::Pending(..) = **self
776 && let MapAsPairsSink::Pending(out) =
777 core::mem::replace(&mut **self, MapAsPairsSink::Map(SinkHandle::null()))
778 {
779 let mut map = M::default();
780 map.reserve_entries(state.container_shape().cautious_capacity::<(K, V)>());
781 **self = MapAsPairsSink::Pairs(PairsSink {
782 out,
783 map,
784 pair: None,
785 duplicate_keys: DuplicateKeys::of(state),
786 errors: CollectedErrors::new(),
787 });
788 return Ok(());
789 }
790 match **self {
791 MapAsPairsSink::Map(ref mut sink) => sink.seq(state),
792 _ => default_container_error(self, state),
793 }
794 }
795
796 fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
797 match **self {
798 MapAsPairsSink::Map(ref mut sink) => sink.next_key(state),
799 _ => Ok(SinkHandle::null()),
800 }
801 }
802
803 fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
804 match **self {
805 MapAsPairsSink::Map(ref mut sink) => sink.next_value(state),
806 MapAsPairsSink::Pairs(ref mut pairs) => {
807 pairs.flush(state)?;
808 Ok(<(KA, VA) as Deserialize<'de, (K, V)>>::deserialize_into(
809 &mut pairs.pair,
810 state,
811 ))
812 }
813 MapAsPairsSink::Pending(..) => Ok(SinkHandle::null()),
814 }
815 }
816
817 fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
818 match **self {
819 MapAsPairsSink::Map(ref mut sink) => sink.__private_key_atom(atom, state),
820 _ => crate::de::atom_into_handle(self.next_key(state)?, atom, state),
821 }
822 }
823
824 fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
825 match **self {
826 MapAsPairsSink::Map(ref mut sink) => sink.__private_value_atom(atom, state),
827 _ => crate::de::atom_into_handle(self.next_value(state)?, atom, state),
828 }
829 }
830
831 fn __private_borrowed_key_atom(
832 &mut self,
833 atom: Atom<'de>,
834 state: &mut State,
835 ) -> Result<(), Error> {
836 match **self {
837 MapAsPairsSink::Map(ref mut sink) => sink.__private_borrowed_key_atom(atom, state),
838 _ => crate::de::borrowed_atom_into_handle(self.next_key(state)?, atom, state),
839 }
840 }
841
842 fn __private_borrowed_value_atom(
843 &mut self,
844 atom: Atom<'de>,
845 state: &mut State,
846 ) -> Result<(), Error> {
847 match **self {
848 MapAsPairsSink::Map(ref mut sink) => sink.__private_borrowed_value_atom(atom, state),
849 _ => crate::de::borrowed_atom_into_handle(self.next_value(state)?, atom, state),
850 }
851 }
852
853 fn value_for_key(
855 &mut self,
856 key: &str,
857 state: &mut State,
858 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
859 if let MapAsPairsSink::Pairs(..) = **self {
860 return Ok(None);
861 }
862 self.map_sink::<KA, VA>(state)?.value_for_key(key, state)
863 }
864
865 fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
866 match **self {
867 MapAsPairsSink::Map(ref mut sink) => sink.recover(err, state),
868 MapAsPairsSink::Pairs(ref mut pairs) => {
869 pairs.pair = None;
870 pairs.errors.collect(err, state)
871 }
872 MapAsPairsSink::Pending(..) => Err(err),
873 }
874 }
875
876 fn finish(&mut self, state: &mut State) -> Result<(), Error> {
877 match **self {
878 MapAsPairsSink::Map(ref mut sink) => sink.finish(state),
879 MapAsPairsSink::Pairs(ref mut pairs) => {
880 pairs.flush(state)?;
881 pairs.errors.finish()?;
882 *pairs.out = Some(take(&mut pairs.map));
883 Ok(())
884 }
885 MapAsPairsSink::Pending(..) => self.map_sink::<KA, VA>(state)?.finish(state),
887 }
888 }
889}
890
891#[cold]
894fn default_container_error(sink: &mut dyn Sink<'_>, state: &State) -> Result<(), Error> {
895 crate::de::atoms::default_container(sink, "sequence", state)
896}
897
898macro_rules! map_as_pairs_impls {
900 ($([$($bound:tt)*] [$($ser_bound:tt)*] $target:ty, $order:ident;)*) => {
901 $(
902 impl<'de, $($bound)*, KA: Deserialize<'de, K>, VA: Deserialize<'de, V>>
903 Deserialize<'de, $target> for MapAsPairs<KA, VA>
904 {
905 fn deserialize_into<'out>(
906 out: &'out mut Option<$target>,
907 state: &mut State,
908 ) -> SinkHandle<'out, 'de> {
909 adapted::arena_sink::<(KA, VA), _>(
910 MapAsPairsSink::<_, K, V>::Pending(out),
911 state,
912 )
913 }
914
915 fn expecting() -> Cow<'static, str> {
916 Cow::Borrowed(<$target as MapTarget<K, V>>::NAME)
917 }
918 }
919
920 impl<$($ser_bound)*, KA: Serialize<K>, VA: Serialize<V>> Serialize<$target>
921 for MapAsPairs<KA, VA>
922 {
923 fn serialize<'a>(
924 value: &'a $target,
925 state: &mut State,
926 ) -> Result<Emit<'a>, Error> {
927 Ok(adapted::seq_emitter::<(KA, VA), _>(
928 PairsEmitter {
929 iter: value.iter(),
930 current: None,
931 },
932 state,
933 ))
934 }
935
936 fn container_shape(value: &$target) -> ContainerShape {
937 let mut shape = ContainerShape::with_order(Order::$order);
938 shape.set_len(value.len());
939 shape
940 }
941 }
942 )*
943 };
944}
945
946map_as_pairs_impls! {
947 [K: Ord + Send, V: Send] [K: Sync, V: Sync] BTreeMap<K, V>, Sorted;
948}
949
950#[cfg(feature = "std")]
951map_as_pairs_impls! {
952 [K: Hash + Eq + Send, V: Send, H: BuildHasher + Default + Send]
953 [K: Sync, V: Sync, H: BuildHasher + Sync]
954 HashMap<K, V, H>, Arbitrary;
955}
956
957struct PairsEmitter<'a, I, K, V> {
959 iter: I,
960 current: Option<(&'a K, &'a V)>,
962}
963
964impl<'a, I, K, V, KA, VA> SeqEmitter for Adapted<(KA, VA), PairsEmitter<'a, I, K, V>>
965where
966 I: Iterator<Item = (&'a K, &'a V)> + Send,
967 K: Sync + 'a,
968 V: Sync + 'a,
969 KA: Serialize<K>,
970 VA: Serialize<V>,
971{
972 fn next(&mut self, _state: &mut State) -> Result<Option<SerializeHandle<'_>>, Error> {
973 let this = &mut **self;
974 this.current = this.iter.next();
975 Ok(this
976 .current
977 .as_ref()
978 .map(handle_as::<Pair<KA, VA>, (&'a K, &'a V)>))
979 }
980}
981
982struct Pair<KA, VA>(PhantomData<fn() -> (KA, VA)>);
984
985impl<'r, K, V, KA, VA> Serialize<(&'r K, &'r V)> for Pair<KA, VA>
986where
987 K: Sync,
988 V: Sync,
989 KA: Serialize<K>,
990 VA: Serialize<V>,
991{
992 fn serialize<'a>(value: &'a (&'r K, &'r V), state: &mut State) -> Result<Emit<'a>, Error> {
993 let seq = Adapted::<Self, _>::indexed(value);
994 Ok(Emit::seq(IndexedSeqEmitter::new(seq), state))
995 }
996
997 fn container_shape(_value: &(&'r K, &'r V)) -> ContainerShape {
998 ContainerShape::with_len(2)
999 }
1000}
1001
1002impl<'r, K, V, KA, VA> IndexedSeq for Adapted<Pair<KA, VA>, (&'r K, &'r V)>
1003where
1004 K: Sync,
1005 V: Sync,
1006 KA: Serialize<K>,
1007 VA: Serialize<V>,
1008{
1009 fn element(
1010 &self,
1011 index: usize,
1012 _state: &mut State,
1013 ) -> Result<Option<SerializeHandle<'_>>, Error> {
1014 let (key, value) = *self.get();
1015 Ok(match index {
1016 0 => Some(handle_as::<KA, K>(key)),
1017 1 => Some(handle_as::<VA, V>(value)),
1018 _ => None,
1019 })
1020 }
1021}
1022
1023enum PairsAsMapSink<'a, 'de, K, V> {
1025 Pending(&'a mut Option<Vec<(K, V)>>),
1026 Seq(SinkHandle<'a, 'de>),
1028 Map(EntriesSink<'a, K, V>),
1030}
1031
1032struct EntriesSink<'a, K, V> {
1034 out: &'a mut Option<Vec<(K, V)>>,
1035 entries: Vec<(K, V)>,
1036 key: Option<K>,
1037 value: Option<V>,
1038 errors: CollectedErrors,
1039}
1040
1041impl<'a, K, V> EntriesSink<'a, K, V> {
1042 fn flush(&mut self) {
1044 if let (Some(key), Some(value)) = (self.key.take(), self.value.take()) {
1045 self.entries.push((key, value));
1046 }
1047 }
1048}
1049
1050impl<'a, 'de, K: Send, V: Send> PairsAsMapSink<'a, 'de, K, V> {
1051 fn seq_sink<KA, VA>(&mut self, state: &mut State) -> Option<&mut SinkHandle<'a, 'de>>
1054 where
1055 KA: Deserialize<'de, K>,
1056 VA: Deserialize<'de, V>,
1057 {
1058 if let PairsAsMapSink::Pending(..) = self
1059 && let PairsAsMapSink::Pending(out) =
1060 core::mem::replace(self, PairsAsMapSink::Seq(SinkHandle::null()))
1061 {
1062 *self = PairsAsMapSink::Seq(
1063 <Vec<(KA, VA)> as Deserialize<'de, Vec<(K, V)>>>::deserialize_into(out, state),
1064 );
1065 }
1066 match self {
1067 PairsAsMapSink::Seq(sink) => Some(sink),
1068 _ => None,
1069 }
1070 }
1071
1072 fn entries(&mut self) -> Option<&mut EntriesSink<'a, K, V>> {
1074 if let PairsAsMapSink::Pending(..) = self
1075 && let PairsAsMapSink::Pending(out) =
1076 core::mem::replace(self, PairsAsMapSink::Seq(SinkHandle::null()))
1077 {
1078 *self = PairsAsMapSink::Map(EntriesSink {
1079 out,
1080 entries: Vec::new(),
1081 key: None,
1082 value: None,
1083 errors: CollectedErrors::new(),
1084 });
1085 }
1086 match self {
1087 PairsAsMapSink::Map(entries) => Some(entries),
1088 _ => None,
1089 }
1090 }
1091}
1092
1093impl<'a, 'de, K, V, KA, VA> Sink<'de> for Adapted<(KA, VA), PairsAsMapSink<'a, 'de, K, V>>
1094where
1095 K: Send,
1096 V: Send,
1097 KA: Deserialize<'de, K>,
1098 VA: Deserialize<'de, V>,
1099{
1100 fn expecting(&self) -> Cow<'_, str> {
1101 Cow::Borrowed("map")
1102 }
1103
1104 fn map(&mut self, state: &mut State) -> Result<(), Error> {
1105 let capacity = state.container_shape().cautious_capacity::<(K, V)>();
1106 if let Some(entries) = self.entries() {
1107 entries.entries.reserve(capacity);
1108 return Ok(());
1109 }
1110 crate::de::atoms::default_container(self, "map", state)
1111 }
1112
1113 fn seq(&mut self, state: &mut State) -> Result<(), Error> {
1114 match self.seq_sink::<KA, VA>(state) {
1115 Some(sink) => sink.seq(state),
1116 None => default_container_error(self, state),
1117 }
1118 }
1119
1120 fn __private_seq(&mut self, state: &mut State) -> Result<bool, Error> {
1121 match self.seq_sink::<KA, VA>(state) {
1123 Some(sink) => sink.__private_seq(state),
1124 None => default_container_error(self, state).map(|()| false),
1125 }
1126 }
1127
1128 fn __private_inline_atom(
1129 &mut self,
1130 index: usize,
1131 atom: Atom,
1132 state: &mut State,
1133 ) -> Result<(), Error> {
1134 match **self {
1135 PairsAsMapSink::Seq(ref mut sink) => sink.__private_inline_atom(index, atom, state),
1136 _ => unreachable!(),
1137 }
1138 }
1139
1140 fn __private_inline_event(
1141 &mut self,
1142 event: crate::de::InlineEvent,
1143 state: &mut State,
1144 ) -> Result<(), Error> {
1145 match **self {
1146 PairsAsMapSink::Seq(ref mut sink) => sink.__private_inline_event(event, state),
1147 _ => unreachable!(),
1148 }
1149 }
1150
1151 fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1152 match **self {
1153 PairsAsMapSink::Map(ref mut entries) => {
1154 entries.flush();
1155 Ok(KA::deserialize_into(&mut entries.key, state))
1156 }
1157 PairsAsMapSink::Seq(ref mut sink) => sink.next_key(state),
1158 PairsAsMapSink::Pending(..) => Ok(SinkHandle::null()),
1159 }
1160 }
1161
1162 fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
1163 match **self {
1164 PairsAsMapSink::Map(ref mut entries) => {
1165 Ok(VA::deserialize_into(&mut entries.value, state))
1166 }
1167 PairsAsMapSink::Seq(ref mut sink) => sink.next_value(state),
1168 PairsAsMapSink::Pending(..) => Ok(SinkHandle::null()),
1169 }
1170 }
1171
1172 fn __private_key_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1173 match **self {
1174 PairsAsMapSink::Map(ref mut entries) => {
1175 entries.flush();
1176 KA::__private_atom_into(&mut entries.key, atom, state)
1177 }
1178 _ => crate::de::atom_into_handle(self.next_key(state)?, atom, state),
1179 }
1180 }
1181
1182 fn __private_value_atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
1183 match **self {
1184 PairsAsMapSink::Map(ref mut entries) => {
1185 VA::__private_atom_into(&mut entries.value, atom, state)
1186 }
1187 PairsAsMapSink::Seq(ref mut sink) => sink.__private_value_atom(atom, state),
1188 PairsAsMapSink::Pending(..) => Ok(()),
1189 }
1190 }
1191
1192 fn __private_borrowed_key_atom(
1193 &mut self,
1194 atom: Atom<'de>,
1195 state: &mut State,
1196 ) -> Result<(), Error> {
1197 match **self {
1198 PairsAsMapSink::Map(ref mut entries) => {
1199 entries.flush();
1200 KA::__private_borrowed_atom_into(&mut entries.key, atom, state)
1201 }
1202 _ => crate::de::borrowed_atom_into_handle(self.next_key(state)?, atom, state),
1203 }
1204 }
1205
1206 fn __private_borrowed_value_atom(
1207 &mut self,
1208 atom: Atom<'de>,
1209 state: &mut State,
1210 ) -> Result<(), Error> {
1211 match **self {
1212 PairsAsMapSink::Map(ref mut entries) => {
1213 VA::__private_borrowed_atom_into(&mut entries.value, atom, state)
1214 }
1215 PairsAsMapSink::Seq(ref mut sink) => sink.__private_borrowed_value_atom(atom, state),
1216 PairsAsMapSink::Pending(..) => Ok(()),
1217 }
1218 }
1219
1220 fn value_for_key(
1223 &mut self,
1224 key: &str,
1225 state: &mut State,
1226 ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
1227 let Some(entries) = self.entries() else {
1228 return Ok(None);
1229 };
1230 entries.flush();
1231 KA::__private_atom_into(&mut entries.key, Atom::Lexical(Text::borrowed(key)), state)?;
1232 Ok(Some(VA::deserialize_into(&mut entries.value, state)))
1233 }
1234
1235 fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
1236 match **self {
1237 PairsAsMapSink::Map(ref mut entries) => {
1238 entries.key = None;
1239 entries.value = None;
1240 entries.errors.collect(err, state)
1241 }
1242 PairsAsMapSink::Seq(ref mut sink) => sink.recover(err, state),
1243 PairsAsMapSink::Pending(..) => Err(err),
1244 }
1245 }
1246
1247 fn finish(&mut self, state: &mut State) -> Result<(), Error> {
1248 let _ = self.entries();
1250 match **self {
1251 PairsAsMapSink::Map(ref mut entries) => {
1252 entries.flush();
1253 entries.errors.finish()?;
1254 *entries.out = Some(take(&mut entries.entries));
1255 Ok(())
1256 }
1257 PairsAsMapSink::Seq(ref mut sink) => sink.finish(state),
1258 PairsAsMapSink::Pending(..) => Ok(()),
1259 }
1260 }
1261}
1262
1263impl<'de, K, V, KA, VA> Deserialize<'de, Vec<(K, V)>> for PairsAsMap<KA, VA>
1264where
1265 K: Send,
1266 V: Send,
1267 KA: Deserialize<'de, K>,
1268 VA: Deserialize<'de, V>,
1269{
1270 fn deserialize_into<'out>(
1271 out: &'out mut Option<Vec<(K, V)>>,
1272 state: &mut State,
1273 ) -> SinkHandle<'out, 'de> {
1274 adapted::arena_sink::<(KA, VA), _>(PairsAsMapSink::Pending(out), state)
1275 }
1276
1277 fn expecting() -> Cow<'static, str> {
1278 Cow::Borrowed("map")
1279 }
1280}
1281
1282impl<K, V, KA, VA> Serialize<Vec<(K, V)>> for PairsAsMap<KA, VA>
1283where
1284 K: Sync,
1285 V: Sync,
1286 KA: Serialize<K>,
1287 VA: Serialize<V>,
1288{
1289 fn serialize<'a>(value: &'a Vec<(K, V)>, state: &mut State) -> Result<Emit<'a>, Error> {
1290 Ok(MapIterEmitter::emit::<K, KA, VA>(
1291 value.iter().map(split_pair as fn(&(K, V)) -> (&K, &V)),
1292 state,
1293 ))
1294 }
1295
1296 fn container_shape(value: &Vec<(K, V)>) -> ContainerShape {
1297 let mut shape = ContainerShape::with_order(Order::Significant);
1298 shape.set_len(value.len());
1299 shape
1300 }
1301}
1302
1303fn split_pair<K, V>(pair: &(K, V)) -> (&K, &V) {
1305 (&pair.0, &pair.1)
1306}