1use crate::bool::BoolEncoder;
2use crate::coder::{Buffer, Encoder, Result};
3use crate::error::{err, Error};
4use crate::f32::F32Encoder;
5use crate::int::IntEncoder;
6use crate::length::LengthEncoder;
7use crate::serde::variant::VariantEncoder;
8use crate::serde::{default_box_slice, get_mut_or_resize, type_changed};
9use crate::str::StrEncoder;
10use alloc::boxed::Box;
11use alloc::vec::Vec;
12use core::num::NonZeroUsize;
13use serde::ser::{
14 SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
15 SerializeTupleStruct, SerializeTupleVariant,
16};
17use serde::{Serialize, Serializer};
18
19mod inner {
21 use super::*;
22 use core::result::Result;
23
24 pub fn serialize<T: Serialize + ?Sized>(t: &T) -> Result<Vec<u8>, Error> {
29 let mut lazy = LazyEncoder::Unspecified {
30 reserved: NonZeroUsize::new(1),
31 };
32 let mut index_alloc = 0;
33 t.serialize(EncoderWrapper {
34 lazy: &mut lazy,
35 index_alloc: &mut index_alloc,
36 })?;
37 Ok(lazy.collect(index_alloc))
38 }
39}
40pub use inner::serialize;
41
42enum SpecifiedEncoder {
43 Bool(BoolEncoder),
44 Enum((VariantEncoder, Vec<LazyEncoder>)), F32(F32Encoder),
46 I8(IntEncoder<i8>),
48 I16(IntEncoder<i16>),
49 I32(IntEncoder<i32>),
50 I64(IntEncoder<i64>),
51 I128(IntEncoder<i128>),
52 Map((LengthEncoder, Box<(LazyEncoder, LazyEncoder)>)), Seq((LengthEncoder, Box<LazyEncoder>)), Str(StrEncoder),
55 Tuple(Box<[LazyEncoder]>), U8(IntEncoder<u8>),
57 U16(IntEncoder<u16>),
58 U32(IntEncoder<u32>),
59 U64(IntEncoder<u64>),
60 U128(IntEncoder<u128>),
61}
62
63impl SpecifiedEncoder {
64 fn reserve(&mut self, additional: NonZeroUsize) {
65 match self {
66 Self::Bool(v) => v.reserve(additional),
67 Self::Enum(v) => {
68 v.0.reserve(additional);
69 }
71 Self::F32(v) => v.reserve(additional),
72 Self::I8(v) => v.reserve(additional),
73 Self::I16(v) => v.reserve(additional),
74 Self::I32(v) => v.reserve(additional),
75 Self::I64(v) => v.reserve(additional),
76 Self::I128(v) => v.reserve(additional),
77 Self::Map(v) => {
78 v.0.reserve(additional);
79 }
81 Self::Seq(v) => {
82 v.0.reserve(additional);
83 }
85 Self::Str(v) => {
86 v.reserve(additional);
87 }
88 Self::Tuple(v) => v.iter_mut().for_each(|v| v.reserve_fast(additional.get())),
89 Self::U8(v) => v.reserve(additional),
90 Self::U16(v) => v.reserve(additional),
91 Self::U32(v) => v.reserve(additional),
92 Self::U64(v) => v.reserve(additional),
93 Self::U128(v) => v.reserve(additional),
94 }
95 }
96}
97
98enum LazyEncoder {
99 Unspecified {
100 reserved: Option<NonZeroUsize>,
101 },
102 Specified {
103 specified: SpecifiedEncoder,
104 index: usize,
105 },
106}
107
108impl Default for LazyEncoder {
109 fn default() -> Self {
110 Self::Unspecified { reserved: None }
111 }
112}
113
114impl LazyEncoder {
115 fn collect(&mut self, index_alloc: usize) -> Vec<u8> {
117 let mut buffers = default_box_slice(index_alloc);
126 self.reorder(&mut buffers);
127
128 let mut bytes = vec![];
129 for buffer in Vec::from(buffers).into_iter().flatten() {
130 buffer.collect_into(&mut bytes);
131 }
132 bytes
133 }
134
135 fn reorder<'a>(&'a mut self, buffers: &mut [Option<&'a mut dyn Buffer>]) {
136 match self {
137 Self::Specified { specified, index } => {
138 buffers[*index] = Some(match specified {
139 SpecifiedEncoder::Bool(v) => v,
140 SpecifiedEncoder::Enum(v) => {
141 v.1.iter_mut().for_each(|v| v.reorder(buffers));
142 &mut v.0
143 }
144 SpecifiedEncoder::F32(v) => v,
145 SpecifiedEncoder::I8(v) => v,
146 SpecifiedEncoder::I16(v) => v,
147 SpecifiedEncoder::I32(v) => v,
148 SpecifiedEncoder::I64(v) => v,
149 SpecifiedEncoder::I128(v) => v,
150 SpecifiedEncoder::Map(v) => {
151 v.1 .0.reorder(buffers);
152 v.1 .1.reorder(buffers);
153 &mut v.0
154 }
155 SpecifiedEncoder::Seq(v) => {
156 v.1.reorder(buffers);
157 &mut v.0
158 }
159 SpecifiedEncoder::Str(v) => v,
160 SpecifiedEncoder::Tuple(v) => {
161 v.iter_mut().for_each(|v| v.reorder(buffers));
162 return; }
164 SpecifiedEncoder::U8(v) => v,
165 SpecifiedEncoder::U16(v) => v,
166 SpecifiedEncoder::U32(v) => v,
167 SpecifiedEncoder::U64(v) => v,
168 SpecifiedEncoder::U128(v) => v,
169 });
170 }
171 Self::Unspecified { .. } => (),
172 }
173 }
174
175 #[inline(always)]
182 fn reserve_fast(&mut self, len: usize) {
183 match self {
184 Self::Specified { specified, .. } => {
185 if let Some(len) = NonZeroUsize::new(len) {
186 specified.reserve(len);
187 }
188 }
189 Self::Unspecified { reserved } => *reserved = NonZeroUsize::new(len),
190 }
191 }
192}
193
194macro_rules! specify {
195 ($wrapper:ident, $variant:ident) => {{
196 let lazy = &mut *$wrapper.lazy;
197 match lazy {
198 LazyEncoder::Specified { specified: SpecifiedEncoder::$variant(_), .. } => (),
200 _ => {
201 #[cold]
204 fn cold(
205 me: &mut LazyEncoder,
206 index_alloc: &mut usize,
207 ) {
208 let &mut LazyEncoder::Unspecified { reserved } = me else {
209 type_changed!()
210 };
211 *me = LazyEncoder::Specified {
212 specified: SpecifiedEncoder::$variant(Default::default()),
213 index: core::mem::replace(index_alloc, *index_alloc + 1),
214 };
215 let LazyEncoder::Specified { specified, .. } = me else {
216 unreachable!();
217 };
218 if let Some(reserved) = reserved {
219 specified.reserve(reserved);
220 }
221 }
222 cold(lazy, &mut *$wrapper.index_alloc);
223 }
224 }
225 let LazyEncoder::Specified { specified: SpecifiedEncoder::$variant(b), .. } = lazy else {
226 unsafe { core::hint::unreachable_unchecked() };
229 };
230 b
231 }};
232}
233
234struct EncoderWrapper<'a> {
235 lazy: &'a mut LazyEncoder,
236 index_alloc: &'a mut usize,
237}
238
239impl<'a> EncoderWrapper<'a> {
240 #[inline(always)]
241 fn variant_index_u8(variant_index: u32) -> Result<u8> {
242 if variant_index > u8::MAX as u32 {
243 err("enums with more than 256 variants are unsupported")
244 } else {
245 Ok(variant_index as u8)
246 }
247 }
248
249 #[inline(always)]
250 fn serialize_enum(self, variant_index: u32) -> Result<EncoderWrapper<'a>> {
251 let b = specify!(self, Enum);
252 b.0.encode(&Self::variant_index_u8(variant_index)?);
253 let lazy = get_mut_or_resize(&mut b.1, variant_index as usize);
254 lazy.reserve_fast(1); Ok(Self {
256 lazy,
257 index_alloc: self.index_alloc,
258 })
259 }
260}
261
262macro_rules! impl_ser {
263 ($name:ident, $t:ty, $variant:ident) => {
264 #[inline]
266 fn $name(self, v: $t) -> Result<()> {
267 specify!(self, $variant).encode(&v);
268 Ok(())
269 }
270 };
271}
272
273impl<'a> Serializer for EncoderWrapper<'a> {
274 type Ok = ();
275 type Error = Error;
276 type SerializeSeq = SeqSerializer<'a>;
277 type SerializeTuple = TupleSerializer<'a>;
278 type SerializeTupleStruct = TupleSerializer<'a>;
279 type SerializeTupleVariant = TupleSerializer<'a>;
280 type SerializeMap = MapSerializer<'a>;
281 type SerializeStruct = TupleSerializer<'a>;
282 type SerializeStructVariant = TupleSerializer<'a>;
283
284 impl_ser!(serialize_bool, bool, Bool);
286 impl_ser!(serialize_f32, f32, F32);
287 impl_ser!(serialize_i8, i8, I8);
288 impl_ser!(serialize_i16, i16, I16);
289 impl_ser!(serialize_i32, i32, I32);
290 impl_ser!(serialize_i64, i64, I64);
291 impl_ser!(serialize_i128, i128, I128);
292 impl_ser!(serialize_str, &str, Str);
293 impl_ser!(serialize_u8, u8, U8);
294 impl_ser!(serialize_u16, u16, U16);
295 impl_ser!(serialize_u32, u32, U32);
296 impl_ser!(serialize_u64, u64, U64);
297 impl_ser!(serialize_u128, u128, U128);
298
299 impl_ser!(serialize_f64, f64, U64);
301 impl_ser!(serialize_char, char, U32);
302
303 #[inline(always)]
304 fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok> {
305 v.serialize(self)
306 }
307
308 #[inline(always)]
309 fn serialize_none(self) -> Result<Self::Ok> {
310 Ok(specify!(self, Enum).0.encode(&0))
313 }
314
315 #[inline(always)]
316 fn serialize_some<T: ?Sized>(self, v: &T) -> Result<Self::Ok>
317 where
318 T: Serialize,
319 {
320 v.serialize(self.serialize_enum(1)?)
321 }
322
323 #[inline(always)]
324 fn serialize_unit(self) -> Result<Self::Ok> {
325 Ok(())
326 }
327
328 #[inline(always)]
329 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> {
330 Ok(())
331 }
332
333 #[inline(always)]
334 fn serialize_unit_variant(
335 self,
336 _name: &'static str,
337 variant_index: u32,
338 _variant: &'static str,
339 ) -> Result<Self::Ok> {
340 Ok(specify!(self, Enum)
342 .0
343 .encode(&Self::variant_index_u8(variant_index)?))
344 }
345
346 #[inline(always)]
347 fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Self::Ok>
348 where
349 T: Serialize,
350 {
351 value.serialize(self)
352 }
353
354 #[inline(always)]
355 fn serialize_newtype_variant<T: ?Sized>(
356 self,
357 _name: &'static str,
358 variant_index: u32,
359 _variant: &'static str,
360 value: &T,
361 ) -> Result<Self::Ok>
362 where
363 T: Serialize,
364 {
365 value.serialize(self.serialize_enum(variant_index)?)
366 }
367
368 #[inline(always)]
369 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
370 let len = len.expect("sequence must have len");
371 let b = specify!(self, Seq);
372 b.0.encode(&len);
373 b.1.reserve_fast(len);
374 Ok(SeqSerializer {
375 lazy: &mut b.1,
376 index_alloc: self.index_alloc,
377 len,
378 })
379 }
380
381 #[inline(always)]
382 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
383 if len == 1 {
385 return Ok(TupleSerializer {
386 encoders: core::slice::from_mut(self.lazy),
387 index_alloc: self.index_alloc,
388 });
389 }
390
391 let lazy = &mut *self.lazy;
393 match lazy {
394 LazyEncoder::Specified {
395 specified: SpecifiedEncoder::Tuple(_),
396 ..
397 } => (),
398 _ => {
399 #[cold]
400 fn cold(me: &mut LazyEncoder, len: usize) {
401 let &mut LazyEncoder::Unspecified { reserved } = me else {
402 type_changed!()
403 };
404 *me = LazyEncoder::Specified {
405 specified: SpecifiedEncoder::Tuple(default_box_slice(len)),
406 index: usize::MAX, };
408 let LazyEncoder::Specified { specified, .. } = me else {
409 unreachable!();
410 };
411 if let Some(reserved) = reserved {
412 specified.reserve(reserved);
413 }
414 }
415 cold(lazy, len);
416 }
417 };
418 let LazyEncoder::Specified {
419 specified: SpecifiedEncoder::Tuple(encoders),
420 ..
421 } = lazy
422 else {
423 unsafe { core::hint::unreachable_unchecked() };
425 };
426 if encoders.len() != len {
427 type_changed!() }
429 Ok(TupleSerializer {
430 encoders,
431 index_alloc: self.index_alloc,
432 })
433 }
434
435 #[inline(always)]
436 fn serialize_tuple_struct(
437 self,
438 _name: &'static str,
439 len: usize,
440 ) -> Result<Self::SerializeTupleStruct> {
441 self.serialize_tuple(len)
442 }
443
444 #[inline(always)]
445 fn serialize_tuple_variant(
446 self,
447 _name: &'static str,
448 variant_index: u32,
449 _variant: &'static str,
450 len: usize,
451 ) -> Result<Self::SerializeTupleVariant> {
452 self.serialize_enum(variant_index)?.serialize_tuple(len)
453 }
454
455 #[inline(always)]
456 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
457 let len = len.expect("sequence must have len");
458 let b = specify!(self, Map);
459 b.0.encode(&len);
460 b.1 .0.reserve_fast(len);
461 b.1 .1.reserve_fast(len);
462 Ok(MapSerializer {
463 encoders: &mut b.1,
464 index_alloc: self.index_alloc,
465 len,
466 key_serialized: false, })
468 }
469
470 #[inline(always)]
471 fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
472 self.serialize_tuple(len)
473 }
474
475 #[inline(always)]
476 fn serialize_struct_variant(
477 self,
478 _name: &'static str,
479 variant_index: u32,
480 _variant: &'static str,
481 len: usize,
482 ) -> Result<Self::SerializeStructVariant> {
483 self.serialize_enum(variant_index)?.serialize_tuple(len)
484 }
485
486 #[inline(always)]
487 fn is_human_readable(&self) -> bool {
488 false
489 }
490}
491
492macro_rules! ok_error_end {
493 () => {
494 type Ok = ();
495 type Error = Error;
496 #[inline(always)]
497 fn end(self) -> Result<Self::Ok> {
498 Ok(())
499 }
500 };
501}
502
503struct SeqSerializer<'a> {
504 lazy: &'a mut LazyEncoder,
505 index_alloc: &'a mut usize,
506 len: usize,
507}
508
509impl SerializeSeq for SeqSerializer<'_> {
510 ok_error_end!();
511 #[inline(always)]
512 fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
513 self.len = self.len.checked_sub(1).expect("length mismatch");
515 value.serialize(EncoderWrapper {
516 lazy: &mut *self.lazy,
517 index_alloc: &mut *self.index_alloc,
518 })
519 }
520}
521
522struct TupleSerializer<'a> {
523 encoders: &'a mut [LazyEncoder], index_alloc: &'a mut usize,
525}
526
527macro_rules! impl_tuple {
528 ($tr:ty, $fun:ident $(, $key:ident)?) => {
529 impl $tr for TupleSerializer<'_> {
530 ok_error_end!();
531 #[inline(always)]
532 fn $fun<T: Serialize + ?Sized>(&mut self, $($key: &'static str,)? value: &T) -> Result<()> {
533 let (lazy, remaining) = core::mem::take(&mut self.encoders)
534 .split_first_mut()
535 .expect("length mismatch");
536 self.encoders = remaining;
537 value.serialize(EncoderWrapper {
538 lazy,
539 index_alloc: &mut *self.index_alloc,
540 })
541 }
542
543 $(
544 fn skip_field(&mut self, $key: &'static str) -> Result<()> {
545 err("skip field is not supported")
546 }
547 )?
548 }
549 };
550}
551impl_tuple!(SerializeTuple, serialize_element);
552impl_tuple!(SerializeTupleStruct, serialize_field);
553impl_tuple!(SerializeTupleVariant, serialize_field);
554impl_tuple!(SerializeStruct, serialize_field, _key);
555impl_tuple!(SerializeStructVariant, serialize_field, _key);
556
557struct MapSerializer<'a> {
558 encoders: &'a mut (LazyEncoder, LazyEncoder), index_alloc: &'a mut usize,
560 len: usize,
561 key_serialized: bool,
562}
563
564impl SerializeMap for MapSerializer<'_> {
565 ok_error_end!();
566 #[inline(always)]
567 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>
568 where
569 T: Serialize,
570 {
571 self.len = self.len.checked_sub(1).expect("length mismatch");
573 self.key_serialized = true;
575 key.serialize(EncoderWrapper {
576 lazy: &mut self.encoders.0,
577 index_alloc: &mut *self.index_alloc,
578 })
579 }
580
581 #[inline(always)]
582 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>
583 where
584 T: Serialize,
585 {
586 assert!(
588 core::mem::take(&mut self.key_serialized),
589 "serialize_value before serialize_key"
590 );
591 value.serialize(EncoderWrapper {
592 lazy: &mut self.encoders.1,
593 index_alloc: &mut *self.index_alloc,
594 })
595 }
596 }
598
599#[cfg(test)]
600mod tests {
601 use core::num::NonZeroUsize;
602 use serde::ser::{SerializeMap, SerializeSeq, SerializeTuple};
603 use serde::{Serialize, Serializer};
604
605 #[test]
606 fn enum_256_variants() {
607 enum Enum {
608 A,
609 B,
610 }
611 impl Serialize for Enum {
612 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
613 let variant_index = match self {
614 Self::A => 255,
615 Self::B => 256,
616 };
617 serializer.serialize_unit_variant("", variant_index, "")
618 }
619 }
620 assert!(crate::serialize(&Enum::A).is_ok());
621 assert!(crate::serialize(&Enum::B).is_err());
622 }
623
624 #[test]
625 #[should_panic(expected = "type changed")]
626 fn test_type_changed() {
627 struct BoolOrU8(bool);
628 impl Serialize for BoolOrU8 {
629 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
630 if self.0 {
631 serializer.serialize_bool(false)
632 } else {
633 serializer.serialize_u8(1)
634 }
635 }
636 }
637 let _ = crate::serialize(&vec![BoolOrU8(false), BoolOrU8(true)]);
638 }
639
640 #[test]
641 #[should_panic(expected = "type changed")]
642 fn test_tuple_len_changed() {
643 struct TupleN(usize);
644 impl Serialize for TupleN {
645 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
646 let mut tuple = serializer.serialize_tuple(self.0)?;
647 (0..self.0).try_for_each(|_| tuple.serialize_element(&false))?;
648 tuple.end()
649 }
650 }
651 let _ = crate::serialize(&vec![TupleN(1), TupleN(2)]);
652 }
653
654 macro_rules! new_wrapper {
656 () => {
657 super::EncoderWrapper {
658 lazy: &mut super::LazyEncoder::Unspecified {
659 reserved: NonZeroUsize::new(1),
660 },
661 index_alloc: &mut 0,
662 }
663 };
664 }
665
666 #[test]
667 fn seq_valid() {
668 let w = new_wrapper!();
669 let mut seq = w.serialize_seq(Some(1)).unwrap();
670 let _ = seq.serialize_element(&0u8); }
672
673 #[test]
674 #[should_panic = "length mismatch"]
675 fn seq_incorrect_len() {
676 let w = new_wrapper!();
677 let mut seq = w.serialize_seq(Some(1)).unwrap();
678 let _ = seq.serialize_element(&0u8); let _ = seq.serialize_element(&0u8);
680 }
681
682 #[test]
683 fn map_valid() {
684 let w = new_wrapper!();
685 let mut map = w.serialize_map(Some(1)).unwrap();
686 let _ = map.serialize_key(&0u8); let _ = map.serialize_value(&0u8);
688 }
689
690 #[test]
691 #[should_panic = "length mismatch"]
692 fn map_incorrect_len_keys() {
693 let w = new_wrapper!();
694 let mut map = w.serialize_map(Some(1)).unwrap();
695 let _ = map.serialize_key(&0u8); let _ = map.serialize_key(&0u8);
697 }
698
699 #[test]
700 #[should_panic = "serialize_value before serialize_key"]
701 fn map_value_before_key() {
702 let w = new_wrapper!();
703 let mut map = w.serialize_map(Some(1)).unwrap();
704 let _ = map.serialize_value(&0u8);
705 }
706
707 #[test]
708 #[should_panic = "serialize_value before serialize_key"]
709 fn map_incorrect_len_values() {
710 let w = new_wrapper!();
711 let mut map = w.serialize_map(Some(1)).unwrap();
712 let _ = map.serialize_key(&0u8); let _ = map.serialize_value(&0u8);
714 let _ = map.serialize_value(&0u8);
715 }
716}