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