Skip to main content

deser_core/ser/
impls.rs

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