Skip to main content

deser_core/ser/
impls.rs

1//! `Serialize` for the standard types.
2//!
3//! The containers are generic over the adapters of their values (see
4//! `crate::adapters`), the container of `T` itself is the adapter with
5//! `A = T`.
6use alloc::borrow::Cow;
7use alloc::borrow::ToOwned;
8use alloc::boxed::Box;
9use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
10use alloc::string::String;
11use alloc::sync::Arc;
12use alloc::vec::Vec;
13#[cfg(feature = "std")]
14use core::hash::BuildHasher;
15use core::marker::PhantomData;
16#[cfg(feature = "std")]
17use std::collections::{HashMap, HashSet};
18
19use crate::State;
20use crate::Text;
21use crate::adapted;
22use crate::error::Error;
23use crate::event::{Atom, Bytes, ContainerShape};
24use crate::ext::ExtValue;
25use crate::ser::{
26    Adapted, Begin, Describe, Emit, IndexedSeq, MapEmitter, PlainSink, SeqEmitter, Serialize,
27    SerializeHandle, SerializeRef, atom_cost, plain_atom,
28};
29
30impl Serialize for bool {
31    begin_without_finish!();
32    plain_atom!(|v| Atom::Bool(*v));
33
34    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
35        Ok(Emit::Atom(Atom::Bool(*value)))
36    }
37}
38
39impl Serialize for () {
40    begin_without_finish!();
41    plain_atom!(|_v| Atom::Null);
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 Serialize for u8 {
53    begin_without_finish!();
54    plain_atom!(|v| Atom::U64(u64::from(*v)));
55
56    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
57        Ok(Emit::Atom(Atom::U64(*value as u64)))
58    }
59
60    fn __private_slice_as_bytes(val: &[u8]) -> Option<Cow<'_, [u8]>> {
61        Some(Cow::Borrowed(val))
62    }
63}
64
65impl Serialize for char {
66    begin_without_finish!();
67    plain_atom!(|v| Atom::Char(*v));
68
69    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
70        Ok(Emit::Atom(Atom::Char(*value)))
71    }
72}
73
74macro_rules! serialize_int {
75    ($ty:ty, $atom:ident) => {
76        impl Serialize for $ty {
77            begin_without_finish!();
78            plain_atom!(|v| Atom::$atom(*v as _));
79
80            fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
81                Ok(Emit::Atom(Atom::$atom(*value as _)))
82            }
83        }
84    };
85}
86
87serialize_int!(u16, U64);
88serialize_int!(u32, U64);
89serialize_int!(u64, U64);
90serialize_int!(i8, I64);
91serialize_int!(i16, I64);
92serialize_int!(i32, I64);
93serialize_int!(i64, I64);
94serialize_int!(isize, I64);
95serialize_int!(usize, U64);
96
97impl Serialize for f32 {
98    begin_without_finish!();
99    plain_atom!(|v| Atom::F32(*v));
100
101    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
102        Ok(Emit::Atom(Atom::F32(*value)))
103    }
104}
105
106impl Serialize for f64 {
107    begin_without_finish!();
108    plain_atom!(|v| Atom::F64(*v));
109
110    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
111        Ok(Emit::Atom(Atom::F64(*value)))
112    }
113}
114
115macro_rules! serialize_ext_int {
116    ($ty:ty) => {
117        impl Serialize for $ty {
118            begin_without_finish!();
119            plain_atom!(|v| Atom::Ext(ExtValue::borrowed(v)));
120
121            fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
122                Ok(Emit::Atom(Atom::Ext(ExtValue::borrowed(value))))
123            }
124        }
125    };
126}
127
128serialize_ext_int!(u128);
129serialize_ext_int!(i128);
130
131impl Serialize for String {
132    begin_without_finish!();
133    plain_atom!(|v| Atom::Str(Text::borrowed(v.as_str())));
134
135    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
136        Ok(Emit::Atom(Atom::Str(value.as_str().into())))
137    }
138}
139
140impl Serialize for str {
141    begin_without_finish!();
142
143    fn serialize<'a>(value: &'a Self, _state: &mut State) -> Result<Emit<'a>, Error> {
144        Ok(Emit::Atom(Atom::Str(Text::borrowed(value))))
145    }
146}
147
148/// `Cow<[T]>` is implemented separately as slices are serialized by the
149/// containers holding them (see `serialize_slice`).
150impl<'a, T> Serialize for Cow<'a, T>
151where
152    T: Serialize + ToOwned + ?Sized,
153    T::Owned: Sync,
154{
155    fn serialize<'b>(value: &'b Self, state: &mut State) -> Result<Emit<'b>, Error> {
156        T::serialize(value, state)
157    }
158
159    fn finish(value: &Self, state: &mut State) -> Result<(), Error> {
160        T::finish(value, state)
161    }
162
163    #[inline]
164    fn __private_begin<'b>(value: &'b Self, state: &mut State) -> Result<Begin<'b>, Error> {
165        T::__private_begin(value, state)
166    }
167
168    fn is_optional(value: &Self) -> bool {
169        T::is_optional(value)
170    }
171
172    fn container_shape(value: &Self) -> ContainerShape {
173        T::container_shape(value)
174    }
175
176    fn describe(value: &Self, d: &mut dyn Describe) {
177        T::describe(value, d)
178    }
179}
180
181/// Returns a handle to a value that serializes with an adapter.
182#[inline(always)]
183pub(crate) fn handle_as<A: Serialize<T>, T: Sync>(value: &T) -> SerializeHandle<'_> {
184    SerializeHandle::from(SerializeRef::serialize_as::<A, T>(value))
185}
186
187/// Emits the elements of an iterator with an adapter.
188pub(crate) struct IterEmitter<'a, I>(I, PhantomData<&'a ()>);
189
190impl<'a, I> IterEmitter<'a, I> {
191    /// Emits a sequence of the elements with the adapter `A`.
192    ///
193    /// The adapter does not need to outlive the `Emit` (see
194    /// [`adapted`](crate::adapted)).
195    #[inline(always)]
196    pub(crate) fn emit<A, T>(iter: I, state: &mut State) -> Emit<'a>
197    where
198        I: Iterator<Item = &'a T> + Send + 'a,
199        T: Sync + 'a,
200        A: Serialize<T>,
201    {
202        adapted::seq_emitter::<A, _>(IterEmitter(iter, PhantomData), state)
203    }
204}
205
206impl<'a, I, T, A> SeqEmitter for Adapted<A, IterEmitter<'a, I>>
207where
208    I: Iterator<Item = &'a T> + Send,
209    T: Sync + 'a,
210    A: Serialize<T>,
211{
212    fn next(&mut self, _state: &mut State) -> Result<Option<SerializeHandle<'_>>, Error> {
213        Ok(self.0.next().map(handle_as::<A, T>))
214    }
215}
216
217/// Emits the entries of a map iterator with adapters.
218pub(crate) struct MapIterEmitter<'a, I, V> {
219    iter: I,
220    value: Option<&'a V>,
221}
222
223impl<'a, I, V> MapIterEmitter<'a, I, V> {
224    /// Emits a map of the entries with the adapters `KA` and `VA`.
225    ///
226    /// The adapters do not need to outlive the `Emit` (see
227    /// [`adapted`](crate::adapted)).
228    #[inline(always)]
229    pub(crate) fn emit<K, KA, VA>(iter: I, state: &mut State) -> Emit<'a>
230    where
231        I: Iterator<Item = (&'a K, &'a V)> + Send + 'a,
232        K: Sync + 'a,
233        V: Sync + 'a,
234        KA: Serialize<K>,
235        VA: Serialize<V>,
236    {
237        let emitter = MapIterEmitter { iter, value: None };
238        adapted::map_emitter::<(KA, VA), _>(emitter, state)
239    }
240}
241
242impl<'a, I, K, V, KA, VA> MapEmitter for Adapted<(KA, VA), MapIterEmitter<'a, I, V>>
243where
244    I: Iterator<Item = (&'a K, &'a V)> + Send,
245    K: Sync + 'a,
246    V: Sync + 'a,
247    KA: Serialize<K>,
248    VA: Serialize<V>,
249{
250    fn next_key(&mut self, _state: &mut State) -> Result<Option<SerializeHandle<'_>>, Error> {
251        let this = &mut **self;
252        Ok(this.iter.next().map(|(k, v)| {
253            this.value = Some(v);
254            handle_as::<KA, K>(k)
255        }))
256    }
257
258    fn next_value(&mut self, _state: &mut State) -> Result<SerializeHandle<'_>, Error> {
259        Ok(handle_as::<VA, V>(self.value.unwrap()))
260    }
261}
262
263/// Begins a sequence which provides its elements by index (see
264/// [`Adapted`]).
265///
266/// The adapter does not need to outlive the value (see
267/// [`adapted`](crate::adapted)).
268#[inline(always)]
269pub(crate) fn begin_indexed<'a, A, T>(value: &'a T, shape: ContainerShape) -> Begin<'a>
270where
271    Adapted<A, T>: IndexedSeq,
272{
273    Begin::indexed_seq(Adapted::<A, T>::indexed(value), shape)
274}
275
276/// Begins a plain value with an adapter (see [`Begin::plain`]).
277#[inline(always)]
278pub(crate) fn begin_plain<'a, A: Serialize<T>, T: Sync>(
279    value: &'a T,
280    shape: ContainerShape,
281) -> Begin<'a> {
282    Begin::plain(SerializeRef::serialize_as::<A, T>(value), shape)
283}
284
285/// Implements `Serialize` for the containers of slices, generic over the
286/// adapter of the elements.
287///
288/// `[T]` itself does not implement `Serialize` as the containers provide
289/// the elements by index which requires a sized value.  The containers
290/// need to support `len` and indexing with `[..]`.  The entries are
291/// `[generics] Container<T> => Container<A>, A;` where the last part is the
292/// adapter of the elements.
293macro_rules! serialize_slice {
294    ($([$($gen:tt)*] $ty:ty => $adapter:ty, $elem:ty;)*) => {
295        $(
296            impl<$($gen)*> $crate::ser::Serialize<$ty> for $adapter {
297                #[inline]
298                fn __private_begin<'a>(
299                    value: &'a $ty,
300                    _state: &mut $crate::State,
301                ) -> Result<$crate::ser::Begin<'a>, $crate::Error> {
302                    Ok(match <$elem as $crate::ser::Serialize<T>>::__private_slice_as_bytes(&value[..]) {
303                        Some(bytes) => $crate::ser::Begin::emit(
304                            $crate::ser::Emit::Atom($crate::Atom::Bytes($crate::Bytes::new(bytes))),
305                            $crate::ContainerShape::new(),
306                            false,
307                        ),
308                        None => $crate::ser::impls::begin_indexed::<$adapter, $ty>(
309                            value,
310                            Self::container_shape(value),
311                        ),
312                    })
313                }
314
315                fn container_shape(value: &$ty) -> $crate::ContainerShape {
316                    $crate::ContainerShape::with_len(value.len())
317                }
318
319                fn serialize<'a>(
320                    value: &'a $ty,
321                    state: &mut $crate::State,
322                ) -> Result<$crate::ser::Emit<'a>, $crate::Error> {
323                    Ok(match <$elem as $crate::ser::Serialize<T>>::__private_slice_as_bytes(&value[..]) {
324                        Some(bytes) => {
325                            $crate::ser::Emit::Atom($crate::Atom::Bytes($crate::Bytes::new(bytes)))
326                        }
327                        None => $crate::ser::impls::IterEmitter::emit::<$elem, _>(value[..].iter(), state),
328                    })
329                }
330
331                #[inline]
332                fn __private_is_plain() -> bool {
333                    <$elem as $crate::ser::Serialize<T>>::__private_is_plain()
334                }
335
336                #[inline]
337                fn __private_is_plain_value(value: &$ty) -> bool {
338                    <$elem as $crate::ser::Serialize<T>>::__private_is_plain() || value.is_empty()
339                }
340
341                fn __private_emit_plain(
342                    value: &$ty,
343                    sink: &mut dyn $crate::ser::PlainSink,
344                ) -> Result<(), $crate::Error> {
345                    $crate::ser::impls::emit_plain_slice::<T, $elem>(
346                        &value[..],
347                        Self::container_shape(value),
348                        sink,
349                    )
350                }
351
352                #[inline]
353                fn __private_plain_cost(value: &$ty, budget: usize) -> Option<usize> {
354                    $crate::ser::impls::plain_cost_slice::<T, $elem>(&value[..], budget)
355                }
356            }
357
358            impl<$($gen)*> $crate::ser::IndexedSeq for $crate::ser::Adapted<$adapter, $ty> {
359                #[inline]
360                fn element(
361                    &self,
362                    index: usize,
363                    _state: &mut $crate::State,
364                ) -> Result<Option<$crate::ser::SerializeHandle<'_>>, $crate::Error> {
365                    Ok(self.get()[..]
366                        .get(index)
367                        .map($crate::ser::impls::handle_as::<$elem, T>))
368                }
369
370                fn emit_plain(
371                    &self,
372                    sink: &mut dyn $crate::ser::PlainSink,
373                ) -> Result<bool, $crate::Error> {
374                    $crate::ser::impls::emit_plain_elements::<T, $elem>(self.get()[..].iter(), sink)
375                }
376
377                fn emit_plain_chunk(
378                    &self,
379                    index: usize,
380                    budget: usize,
381                    sink: &mut dyn $crate::ser::PlainSink,
382                ) -> Result<usize, $crate::Error> {
383                    $crate::ser::impls::emit_plain_chunk::<T, $elem>(
384                        self.get()[..].get(index..).unwrap_or_default().iter(),
385                        index,
386                        budget,
387                        sink,
388                    )
389                }
390            }
391        )*
392    };
393}
394
395// also used for the containers of other crates
396#[allow(unused_imports)]
397pub(crate) use serialize_slice;
398
399serialize_slice! {
400    [T: Sync, A: Serialize<T>] Vec<T> => Vec<A>, A;
401    ['r, 's, T: Sync, A: Serialize<T>] &'r [T] => &'s [A], A;
402    [T: Sync, A: Serialize<T>] Box<[T]> => Box<[A]>, A;
403    [T: Send + Sync, A: Serialize<T> + Send] Arc<[T]> => Arc<[A]>, A;
404    ['r, T: Serialize + Clone] Cow<'r, [T]> => Cow<'r, [T]>, T;
405}
406
407/// Emits a slice of plain values, as bytes or as sequence.
408#[inline]
409pub(crate) fn emit_plain_slice<T, A: Serialize<T>>(
410    slice: &[T],
411    shape: ContainerShape,
412    sink: &mut dyn PlainSink,
413) -> Result<(), Error> {
414    match A::__private_slice_as_bytes(slice) {
415        Some(bytes) => sink.atom(Atom::Bytes(Bytes::new(bytes))),
416        None => {
417            sink.seq_start(shape)?;
418            for value in slice {
419                A::__private_emit_plain(value, sink)?;
420            }
421            sink.seq_end()
422        }
423    }
424}
425
426/// Emits the elements of a sequence if they are plain (or if there are
427/// none).
428#[inline]
429pub(crate) fn emit_plain_elements<'a, T: 'a, A: Serialize<T>>(
430    values: impl ExactSizeIterator<Item = &'a T>,
431    sink: &mut dyn PlainSink,
432) -> Result<bool, Error> {
433    if !A::__private_is_plain() && values.len() > 0 {
434        return Ok(false);
435    }
436    for value in values {
437        A::__private_emit_plain(value, sink)?;
438    }
439    Ok(true)
440}
441
442/// Returns the budget that is left after emitting a slice of plain values
443/// at once (see `Serialize::__private_plain_cost`).
444#[inline]
445pub(crate) fn plain_cost_slice<T, A: Serialize<T>>(slice: &[T], budget: usize) -> Option<usize> {
446    if let Some(bytes) = A::__private_slice_as_bytes(slice) {
447        return budget.checked_sub(atom_cost(&Atom::Bytes(Bytes::new(bytes))));
448    }
449    plain_cost_values::<T, A>(slice.iter(), budget)
450}
451
452/// Returns the budget that is left after emitting a sequence of plain
453/// values at once.
454#[inline]
455pub(crate) fn plain_cost_values<'a, T: 'a, A: Serialize<T>>(
456    values: impl Iterator<Item = &'a T>,
457    budget: usize,
458) -> Option<usize> {
459    let mut budget = budget.checked_sub(1)?;
460    // values that are not plain are driven on their own
461    if !A::__private_is_plain() {
462        return Some(budget);
463    }
464    for value in values {
465        budget = A::__private_plain_cost(value, budget)?;
466    }
467    Some(budget)
468}
469
470/// Emits plain elements as long as they fit into the budget (see
471/// `IndexedSeq::emit_plain_chunk`).
472///
473/// `index` is the index of the first element, the index of the first
474/// element that was not emitted is returned.
475#[inline]
476pub(crate) fn emit_plain_chunk<'a, T: 'a, A: Serialize<T>>(
477    values: impl Iterator<Item = &'a T>,
478    mut index: usize,
479    mut budget: usize,
480    sink: &mut dyn PlainSink,
481) -> Result<usize, Error> {
482    if !A::__private_is_plain() {
483        return Ok(index);
484    }
485    for value in values {
486        match A::__private_plain_cost(value, budget) {
487            Some(left) => budget = left,
488            None => break,
489        }
490        A::__private_emit_plain(value, sink)?;
491        index += 1;
492    }
493    Ok(index)
494}
495
496/// Returns the bytes of a deque of `u8`.
497fn deque_bytes<T, A: Serialize<T>>(value: &VecDeque<T>) -> Option<Cow<'_, [u8]>> {
498    let (front, back) = value.as_slices();
499    let front = A::__private_slice_as_bytes(front)?;
500    if back.is_empty() {
501        return Some(front);
502    }
503    let back = A::__private_slice_as_bytes(back)?;
504    let mut rv = front.into_owned();
505    rv.extend_from_slice(&back);
506    Some(Cow::Owned(rv))
507}
508
509impl<T: Sync, A: Serialize<T>> Serialize<VecDeque<T>> for VecDeque<A> {
510    #[inline]
511    fn __private_begin<'a>(value: &'a VecDeque<T>, _state: &mut State) -> Result<Begin<'a>, Error> {
512        Ok(match deque_bytes::<T, A>(value) {
513            Some(bytes) => Begin::emit(
514                Emit::Atom(Atom::Bytes(Bytes::new(bytes))),
515                ContainerShape::new(),
516                false,
517            ),
518            None => begin_indexed::<Self, _>(value, Self::container_shape(value)),
519        })
520    }
521
522    fn container_shape(value: &VecDeque<T>) -> ContainerShape {
523        ContainerShape::with_len(value.len())
524    }
525
526    fn serialize<'a>(value: &'a VecDeque<T>, state: &mut State) -> Result<Emit<'a>, Error> {
527        Ok(match deque_bytes::<T, A>(value) {
528            Some(bytes) => Emit::Atom(Atom::Bytes(Bytes::new(bytes))),
529            None => IterEmitter::emit::<A, _>(value.iter(), state),
530        })
531    }
532
533    #[inline]
534    fn __private_is_plain() -> bool {
535        A::__private_is_plain()
536    }
537
538    #[inline]
539    fn __private_is_plain_value(value: &VecDeque<T>) -> bool {
540        A::__private_is_plain() || value.is_empty()
541    }
542
543    fn __private_emit_plain(value: &VecDeque<T>, sink: &mut dyn PlainSink) -> Result<(), Error> {
544        match deque_bytes::<T, A>(value) {
545            Some(bytes) => sink.atom(Atom::Bytes(Bytes::new(bytes))),
546            None => {
547                sink.seq_start(Self::container_shape(value))?;
548                emit_plain_elements::<T, A>(value.iter(), sink)?;
549                sink.seq_end()
550            }
551        }
552    }
553
554    #[inline]
555    fn __private_plain_cost(value: &VecDeque<T>, budget: usize) -> Option<usize> {
556        let (front, back) = value.as_slices();
557        plain_cost_slice::<T, A>(back, plain_cost_slice::<T, A>(front, budget)?)
558    }
559}
560
561impl<T: Sync, A: Serialize<T>> IndexedSeq for Adapted<VecDeque<A>, VecDeque<T>> {
562    #[inline]
563    fn element(
564        &self,
565        index: usize,
566        _state: &mut State,
567    ) -> Result<Option<SerializeHandle<'_>>, Error> {
568        Ok(self.get().get(index).map(handle_as::<A, T>))
569    }
570
571    fn emit_plain(&self, sink: &mut dyn PlainSink) -> Result<bool, Error> {
572        emit_plain_elements::<T, A>(self.get().iter(), sink)
573    }
574
575    fn emit_plain_chunk(
576        &self,
577        index: usize,
578        budget: usize,
579        sink: &mut dyn PlainSink,
580    ) -> Result<usize, Error> {
581        emit_plain_chunk::<T, A>(self.get().iter().skip(index), index, budget, sink)
582    }
583}
584
585impl<T: Sync, A: Serialize<T>> Serialize<LinkedList<T>> for LinkedList<A> {
586    begin_without_finish!(LinkedList<T>);
587
588    fn container_shape(value: &LinkedList<T>) -> ContainerShape {
589        ContainerShape::with_len(value.len())
590    }
591
592    fn serialize<'a>(value: &'a LinkedList<T>, state: &mut State) -> Result<Emit<'a>, Error> {
593        Ok(IterEmitter::emit::<A, _>(value.iter(), state))
594    }
595}
596
597/// The elements are emitted in the (arbitrary) order of the heap.
598impl<T: Sync, A: Serialize<T>> Serialize<BinaryHeap<T>> for BinaryHeap<A> {
599    #[inline]
600    fn __private_begin<'a>(
601        value: &'a BinaryHeap<T>,
602        _state: &mut State,
603    ) -> Result<Begin<'a>, Error> {
604        Ok(match A::__private_slice_as_bytes(value.as_slice()) {
605            Some(bytes) => Begin::emit(
606                Emit::Atom(Atom::Bytes(Bytes::new(bytes))),
607                ContainerShape::new(),
608                false,
609            ),
610            None => begin_indexed::<Self, _>(value, Self::container_shape(value)),
611        })
612    }
613
614    fn container_shape(value: &BinaryHeap<T>) -> ContainerShape {
615        ContainerShape::with_len(value.len())
616    }
617
618    fn serialize<'a>(value: &'a BinaryHeap<T>, state: &mut State) -> Result<Emit<'a>, Error> {
619        Ok(match A::__private_slice_as_bytes(value.as_slice()) {
620            Some(bytes) => Emit::Atom(Atom::Bytes(Bytes::new(bytes))),
621            None => IterEmitter::emit::<A, _>(value.as_slice().iter(), state),
622        })
623    }
624}
625
626impl<T: Sync, A: Serialize<T>> IndexedSeq for Adapted<BinaryHeap<A>, BinaryHeap<T>> {
627    #[inline]
628    fn element(
629        &self,
630        index: usize,
631        _state: &mut State,
632    ) -> Result<Option<SerializeHandle<'_>>, Error> {
633        Ok(self.get().as_slice().get(index).map(handle_as::<A, T>))
634    }
635}
636
637/// Implements `Serialize` for maps, generic over the adapters of the keys
638/// and values.
639///
640/// The maps need to support `len`, `is_empty` and `iter`.
641macro_rules! serialize_map {
642    ($([$($gen:tt)*] $ty:ty => $adapter:ty, $order:ident;)*) => {
643        $(
644            impl<$($gen)*> $crate::ser::Serialize<$ty> for $adapter
645            where
646                K: Sync,
647                V: Sync,
648                KA: $crate::ser::Serialize<K>,
649                VA: $crate::ser::Serialize<V>,
650            {
651                #[inline]
652                fn __private_begin<'a>(
653                    value: &'a $ty,
654                    state: &mut $crate::State,
655                ) -> Result<$crate::ser::Begin<'a>, $crate::Error> {
656                    let shape = Self::container_shape(value);
657                    if Self::__private_is_plain_value(value) {
658                        Ok($crate::ser::impls::begin_plain::<Self, $ty>(value, shape))
659                    } else {
660                        Ok($crate::ser::Begin::emit(Self::serialize(value, state)?, shape, false))
661                    }
662                }
663
664                fn container_shape(value: &$ty) -> $crate::ContainerShape {
665                    { let mut shape = $crate::ContainerShape::with_order($crate::Order::$order); shape.set_len(value.len()); shape }
666                }
667
668                fn serialize<'a>(
669                    value: &'a $ty,
670                    state: &mut $crate::State,
671                ) -> Result<$crate::ser::Emit<'a>, $crate::Error> {
672                    Ok($crate::ser::impls::MapIterEmitter::emit::<K, KA, VA>(value.iter(), state))
673                }
674
675                #[inline]
676                fn __private_is_plain() -> bool {
677                    KA::__private_is_plain() && VA::__private_is_plain()
678                }
679
680                #[inline]
681                fn __private_is_plain_value(value: &$ty) -> bool {
682                    (KA::__private_is_plain() && VA::__private_is_plain()) || value.is_empty()
683                }
684
685                fn __private_emit_plain(
686                    value: &$ty,
687                    sink: &mut dyn $crate::ser::PlainSink,
688                ) -> Result<(), $crate::Error> {
689                    sink.map_start(Self::container_shape(value))?;
690                    for (key, value) in value.iter() {
691                        sink.key();
692                        KA::__private_emit_plain(key, sink)?;
693                        VA::__private_emit_plain(value, sink)?;
694                    }
695                    sink.map_end()
696                }
697
698                #[inline]
699                fn __private_plain_cost(value: &$ty, budget: usize) -> Option<usize> {
700                    let mut budget = budget.checked_sub(1)?;
701                    for (key, value) in value.iter() {
702                        budget = KA::__private_plain_cost(key, budget)?;
703                        budget = VA::__private_plain_cost(value, budget)?;
704                    }
705                    Some(budget)
706                }
707            }
708        )*
709    };
710}
711
712// also used for the containers of other crates
713#[allow(unused_imports)]
714pub(crate) use serialize_map;
715
716serialize_map! {
717    [K, V, KA, VA] BTreeMap<K, V> => BTreeMap<KA, VA>, Sorted;
718}
719
720// the hasher of the adapter is not used
721#[cfg(feature = "std")]
722serialize_map! {
723    [K, V, H: BuildHasher + Sync, KA, VA, AH: Sync] HashMap<K, V, H> => HashMap<KA, VA, AH>, Arbitrary;
724}
725
726/// Implements `Serialize` for sets, generic over the adapter of the
727/// elements.
728///
729/// The sets need to support `len`, `is_empty` and `iter`.
730macro_rules! serialize_set {
731    ($([$($gen:tt)*] $ty:ty => $adapter:ty, $order:ident;)*) => {
732        $(
733            impl<$($gen)*> $crate::ser::Serialize<$ty> for $adapter
734            where
735                T: Sync,
736                A: $crate::ser::Serialize<T>,
737            {
738                #[inline]
739                fn __private_begin<'a>(
740                    value: &'a $ty,
741                    state: &mut $crate::State,
742                ) -> Result<$crate::ser::Begin<'a>, $crate::Error> {
743                    let shape = Self::container_shape(value);
744                    if Self::__private_is_plain_value(value) {
745                        Ok($crate::ser::impls::begin_plain::<Self, $ty>(value, shape))
746                    } else {
747                        Ok($crate::ser::Begin::emit(Self::serialize(value, state)?, shape, false))
748                    }
749                }
750
751                fn container_shape(value: &$ty) -> $crate::ContainerShape {
752                    { let mut shape = $crate::ContainerShape::with_order($crate::Order::$order); shape.set_len(value.len()); shape }
753                }
754
755                fn describe(_value: &$ty, d: &mut dyn $crate::ser::Describe) {
756                    d.set();
757                }
758
759                fn serialize<'a>(
760                    value: &'a $ty,
761                    state: &mut $crate::State,
762                ) -> Result<$crate::ser::Emit<'a>, $crate::Error> {
763                    Ok($crate::ser::impls::IterEmitter::emit::<A, _>(value.iter(), state))
764                }
765
766                #[inline]
767                fn __private_is_plain() -> bool {
768                    A::__private_is_plain()
769                }
770
771                #[inline]
772                fn __private_is_plain_value(value: &$ty) -> bool {
773                    A::__private_is_plain() || value.is_empty()
774                }
775
776                fn __private_emit_plain(
777                    value: &$ty,
778                    sink: &mut dyn $crate::ser::PlainSink,
779                ) -> Result<(), $crate::Error> {
780                    sink.seq_start(Self::container_shape(value))?;
781                    for value in value.iter() {
782                        A::__private_emit_plain(value, sink)?;
783                    }
784                    sink.seq_end()
785                }
786
787                #[inline]
788                fn __private_plain_cost(value: &$ty, budget: usize) -> Option<usize> {
789                    $crate::ser::impls::plain_cost_values::<T, A>(value.iter(), budget)
790                }
791            }
792        )*
793    };
794}
795
796// also used for the containers of other crates
797#[allow(unused_imports)]
798pub(crate) use serialize_set;
799
800serialize_set! {
801    [T, A] BTreeSet<T> => BTreeSet<A>, Sorted;
802}
803
804// the hasher of the adapter is not used
805#[cfg(feature = "std")]
806serialize_set! {
807    [T, H: BuildHasher + Sync, A, AH: Sync] HashSet<T, H> => HashSet<A, AH>, Arbitrary;
808}
809
810impl<T: Sync, A: Serialize<T>> Serialize<Option<T>> for Option<A> {
811    fn is_optional(value: &Option<T>) -> bool {
812        value.is_none()
813    }
814
815    fn container_shape(value: &Option<T>) -> ContainerShape {
816        match value {
817            Some(value) => A::container_shape(value),
818            None => ContainerShape::new(),
819        }
820    }
821
822    fn describe(value: &Option<T>, d: &mut dyn Describe) {
823        match value {
824            Some(value) => {
825                d.some();
826                A::describe(value, d);
827            }
828            None => d.none(),
829        }
830    }
831
832    fn serialize<'a>(value: &'a Option<T>, state: &mut State) -> Result<Emit<'a>, Error> {
833        match value {
834            Some(value) => A::serialize(value, state),
835            None => Ok(Emit::Atom(Atom::Null)),
836        }
837    }
838
839    fn finish(value: &Option<T>, state: &mut State) -> Result<(), Error> {
840        match value {
841            Some(value) => A::finish(value, state),
842            None => Ok(()),
843        }
844    }
845
846    #[inline]
847    fn __private_begin<'a>(value: &'a Option<T>, state: &mut State) -> Result<Begin<'a>, Error> {
848        match value {
849            Some(value) => A::__private_begin(value, state),
850            None => Ok(Begin::emit(
851                Emit::Atom(Atom::Null),
852                ContainerShape::new(),
853                false,
854            )),
855        }
856    }
857
858    #[inline]
859    fn __private_is_plain() -> bool {
860        A::__private_is_plain()
861    }
862
863    #[inline]
864    fn __private_is_plain_value(value: &Option<T>) -> bool {
865        match value {
866            Some(value) => A::__private_is_plain_value(value),
867            None => true,
868        }
869    }
870
871    #[inline]
872    fn __private_emit_plain(value: &Option<T>, sink: &mut dyn PlainSink) -> Result<(), Error> {
873        match value {
874            Some(value) => A::__private_emit_plain(value, sink),
875            None => sink.atom(Atom::Null),
876        }
877    }
878
879    #[inline]
880    fn __private_plain_cost(value: &Option<T>, budget: usize) -> Option<usize> {
881        match value {
882            Some(value) => A::__private_plain_cost(value, budget),
883            None => budget.checked_sub(1),
884        }
885    }
886}
887
888/// Counts as one, used to count repetitions.
889macro_rules! count_one {
890    ($name:ident) => {
891        1
892    };
893}
894
895macro_rules! serialize_for_tuple {
896    () => ();
897    ($(($name:ident, $adapter:ident),)+) => (
898        impl<$($name: Sync,)* $($adapter: Serialize<$name>),*> Serialize<($($name,)*)> for ($($adapter,)*) {
899            #[inline]
900            fn __private_begin<'a>(value: &'a ($($name,)*), _state: &mut State) -> Result<Begin<'a>, Error> {
901                Ok(begin_indexed::<Self, _>(value, Self::container_shape(value)))
902            }
903
904            fn container_shape(_value: &($($name,)*)) -> ContainerShape {
905                ContainerShape::with_len(0 $(+ count_one!($name))*)
906            }
907
908            fn describe(_value: &($($name,)*), d: &mut dyn Describe) {
909                d.tuple();
910            }
911
912            #[inline]
913            fn __private_is_plain() -> bool {
914                true $(&& $adapter::__private_is_plain())*
915            }
916
917            #[allow(non_snake_case)]
918            fn __private_emit_plain(value: &($($name,)*), sink: &mut dyn PlainSink) -> Result<(), Error> {
919                let ($($name,)*) = value;
920                sink.seq_start(Self::container_shape(value))?;
921                $($adapter::__private_emit_plain($name, sink)?;)*
922                sink.seq_end()
923            }
924
925            #[allow(non_snake_case)]
926            #[inline]
927            fn __private_plain_cost(value: &($($name,)*), budget: usize) -> Option<usize> {
928                let ($($name,)*) = value;
929                let budget = budget.checked_sub(1)?;
930                $(let budget = $adapter::__private_plain_cost($name, budget)?;)*
931                Some(budget)
932            }
933
934            fn serialize<'a>(value: &'a ($($name,)*), state: &mut State) -> Result<Emit<'a>, Error> {
935                let seq = Adapted::<Self, _>::indexed(value);
936                Ok(Emit::seq(crate::ser::IndexedSeqEmitter::new(seq), state))
937            }
938        }
939
940        impl<$($name: Sync,)* $($adapter: Serialize<$name>),*> IndexedSeq
941            for Adapted<($($adapter,)*), ($($name,)*)>
942        {
943            #[allow(non_snake_case)]
944            fn element(&self, index: usize, _state: &mut State) -> Result<Option<SerializeHandle<'_>>, Error> {
945                let ($($name,)*) = self.get();
946                let mut __counter = 0;
947                $(
948                    if index == __counter {
949                        return Ok(Some(handle_as::<$adapter, $name>($name)));
950                    }
951                    __counter += 1;
952                )*
953                let _ = __counter;
954                Ok(None)
955            }
956
957            #[allow(non_snake_case)]
958            fn emit_plain(&self, sink: &mut dyn PlainSink) -> Result<bool, Error> {
959                if !<($($adapter,)*) as Serialize<($($name,)*)>>::__private_is_plain() {
960                    return Ok(false);
961                }
962                let ($($name,)*) = self.get();
963                $($adapter::__private_emit_plain($name, sink)?;)*
964                Ok(true)
965            }
966        }
967
968        serialize_for_tuple_peel!($(($name, $adapter),)*);
969    )
970}
971
972macro_rules! serialize_for_tuple_peel {
973    ($first:tt, $($other:tt,)*) => (serialize_for_tuple!($($other,)*);)
974}
975
976serialize_for_tuple! {
977    (T1, A1), (T2, A2), (T3, A3), (T4, A4), (T5, A5), (T6, A6),
978    (T7, A7), (T8, A8), (T9, A9), (T10, A10), (T11, A11), (T12, A12),
979}
980
981impl<T: Sync, A: Serialize<T>, const N: usize> Serialize<[T; N]> for [A; N] {
982    #[inline]
983    fn __private_begin<'a>(value: &'a [T; N], _state: &mut State) -> Result<Begin<'a>, Error> {
984        Ok(match A::__private_slice_as_bytes(&value[..]) {
985            Some(bytes) => Begin::emit(
986                Emit::Atom(Atom::Bytes(Bytes::new(bytes))),
987                ContainerShape::new(),
988                false,
989            ),
990            None => begin_indexed::<Self, _>(value, Self::container_shape(value)),
991        })
992    }
993
994    fn container_shape(value: &[T; N]) -> ContainerShape {
995        ContainerShape::with_len(value.len())
996    }
997
998    fn serialize<'a>(value: &'a [T; N], state: &mut State) -> Result<Emit<'a>, Error> {
999        Ok(match A::__private_slice_as_bytes(value) {
1000            Some(bytes) => Emit::Atom(Atom::Bytes(Bytes::new(bytes))),
1001            None => IterEmitter::emit::<A, _>(value.iter(), state),
1002        })
1003    }
1004
1005    #[inline]
1006    fn __private_is_plain() -> bool {
1007        A::__private_is_plain()
1008    }
1009
1010    #[inline]
1011    fn __private_is_plain_value(_value: &[T; N]) -> bool {
1012        A::__private_is_plain() || N == 0
1013    }
1014
1015    fn __private_emit_plain(value: &[T; N], sink: &mut dyn PlainSink) -> Result<(), Error> {
1016        emit_plain_slice::<T, A>(value, Self::container_shape(value), sink)
1017    }
1018
1019    #[inline]
1020    fn __private_plain_cost(value: &[T; N], budget: usize) -> Option<usize> {
1021        plain_cost_slice::<T, A>(value, budget)
1022    }
1023}
1024
1025impl<T: Sync, A: Serialize<T>, const N: usize> IndexedSeq for Adapted<[A; N], [T; N]> {
1026    #[inline]
1027    fn element(
1028        &self,
1029        index: usize,
1030        _state: &mut State,
1031    ) -> Result<Option<SerializeHandle<'_>>, Error> {
1032        Ok(self.get().get(index).map(handle_as::<A, T>))
1033    }
1034
1035    fn emit_plain(&self, sink: &mut dyn PlainSink) -> Result<bool, Error> {
1036        emit_plain_elements::<T, A>(self.get().iter(), sink)
1037    }
1038
1039    fn emit_plain_chunk(
1040        &self,
1041        index: usize,
1042        budget: usize,
1043        sink: &mut dyn PlainSink,
1044    ) -> Result<usize, Error> {
1045        emit_plain_chunk::<T, A>(
1046            self.get().get(index..).unwrap_or_default().iter(),
1047            index,
1048            budget,
1049            sink,
1050        )
1051    }
1052}
1053
1054/// Implements `Serialize` for pointers by forwarding to the pointee.
1055macro_rules! serialize_pointer {
1056    ($([$($gen:tt)*] $ty:ty => $adapter:ty;)*) => {
1057        $(
1058            impl<$($gen)*> Serialize<$ty> for $adapter {
1059                fn serialize<'a>(value: &'a $ty, state: &mut State) -> Result<Emit<'a>, Error> {
1060                    A::serialize(value, state)
1061                }
1062
1063                fn finish(value: &$ty, state: &mut State) -> Result<(), Error> {
1064                    A::finish(value, state)
1065                }
1066
1067                #[inline]
1068                fn __private_begin<'a>(value: &'a $ty, state: &mut State) -> Result<Begin<'a>, Error> {
1069                    A::__private_begin(value, state)
1070                }
1071
1072                fn is_optional(value: &$ty) -> bool {
1073                    A::is_optional(value)
1074                }
1075
1076                fn container_shape(value: &$ty) -> ContainerShape {
1077                    A::container_shape(value)
1078                }
1079
1080                fn describe(value: &$ty, d: &mut dyn Describe) {
1081                    A::describe(value, d)
1082                }
1083
1084                #[inline]
1085                fn __private_is_plain() -> bool {
1086                    A::__private_is_plain()
1087                }
1088
1089                #[inline]
1090                fn __private_is_plain_value(value: &$ty) -> bool {
1091                    A::__private_is_plain_value(value)
1092                }
1093
1094                #[inline]
1095                fn __private_emit_plain(value: &$ty, sink: &mut dyn PlainSink) -> Result<(), Error> {
1096                    A::__private_emit_plain(value, sink)
1097                }
1098
1099                #[inline]
1100                fn __private_plain_cost(value: &$ty, budget: usize) -> Option<usize> {
1101                    A::__private_plain_cost(value, budget)
1102                }
1103            }
1104        )*
1105    };
1106}
1107
1108serialize_pointer! {
1109    ['r, T: Sync + ?Sized, A: Serialize<T> + ?Sized] &'r T => &'r A;
1110    ['r, T: Sync + ?Sized, A: Serialize<T> + ?Sized] &'r mut T => &'r mut A;
1111    [T: Sync + ?Sized, A: Serialize<T> + ?Sized] Box<T> => Box<A>;
1112    [T: Send + Sync + ?Sized, A: Serialize<T> + Send + ?Sized] Arc<T> => Arc<A>;
1113}