1use crate::bytes::OnlyBytes;
4use crate::config::BytesMode;
5use std::error;
6use std::fmt::{self, Display};
7use std::io::Write;
8use std::marker::PhantomData;
9
10use serde;
11use serde::ser::{
12 SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
13 SerializeTupleStruct, SerializeTupleVariant,
14};
15use serde::Serialize;
16
17use rmp::encode::ValueWriteError;
18use rmp::{encode, Marker};
19
20use crate::config::{
21 BinaryConfig, DefaultConfig, HumanReadableConfig, RuntimeConfig, SerializerConfig,
22 StructMapConfig, StructTupleConfig,
23};
24use crate::MSGPACK_EXT_STRUCT_NAME;
25
26#[derive(Debug)]
29pub enum Error {
30 InvalidValueWrite(ValueWriteError),
32 UnknownLength,
35 InvalidDataModel(&'static str),
37 DepthLimitExceeded,
39 Syntax(String),
41}
42
43impl error::Error for Error {
44 #[cold]
45 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
46 match *self {
47 Self::InvalidValueWrite(ref err) => Some(err),
48 Self::UnknownLength => None,
49 Self::InvalidDataModel(_) => None,
50 Self::DepthLimitExceeded => None,
51 Self::Syntax(..) => None,
52 }
53 }
54}
55
56impl Display for Error {
57 #[cold]
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
59 match *self {
60 Self::InvalidValueWrite(ref err) => write!(f, "invalid value write: {err}"),
61 Self::UnknownLength => {
62 f.write_str("attempt to serialize struct, sequence or map with unknown length")
63 }
64 Self::InvalidDataModel(r) => write!(f, "serialize data model is invalid: {r}"),
65 Self::DepthLimitExceeded => f.write_str("depth limit exceeded"),
66 Self::Syntax(ref msg) => f.write_str(msg),
67 }
68 }
69}
70
71impl From<ValueWriteError> for Error {
72 #[cold]
73 fn from(err: ValueWriteError) -> Self {
74 Self::InvalidValueWrite(err)
75 }
76}
77
78impl serde::ser::Error for Error {
79 #[cold]
81 fn custom<T: Display>(msg: T) -> Self {
82 Self::Syntax(msg.to_string())
83 }
84}
85
86pub trait UnderlyingWrite {
88 type Write: Write;
90
91 fn get_ref(&self) -> &Self::Write;
93
94 fn get_mut(&mut self) -> &mut Self::Write;
98
99 fn into_inner(self) -> Self::Write;
101}
102
103#[derive(Debug)]
118pub struct Serializer<W, C = DefaultConfig> {
119 wr: W,
120 depth: u16,
121 config: RuntimeConfig,
122 _back_compat_config: PhantomData<C>,
123}
124
125impl<W: Write, C> Serializer<W, C> {
126 #[inline(always)]
128 pub fn get_ref(&self) -> &W {
129 &self.wr
130 }
131
132 #[inline(always)]
136 pub fn get_mut(&mut self) -> &mut W {
137 &mut self.wr
138 }
139
140 #[inline(always)]
142 pub fn into_inner(self) -> W {
143 self.wr
144 }
145
146 #[doc(hidden)]
150 #[inline]
151 pub fn unstable_set_max_depth(&mut self, depth: usize) {
152 self.depth = depth.min(u16::MAX as _) as u16;
153 }
154}
155
156impl<W: Write> Serializer<W, DefaultConfig> {
157 #[inline]
165 pub fn new(wr: W) -> Self {
166 Self {
167 wr,
168 depth: 1024,
169 config: RuntimeConfig::new(DefaultConfig),
170 _back_compat_config: PhantomData,
171 }
172 }
173}
174
175impl<'a, W: Write + 'a, C> Serializer<W, C> {
176 #[inline]
177 const fn compound(&'a mut self) -> Result<Compound<'a, W, C>, Error> {
178 Ok(Compound { se: self })
179 }
180}
181
182impl<'a, W: Write + 'a, C: SerializerConfig> Serializer<W, C> {
183 #[inline]
184 fn maybe_unknown_len_compound<F>(
185 &'a mut self,
186 len: Option<u32>,
187 f: F,
188 ) -> Result<MaybeUnknownLengthCompound<'a, W, C>, Error>
189 where
190 F: Fn(&mut W, u32) -> Result<Marker, ValueWriteError>,
191 {
192 Ok(MaybeUnknownLengthCompound {
193 compound: match len {
194 Some(len) => {
195 f(&mut self.wr, len)?;
196 None
197 }
198 None => Some(UnknownLengthCompound::from(&*self)),
199 },
200 se: self,
201 })
202 }
203}
204
205impl<W: Write, C> Serializer<W, C> {
206 #[inline]
211 pub fn with_struct_map(self) -> Serializer<W, StructMapConfig<C>> {
212 let Self {
213 wr,
214 depth,
215 config,
216 _back_compat_config: _,
217 } = self;
218 Serializer {
219 wr,
220 depth,
221 config: RuntimeConfig::new(StructMapConfig::new(config)),
222 _back_compat_config: PhantomData,
223 }
224 }
225
226 #[inline]
232 pub fn with_struct_tuple(self) -> Serializer<W, StructTupleConfig<C>> {
233 let Self {
234 wr,
235 depth,
236 config,
237 _back_compat_config: _,
238 } = self;
239 Serializer {
240 wr,
241 depth,
242 config: RuntimeConfig::new(StructTupleConfig::new(config)),
243 _back_compat_config: PhantomData,
244 }
245 }
246
247 #[inline]
255 pub fn with_human_readable(self) -> Serializer<W, HumanReadableConfig<C>> {
256 let Self {
257 wr,
258 depth,
259 config,
260 _back_compat_config: _,
261 } = self;
262 Serializer {
263 wr,
264 depth,
265 config: RuntimeConfig::new(HumanReadableConfig::new(config)),
266 _back_compat_config: PhantomData,
267 }
268 }
269
270 #[inline]
276 pub fn with_binary(self) -> Serializer<W, BinaryConfig<C>> {
277 let Self {
278 wr,
279 depth,
280 config,
281 _back_compat_config: _,
282 } = self;
283 Serializer {
284 wr,
285 depth,
286 config: RuntimeConfig::new(BinaryConfig::new(config)),
287 _back_compat_config: PhantomData,
288 }
289 }
290
291 #[inline]
306 pub const fn with_bytes(mut self, mode: BytesMode) -> Self {
307 self.config.bytes = mode;
308 self
309 }
310}
311
312impl<W: Write, C> UnderlyingWrite for Serializer<W, C> {
313 type Write = W;
314
315 #[inline(always)]
316 fn get_ref(&self) -> &Self::Write {
317 &self.wr
318 }
319
320 #[inline(always)]
321 fn get_mut(&mut self) -> &mut Self::Write {
322 &mut self.wr
323 }
324
325 #[inline(always)]
326 fn into_inner(self) -> Self::Write {
327 self.wr
328 }
329}
330
331#[derive(Debug)]
333#[doc(hidden)]
334pub struct Tuple<'a, W, C> {
335 len: u32,
336 buf: Option<Vec<u8>>,
338 se: &'a mut Serializer<W, C>,
339}
340
341impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTuple for Tuple<'a, W, C> {
342 type Ok = ();
343 type Error = Error;
344
345 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
346 if let Some(buf) = &mut self.buf {
347 if let Ok(byte) = value.serialize(OnlyBytes) {
348 buf.push(byte);
349 return Ok(());
350 } else {
351 encode::write_array_len(&mut self.se.wr, self.len)?;
352 for b in buf {
353 b.serialize(&mut *self.se)?;
354 }
355 self.buf = None;
356 }
357 }
358 value.serialize(&mut *self.se)
359 }
360
361 fn end(self) -> Result<Self::Ok, Self::Error> {
362 if let Some(buf) = self.buf {
363 if self.len < 16 && buf.iter().all(|&b| b < 128) {
364 encode::write_array_len(&mut self.se.wr, self.len)?;
365 } else {
366 encode::write_bin_len(&mut self.se.wr, self.len)?;
367 }
368 self.se
369 .wr
370 .write_all(&buf)
371 .map_err(ValueWriteError::InvalidDataWrite)?;
372 }
373 Ok(())
374 }
375}
376
377#[derive(Debug)]
379#[doc(hidden)]
380pub struct Compound<'a, W, C> {
381 se: &'a mut Serializer<W, C>,
382}
383
384#[derive(Debug)]
385#[allow(missing_docs)]
386pub struct ExtFieldSerializer<'a, W> {
387 wr: &'a mut W,
388 tag: Option<i8>,
389 finish: bool,
390}
391
392#[derive(Debug)]
394pub struct ExtSerializer<'a, W> {
395 fields_se: ExtFieldSerializer<'a, W>,
396 tuple_received: bool,
397}
398
399impl<'a, W: Write + 'a, C: SerializerConfig> SerializeSeq for Compound<'a, W, C> {
400 type Ok = ();
401 type Error = Error;
402
403 #[inline]
404 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
405 value.serialize(&mut *self.se)
406 }
407
408 #[inline(always)]
409 fn end(self) -> Result<Self::Ok, Self::Error> {
410 Ok(())
411 }
412}
413
414impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTuple for Compound<'a, W, C> {
415 type Ok = ();
416 type Error = Error;
417
418 #[inline]
419 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
420 value.serialize(&mut *self.se)
421 }
422
423 #[inline(always)]
424 fn end(self) -> Result<Self::Ok, Self::Error> {
425 Ok(())
426 }
427}
428
429impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTupleStruct for Compound<'a, W, C> {
430 type Ok = ();
431 type Error = Error;
432
433 #[inline]
434 fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
435 value.serialize(&mut *self.se)
436 }
437
438 #[inline(always)]
439 fn end(self) -> Result<Self::Ok, Self::Error> {
440 Ok(())
441 }
442}
443
444impl<'a, W: Write + 'a, C: SerializerConfig> SerializeStruct for Compound<'a, W, C> {
445 type Ok = ();
446 type Error = Error;
447
448 #[inline]
449 fn serialize_field<T: ?Sized + Serialize>(
450 &mut self,
451 key: &'static str,
452 value: &T,
453 ) -> Result<(), Self::Error> {
454 if self.se.config.is_named {
455 encode::write_str(self.se.get_mut(), key)?;
456 }
457 value.serialize(&mut *self.se)
458 }
459
460 #[inline(always)]
461 fn end(self) -> Result<Self::Ok, Self::Error> {
462 Ok(())
463 }
464}
465
466impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTupleVariant for Compound<'a, W, C> {
467 type Ok = ();
468 type Error = Error;
469
470 #[inline]
471 fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
472 value.serialize(&mut *self.se)
473 }
474
475 #[inline(always)]
476 fn end(self) -> Result<Self::Ok, Self::Error> {
477 Ok(())
478 }
479}
480
481impl<'a, W: Write + 'a, C: SerializerConfig> SerializeStructVariant for Compound<'a, W, C> {
482 type Ok = ();
483 type Error = Error;
484
485 fn serialize_field<T: ?Sized + Serialize>(
486 &mut self,
487 key: &'static str,
488 value: &T,
489 ) -> Result<(), Self::Error> {
490 if self.se.config.is_named {
491 encode::write_str(self.se.get_mut(), key)?;
492 value.serialize(&mut *self.se)
493 } else {
494 value.serialize(&mut *self.se)
495 }
496 }
497
498 #[inline(always)]
499 fn end(self) -> Result<Self::Ok, Self::Error> {
500 Ok(())
501 }
502}
503
504#[derive(Debug)]
507struct UnknownLengthCompound {
508 se: Serializer<Vec<u8>, DefaultConfig>,
509 elem_count: u32,
510}
511
512impl<W, C: SerializerConfig> From<&Serializer<W, C>> for UnknownLengthCompound {
513 fn from(se: &Serializer<W, C>) -> Self {
514 Self {
515 se: Serializer {
516 wr: Vec::with_capacity(128),
517 config: RuntimeConfig::new(se.config),
518 depth: se.depth,
519 _back_compat_config: PhantomData,
520 },
521 elem_count: 0,
522 }
523 }
524}
525
526#[derive(Debug)]
542#[doc(hidden)]
543pub struct MaybeUnknownLengthCompound<'a, W, C> {
544 se: &'a mut Serializer<W, C>,
545 compound: Option<UnknownLengthCompound>,
546}
547
548impl<'a, W: Write + 'a, C: SerializerConfig> SerializeSeq for MaybeUnknownLengthCompound<'a, W, C> {
549 type Ok = ();
550 type Error = Error;
551
552 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
553 match self.compound.as_mut() {
554 None => value.serialize(&mut *self.se),
555 Some(buf) => {
556 value.serialize(&mut buf.se)?;
557 buf.elem_count += 1;
558 Ok(())
559 }
560 }
561 }
562
563 fn end(self) -> Result<Self::Ok, Self::Error> {
564 if let Some(compound) = self.compound {
565 encode::write_array_len(&mut self.se.wr, compound.elem_count)?;
566 self.se
567 .wr
568 .write_all(&compound.se.into_inner())
569 .map_err(ValueWriteError::InvalidDataWrite)?;
570 }
571 Ok(())
572 }
573}
574
575impl<'a, W: Write + 'a, C: SerializerConfig> SerializeMap for MaybeUnknownLengthCompound<'a, W, C> {
576 type Ok = ();
577 type Error = Error;
578
579 fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error> {
580 <Self as SerializeSeq>::serialize_element(self, key)
581 }
582
583 fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
584 <Self as SerializeSeq>::serialize_element(self, value)
585 }
586
587 fn end(self) -> Result<Self::Ok, Self::Error> {
588 if let Some(compound) = self.compound {
589 encode::write_map_len(&mut self.se.wr, compound.elem_count / 2)?;
590 self.se
591 .wr
592 .write_all(&compound.se.into_inner())
593 .map_err(ValueWriteError::InvalidDataWrite)?;
594 }
595 Ok(())
596 }
597}
598
599impl<'a, W, C> serde::Serializer for &'a mut Serializer<W, C>
600where
601 W: Write,
602 C: SerializerConfig,
603{
604 type Ok = ();
605 type Error = Error;
606
607 type SerializeSeq = MaybeUnknownLengthCompound<'a, W, C>;
608 type SerializeTuple = Tuple<'a, W, C>;
609 type SerializeTupleStruct = Compound<'a, W, C>;
610 type SerializeTupleVariant = Compound<'a, W, C>;
611 type SerializeMap = MaybeUnknownLengthCompound<'a, W, C>;
612 type SerializeStruct = Compound<'a, W, C>;
613 type SerializeStructVariant = Compound<'a, W, C>;
614
615 #[inline]
616 fn is_human_readable(&self) -> bool {
617 self.config.is_human_readable
618 }
619
620 fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
621 encode::write_bool(&mut self.wr, v)
622 .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidMarkerWrite(err)))
623 }
624
625 fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
626 self.serialize_i64(i64::from(v))
627 }
628
629 fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
630 self.serialize_i64(i64::from(v))
631 }
632
633 fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
634 self.serialize_i64(i64::from(v))
635 }
636
637 fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
638 encode::write_sint(&mut self.wr, v)?;
639 Ok(())
640 }
641
642 fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
643 self.serialize_bytes(&v.to_be_bytes())
644 }
645
646 fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
647 self.serialize_u64(u64::from(v))
648 }
649
650 fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
651 self.serialize_u64(u64::from(v))
652 }
653
654 fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
655 self.serialize_u64(u64::from(v))
656 }
657
658 fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
659 encode::write_uint(&mut self.wr, v)?;
660 Ok(())
661 }
662
663 fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
664 self.serialize_bytes(&v.to_be_bytes())
665 }
666
667 fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
668 encode::write_f32(&mut self.wr, v)?;
669 Ok(())
670 }
671
672 fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
673 encode::write_f64(&mut self.wr, v)?;
674 Ok(())
675 }
676
677 fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
678 let mut buf = [0; 4];
680 self.serialize_str(v.encode_utf8(&mut buf))
681 }
682
683 fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
684 encode::write_str(&mut self.wr, v)?;
685 Ok(())
686 }
687
688 fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
689 Ok(encode::write_bin(&mut self.wr, value)?)
690 }
691
692 fn serialize_none(self) -> Result<(), Self::Error> {
693 self.serialize_unit()
694 }
695
696 fn serialize_some<T: ?Sized + serde::Serialize>(self, v: &T) -> Result<(), Self::Error> {
697 v.serialize(self)
698 }
699
700 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
701 encode::write_nil(&mut self.wr)
702 .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidMarkerWrite(err)))
703 }
704
705 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
706 encode::write_array_len(&mut self.wr, 0)?;
707 Ok(())
708 }
709
710 fn serialize_unit_variant(
711 self,
712 _name: &str,
713 _: u32,
714 variant: &'static str,
715 ) -> Result<Self::Ok, Self::Error> {
716 self.serialize_str(variant)
717 }
718
719 fn serialize_newtype_struct<T: ?Sized + serde::Serialize>(
720 self,
721 name: &'static str,
722 value: &T,
723 ) -> Result<(), Self::Error> {
724 if name == MSGPACK_EXT_STRUCT_NAME {
725 let mut ext_se = ExtSerializer::new(self);
726 value.serialize(&mut ext_se)?;
727
728 return ext_se.end();
729 }
730
731 value.serialize(self)
733 }
734
735 fn serialize_newtype_variant<T: ?Sized + serde::Serialize>(
736 self,
737 _name: &'static str,
738 _: u32,
739 variant: &'static str,
740 value: &T,
741 ) -> Result<Self::Ok, Self::Error> {
742 encode::write_map_len(&mut self.wr, 1)?;
744 self.serialize_str(variant)?;
745 value.serialize(self)
746 }
747
748 #[inline]
749 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
750 self.maybe_unknown_len_compound(len.map(|len| len as u32), |wr, len| {
751 encode::write_array_len(wr, len)
752 })
753 }
754
755 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
756 Ok(Tuple {
757 buf: if self.config.bytes == BytesMode::ForceAll && len > 0 {
758 Some(Vec::new())
759 } else {
760 encode::write_array_len(&mut self.wr, len as u32)?;
761 None
762 },
763 len: len as u32,
764 se: self,
765 })
766 }
767
768 fn serialize_tuple_struct(
769 self,
770 _name: &'static str,
771 len: usize,
772 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
773 encode::write_array_len(&mut self.wr, len as u32)?;
774
775 self.compound()
776 }
777
778 fn serialize_tuple_variant(
779 self,
780 _name: &'static str,
781 _: u32,
782 variant: &'static str,
783 len: usize,
784 ) -> Result<Self::SerializeTupleVariant, Error> {
785 encode::write_map_len(&mut self.wr, 1)?;
787 self.serialize_str(variant)?;
788 encode::write_array_len(&mut self.wr, len as u32)?;
789 self.compound()
790 }
791
792 #[inline]
793 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Error> {
794 self.maybe_unknown_len_compound(len.map(|len| len as u32), |wr, len| {
795 encode::write_map_len(wr, len)
796 })
797 }
798
799 fn serialize_struct(
800 self,
801 _name: &'static str,
802 len: usize,
803 ) -> Result<Self::SerializeStruct, Self::Error> {
804 if self.config.is_named {
805 encode::write_map_len(self.get_mut(), len as u32)?;
806 } else {
807 encode::write_array_len(self.get_mut(), len as u32)?;
808 }
809 self.compound()
810 }
811
812 fn serialize_struct_variant(
813 self,
814 name: &'static str,
815 _: u32,
816 variant: &'static str,
817 len: usize,
818 ) -> Result<Self::SerializeStructVariant, Error> {
819 encode::write_map_len(&mut self.wr, 1)?;
821 self.serialize_str(variant)?;
822 self.serialize_struct(name, len)
823 }
824
825 fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
826 where
827 I: IntoIterator,
828 I::Item: Serialize,
829 {
830 let iter = iter.into_iter();
831 let len = match iter.size_hint() {
832 (lo, Some(hi)) if lo == hi && u32::try_from(lo).is_ok() => Some(lo as u32),
833 _ => None,
834 };
835
836 const MAX_ITER_SIZE: usize = std::mem::size_of::<<&[u8] as IntoIterator>::IntoIter>();
837 const ITEM_PTR_SIZE: usize = std::mem::size_of::<&u8>();
838
839 let might_be_a_bytes_iter = (std::mem::size_of::<I::Item>() == 1 || std::mem::size_of::<I::Item>() == ITEM_PTR_SIZE)
841 && std::mem::size_of::<I::IntoIter>() <= MAX_ITER_SIZE;
844
845 let mut iter = iter.peekable();
846 if might_be_a_bytes_iter && self.config.bytes != BytesMode::Normal {
847 if let Some(len) = len {
848 if iter
850 .peek()
851 .is_some_and(|item| item.serialize(OnlyBytes).is_ok())
852 {
853 return self.bytes_from_iter(iter, len);
854 }
855 }
856 }
857
858 let mut serializer = self.serialize_seq(len.map(|len| len as usize))?;
859 iter.try_for_each(|item| serializer.serialize_element(&item))?;
860 SerializeSeq::end(serializer)
861 }
862}
863
864impl<W: Write, C: SerializerConfig> Serializer<W, C> {
865 fn bytes_from_iter<I>(
866 &mut self,
867 mut iter: I,
868 len: u32,
869 ) -> Result<(), <&mut Self as serde::Serializer>::Error>
870 where
871 I: Iterator,
872 I::Item: Serialize,
873 {
874 encode::write_bin_len(&mut self.wr, len)?;
875 iter.try_for_each(|item| {
876 self.wr
877 .write(std::slice::from_ref(
878 &item
879 .serialize(OnlyBytes)
880 .map_err(|_| Error::InvalidDataModel("BytesMode"))?,
881 ))
882 .map_err(ValueWriteError::InvalidDataWrite)?;
883 Ok(())
884 })
885 }
886}
887
888impl<'a, W: Write + 'a> serde::Serializer for &mut ExtFieldSerializer<'a, W> {
889 type Ok = ();
890 type Error = Error;
891
892 type SerializeSeq = serde::ser::Impossible<(), Error>;
893 type SerializeTuple = serde::ser::Impossible<(), Error>;
894 type SerializeTupleStruct = serde::ser::Impossible<(), Error>;
895 type SerializeTupleVariant = serde::ser::Impossible<(), Error>;
896 type SerializeMap = serde::ser::Impossible<(), Error>;
897 type SerializeStruct = serde::ser::Impossible<(), Error>;
898 type SerializeStructVariant = serde::ser::Impossible<(), Error>;
899
900 #[inline]
901 fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
902 if self.tag.is_none() {
903 self.tag.replace(value);
904 Ok(())
905 } else {
906 Err(Error::InvalidDataModel("expected i8 and bytes"))
907 }
908 }
909
910 #[inline]
911 fn serialize_bytes(self, val: &[u8]) -> Result<Self::Ok, Self::Error> {
912 if let Some(tag) = self.tag.take() {
913 encode::write_ext_meta(self.wr, val.len() as u32, tag)?;
914 self.wr
915 .write_all(val)
916 .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidDataWrite(err)))?;
917
918 self.finish = true;
919
920 Ok(())
921 } else {
922 Err(Error::InvalidDataModel("expected i8 and bytes"))
923 }
924 }
925
926 #[inline]
927 fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
928 Err(Error::InvalidDataModel("expected i8 and bytes"))
929 }
930
931 #[inline]
932 fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
933 Err(Error::InvalidDataModel("expected i8 and bytes"))
934 }
935
936 #[inline]
937 fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
938 Err(Error::InvalidDataModel("expected i8 and bytes"))
939 }
940
941 #[inline]
942 fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
943 Err(Error::InvalidDataModel("expected i8 and bytes"))
944 }
945
946 #[inline]
947 fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
948 Err(Error::InvalidDataModel("expected i8 and bytes"))
949 }
950
951 #[inline]
952 fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
953 Err(Error::InvalidDataModel("expected i8 and bytes"))
954 }
955
956 #[inline]
957 fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
958 Err(Error::InvalidDataModel("expected i8 and bytes"))
959 }
960
961 #[inline]
962 fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
963 Err(Error::InvalidDataModel("expected i8 and bytes"))
964 }
965
966 #[inline]
967 fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
968 Err(Error::InvalidDataModel("expected i8 and bytes"))
969 }
970
971 #[inline]
972 fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
973 Err(Error::InvalidDataModel("expected i8 and bytes"))
974 }
975
976 #[inline]
977 fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
978 Err(Error::InvalidDataModel("expected i8 and bytes"))
979 }
980
981 #[inline]
982 fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
983 Err(Error::InvalidDataModel("expected i8 and bytes"))
984 }
985
986 #[inline]
987 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
988 Err(Error::InvalidDataModel("expected i8 and bytes"))
989 }
990
991 #[inline]
992 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
993 Err(Error::InvalidDataModel("expected i8 and bytes"))
994 }
995
996 #[inline]
997 fn serialize_unit_variant(
998 self,
999 _name: &'static str,
1000 _idx: u32,
1001 _variant: &'static str,
1002 ) -> Result<Self::Ok, Self::Error> {
1003 Err(Error::InvalidDataModel("expected i8 and bytes"))
1004 }
1005
1006 #[inline]
1007 fn serialize_newtype_struct<T: ?Sized + Serialize>(
1008 self,
1009 _name: &'static str,
1010 _value: &T,
1011 ) -> Result<Self::Ok, Self::Error> {
1012 Err(Error::InvalidDataModel("expected i8 and bytes"))
1013 }
1014
1015 fn serialize_newtype_variant<T: ?Sized + Serialize>(
1016 self,
1017 _name: &'static str,
1018 _idx: u32,
1019 _variant: &'static str,
1020 _value: &T,
1021 ) -> Result<Self::Ok, Self::Error> {
1022 Err(Error::InvalidDataModel("expected i8 and bytes"))
1023 }
1024
1025 #[inline]
1026 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1027 Err(Error::InvalidDataModel("expected i8 and bytes"))
1028 }
1029
1030 #[inline]
1031 fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<Self::Ok, Self::Error> {
1032 Err(Error::InvalidDataModel("expected i8 and bytes"))
1033 }
1034
1035 #[inline]
1036 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1037 Err(Error::InvalidDataModel("expected i8 and bytes"))
1038 }
1039
1040 #[inline]
1041 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
1042 Err(Error::InvalidDataModel("expected i8 and bytes"))
1043 }
1044
1045 #[inline]
1046 fn serialize_tuple_struct(
1047 self,
1048 _name: &'static str,
1049 _len: usize,
1050 ) -> Result<Self::SerializeTupleStruct, Error> {
1051 Err(Error::InvalidDataModel("expected i8 and bytes"))
1052 }
1053
1054 #[inline]
1055 fn serialize_tuple_variant(
1056 self,
1057 _name: &'static str,
1058 _idx: u32,
1059 _variant: &'static str,
1060 _len: usize,
1061 ) -> Result<Self::SerializeTupleVariant, Error> {
1062 Err(Error::InvalidDataModel("expected i8 and bytes"))
1063 }
1064
1065 #[inline]
1066 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
1067 Err(Error::InvalidDataModel("expected i8 and bytes"))
1068 }
1069
1070 #[inline]
1071 fn serialize_struct(
1072 self,
1073 _name: &'static str,
1074 _len: usize,
1075 ) -> Result<Self::SerializeStruct, Error> {
1076 Err(Error::InvalidDataModel("expected i8 and bytes"))
1077 }
1078
1079 #[inline]
1080 fn serialize_struct_variant(
1081 self,
1082 _name: &'static str,
1083 _idx: u32,
1084 _variant: &'static str,
1085 _len: usize,
1086 ) -> Result<Self::SerializeStructVariant, Error> {
1087 Err(Error::InvalidDataModel("expected i8 and bytes"))
1088 }
1089}
1090
1091impl<'a, W: Write + 'a> serde::ser::Serializer for &mut ExtSerializer<'a, W> {
1092 type Ok = ();
1093 type Error = Error;
1094
1095 type SerializeSeq = serde::ser::Impossible<(), Error>;
1096 type SerializeTuple = Self;
1097 type SerializeTupleStruct = serde::ser::Impossible<(), Error>;
1098 type SerializeTupleVariant = serde::ser::Impossible<(), Error>;
1099 type SerializeMap = serde::ser::Impossible<(), Error>;
1100 type SerializeStruct = serde::ser::Impossible<(), Error>;
1101 type SerializeStructVariant = serde::ser::Impossible<(), Error>;
1102
1103 #[inline]
1104 fn serialize_bytes(self, _val: &[u8]) -> Result<Self::Ok, Self::Error> {
1105 Err(Error::InvalidDataModel("expected tuple"))
1106 }
1107
1108 #[inline]
1109 fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
1110 Err(Error::InvalidDataModel("expected tuple"))
1111 }
1112
1113 #[inline]
1114 fn serialize_i8(self, _value: i8) -> Result<Self::Ok, Self::Error> {
1115 Err(Error::InvalidDataModel("expected tuple"))
1116 }
1117
1118 #[inline]
1119 fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
1120 Err(Error::InvalidDataModel("expected tuple"))
1121 }
1122
1123 #[inline]
1124 fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
1125 Err(Error::InvalidDataModel("expected tuple"))
1126 }
1127
1128 #[inline]
1129 fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
1130 Err(Error::InvalidDataModel("expected tuple"))
1131 }
1132
1133 #[inline]
1134 fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
1135 Err(Error::InvalidDataModel("expected tuple"))
1136 }
1137
1138 #[inline]
1139 fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
1140 Err(Error::InvalidDataModel("expected tuple"))
1141 }
1142
1143 #[inline]
1144 fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
1145 Err(Error::InvalidDataModel("expected tuple"))
1146 }
1147
1148 #[inline]
1149 fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
1150 Err(Error::InvalidDataModel("expected tuple"))
1151 }
1152
1153 #[inline]
1154 fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
1155 Err(Error::InvalidDataModel("expected tuple"))
1156 }
1157
1158 #[inline]
1159 fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
1160 Err(Error::InvalidDataModel("expected tuple"))
1161 }
1162
1163 #[inline]
1164 fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
1165 Err(Error::InvalidDataModel("expected tuple"))
1166 }
1167
1168 #[inline]
1169 fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
1170 Err(Error::InvalidDataModel("expected tuple"))
1171 }
1172
1173 #[inline]
1174 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
1175 Err(Error::InvalidDataModel("expected tuple"))
1176 }
1177
1178 #[inline]
1179 fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
1180 Err(Error::InvalidDataModel("expected tuple"))
1181 }
1182
1183 #[inline]
1184 fn serialize_unit_variant(
1185 self,
1186 _name: &'static str,
1187 _idx: u32,
1188 _variant: &'static str,
1189 ) -> Result<Self::Ok, Self::Error> {
1190 Err(Error::InvalidDataModel("expected tuple"))
1191 }
1192
1193 #[inline]
1194 fn serialize_newtype_struct<T: ?Sized + Serialize>(
1195 self,
1196 _name: &'static str,
1197 _value: &T,
1198 ) -> Result<Self::Ok, Self::Error> {
1199 Err(Error::InvalidDataModel("expected tuple"))
1200 }
1201
1202 #[inline]
1203 fn serialize_newtype_variant<T: ?Sized + Serialize>(
1204 self,
1205 _name: &'static str,
1206 _idx: u32,
1207 _variant: &'static str,
1208 _value: &T,
1209 ) -> Result<Self::Ok, Self::Error> {
1210 Err(Error::InvalidDataModel("expected tuple"))
1211 }
1212
1213 #[inline]
1214 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1215 Err(Error::InvalidDataModel("expected tuple"))
1216 }
1217
1218 #[inline]
1219 fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<Self::Ok, Self::Error> {
1220 Err(Error::InvalidDataModel("expected tuple"))
1221 }
1222
1223 #[inline]
1224 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1225 Err(Error::InvalidDataModel("expected tuple"))
1226 }
1227
1228 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
1229 self.tuple_received = true;
1231
1232 Ok(self)
1233 }
1234
1235 #[inline]
1236 fn serialize_tuple_struct(
1237 self,
1238 _name: &'static str,
1239 _len: usize,
1240 ) -> Result<Self::SerializeTupleStruct, Error> {
1241 Err(Error::InvalidDataModel("expected tuple"))
1242 }
1243
1244 #[inline]
1245 fn serialize_tuple_variant(
1246 self,
1247 _name: &'static str,
1248 _idx: u32,
1249 _variant: &'static str,
1250 _len: usize,
1251 ) -> Result<Self::SerializeTupleVariant, Error> {
1252 Err(Error::InvalidDataModel("expected tuple"))
1253 }
1254
1255 #[inline]
1256 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
1257 Err(Error::InvalidDataModel("expected tuple"))
1258 }
1259
1260 #[inline]
1261 fn serialize_struct(
1262 self,
1263 _name: &'static str,
1264 _len: usize,
1265 ) -> Result<Self::SerializeStruct, Error> {
1266 Err(Error::InvalidDataModel("expected tuple"))
1267 }
1268
1269 #[inline]
1270 fn serialize_struct_variant(
1271 self,
1272 _name: &'static str,
1273 _idx: u32,
1274 _variant: &'static str,
1275 _len: usize,
1276 ) -> Result<Self::SerializeStructVariant, Error> {
1277 Err(Error::InvalidDataModel("expected tuple"))
1278 }
1279}
1280
1281impl<'a, W: Write + 'a> SerializeTuple for &mut ExtSerializer<'a, W> {
1282 type Ok = ();
1283 type Error = Error;
1284
1285 #[inline]
1286 fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
1287 value.serialize(&mut self.fields_se)
1288 }
1289
1290 #[inline(always)]
1291 fn end(self) -> Result<Self::Ok, Self::Error> {
1292 Ok(())
1293 }
1294}
1295
1296impl<'a, W: Write + 'a> ExtSerializer<'a, W> {
1297 #[inline]
1298 fn new<C>(ser: &'a mut Serializer<W, C>) -> Self {
1299 Self {
1300 fields_se: ExtFieldSerializer::new(ser),
1301 tuple_received: false,
1302 }
1303 }
1304
1305 #[inline]
1306 const fn end(self) -> Result<(), Error> {
1307 if self.tuple_received {
1308 self.fields_se.end()
1309 } else {
1310 Err(Error::InvalidDataModel("expected tuple"))
1311 }
1312 }
1313}
1314
1315impl<'a, W: Write + 'a> ExtFieldSerializer<'a, W> {
1316 #[inline]
1317 fn new<C>(ser: &'a mut Serializer<W, C>) -> Self {
1318 Self {
1319 wr: UnderlyingWrite::get_mut(ser),
1320 tag: None,
1321 finish: false,
1322 }
1323 }
1324
1325 #[inline]
1326 const fn end(self) -> Result<(), Error> {
1327 if self.finish {
1328 Ok(())
1329 } else {
1330 Err(Error::InvalidDataModel("expected i8 and bytes"))
1331 }
1332 }
1333}
1334
1335#[inline]
1340pub fn write<W, T>(wr: &mut W, val: &T) -> Result<(), Error>
1341where
1342 W: Write + ?Sized,
1343 T: Serialize + ?Sized,
1344{
1345 val.serialize(&mut Serializer::new(wr))
1346}
1347
1348pub fn write_named<W, T>(wr: &mut W, val: &T) -> Result<(), Error>
1353where
1354 W: Write + ?Sized,
1355 T: Serialize + ?Sized,
1356{
1357 let mut se = Serializer::new(wr);
1358 se.config = RuntimeConfig::new(StructMapConfig::new(se.config));
1360 val.serialize(&mut se)
1361}
1362
1363#[inline]
1368pub fn to_vec<T>(val: &T) -> Result<Vec<u8>, Error>
1369where
1370 T: Serialize + ?Sized,
1371{
1372 let mut wr = FallibleWriter(Vec::new());
1373 write(&mut wr, val)?;
1374 Ok(wr.0)
1375}
1376
1377#[inline]
1384pub fn to_vec_named<T>(val: &T) -> Result<Vec<u8>, Error>
1385where
1386 T: Serialize + ?Sized,
1387{
1388 let mut wr = FallibleWriter(Vec::new());
1389 write_named(&mut wr, val)?;
1390 Ok(wr.0)
1391}
1392
1393#[repr(transparent)]
1394struct FallibleWriter(Vec<u8>);
1395
1396impl Write for FallibleWriter {
1397 #[inline(always)]
1398 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1399 self.write_all(buf)?;
1400 Ok(buf.len())
1401 }
1402
1403 #[inline]
1404 fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
1405 self.0
1406 .try_reserve(buf.len())
1407 .map_err(|_| std::io::ErrorKind::OutOfMemory)?;
1408 self.0.extend_from_slice(buf);
1409 Ok(())
1410 }
1411
1412 fn flush(&mut self) -> std::io::Result<()> {
1413 Ok(())
1414 }
1415}