rmp_serde/
encode.rs

1//! Serialize a Rust data structure into MessagePack data.
2
3use 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, StructMapConfig, StructTupleConfig
22};
23use crate::MSGPACK_EXT_STRUCT_NAME;
24
25/// This type represents all possible errors that can occur when serializing or
26/// deserializing MessagePack data.
27#[derive(Debug)]
28pub enum Error {
29    /// Failed to write a MessagePack value.
30    InvalidValueWrite(ValueWriteError),
31    //TODO: This can be removed at some point
32    /// Failed to serialize struct, sequence or map, because its length is unknown.
33    UnknownLength,
34    /// Invalid Data model, i.e. Serialize trait is not implmented correctly
35    InvalidDataModel(&'static str),
36    /// Depth limit exceeded
37    DepthLimitExceeded,
38    /// Catchall for syntax error messages.
39    Syntax(String),
40}
41
42impl error::Error for Error {
43    #[cold]
44    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
45        match *self {
46            Self::InvalidValueWrite(ref err) => Some(err),
47            Self::UnknownLength => None,
48            Self::InvalidDataModel(_) => None,
49            Self::DepthLimitExceeded => None,
50            Self::Syntax(..) => None,
51        }
52    }
53}
54
55impl Display for Error {
56    #[cold]
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
58        match *self {
59            Self::InvalidValueWrite(ref err) => write!(f, "invalid value write: {err}"),
60            Self::UnknownLength => {
61                f.write_str("attempt to serialize struct, sequence or map with unknown length")
62            }
63            Self::InvalidDataModel(r) => write!(f, "serialize data model is invalid: {r}"),
64            Self::DepthLimitExceeded => f.write_str("depth limit exceeded"),
65            Self::Syntax(ref msg) => f.write_str(msg),
66        }
67    }
68}
69
70impl From<ValueWriteError> for Error {
71    #[cold]
72    fn from(err: ValueWriteError) -> Self {
73        Self::InvalidValueWrite(err)
74    }
75}
76
77impl serde::ser::Error for Error {
78    /// Raised when there is general error when deserializing a type.
79    #[cold]
80    fn custom<T: Display>(msg: T) -> Self {
81        Self::Syntax(msg.to_string())
82    }
83}
84
85/// Obtain the underlying writer.
86pub trait UnderlyingWrite {
87    /// Underlying writer type.
88    type Write: Write;
89
90    /// Gets a reference to the underlying writer.
91    fn get_ref(&self) -> &Self::Write;
92
93    /// Gets a mutable reference to the underlying writer.
94    ///
95    /// It is inadvisable to directly write to the underlying writer.
96    fn get_mut(&mut self) -> &mut Self::Write;
97
98    /// Unwraps this `Serializer`, returning the underlying writer.
99    fn into_inner(self) -> Self::Write;
100}
101
102/// Represents MessagePack serialization implementation.
103///
104/// # Note
105///
106/// MessagePack has no specification about how to encode enum types. Thus we are free to do
107/// whatever we want, so the given choice may be not ideal for you.
108///
109/// An enum value is represented as a single-entry map whose key is the variant
110/// id and whose value is a sequence containing all associated data. If the enum
111/// does not have associated data, the sequence is empty.
112///
113/// All instances of `ErrorKind::Interrupted` are handled by this function and the underlying
114/// operation is retried.
115// TODO: Docs. Examples.
116#[derive(Debug)]
117pub struct Serializer<W, C = DefaultConfig> {
118    wr: W,
119    depth: u16,
120    config: RuntimeConfig,
121    _back_compat_config: PhantomData<C>,
122}
123
124impl<W: Write, C> Serializer<W, C> {
125    /// Gets a reference to the underlying writer.
126    #[inline(always)]
127    pub fn get_ref(&self) -> &W {
128        &self.wr
129    }
130
131    /// Gets a mutable reference to the underlying writer.
132    ///
133    /// It is inadvisable to directly write to the underlying writer.
134    #[inline(always)]
135    pub fn get_mut(&mut self) -> &mut W {
136        &mut self.wr
137    }
138
139    /// Unwraps this `Serializer`, returning the underlying writer.
140    #[inline(always)]
141    pub fn into_inner(self) -> W {
142        self.wr
143    }
144
145    /// Changes the maximum nesting depth that is allowed.
146    ///
147    /// Currently unused.
148    #[doc(hidden)]
149    #[inline]
150    pub fn unstable_set_max_depth(&mut self, depth: usize) {
151        self.depth = depth.min(u16::MAX as _) as u16;
152    }
153}
154
155impl<W: Write> Serializer<W, DefaultConfig> {
156    /// Constructs a new `MessagePack` serializer whose output will be written to the writer
157    /// specified.
158    ///
159    /// # Note
160    ///
161    /// This is the default constructor, which returns a serializer that will serialize structs
162    /// and enums using the most compact representation.
163    #[inline]
164    pub fn new(wr: W) -> Self {
165        Self {
166            wr,
167            depth: 1024,
168            config: RuntimeConfig::new(DefaultConfig),
169            _back_compat_config: PhantomData,
170        }
171    }
172}
173
174impl<'a, W: Write + 'a, C> Serializer<W, C> {
175    #[inline]
176    const fn compound(&'a mut self) -> Compound<'a, W, C> {
177        Compound { se: self }
178    }
179}
180
181impl<'a, W: Write + 'a, C: SerializerConfig> Serializer<W, C> {
182    #[inline]
183    fn maybe_unknown_len_compound<F>(&'a mut self, len: Option<u32>, f: F) -> Result<MaybeUnknownLengthCompound<'a, W, C>, Error>
184    where F: Fn(&mut W, u32) -> Result<Marker, ValueWriteError>
185    {
186        Ok(MaybeUnknownLengthCompound {
187            compound: match len {
188                Some(len) => {
189                    f(&mut self.wr, len)?;
190                    None
191                }
192                None => Some(UnknownLengthCompound::from(&*self)),
193            },
194            se: self,
195        })
196    }
197}
198
199impl<W: Write, C> Serializer<W, C> {
200    /// Consumes this serializer returning the new one, which will serialize structs as a map.
201    ///
202    /// This is used, when the default struct serialization as a tuple does not fit your
203    /// requirements.
204    #[inline]
205    pub fn with_struct_map(self) -> Serializer<W, StructMapConfig<C>> {
206        let Self { wr, depth, config, _back_compat_config: _ } = self;
207        Serializer {
208            wr,
209            depth,
210            config: RuntimeConfig::new(StructMapConfig::new(config)),
211            _back_compat_config: PhantomData,
212        }
213    }
214
215    /// Consumes this serializer returning the new one, which will serialize structs as a tuple
216    /// without field names.
217    ///
218    /// This is the default MessagePack serialization mechanism, emitting the most compact
219    /// representation.
220    #[inline]
221    pub fn with_struct_tuple(self) -> Serializer<W, StructTupleConfig<C>> {
222        let Self { wr, depth, config, _back_compat_config: _ } = self;
223        Serializer {
224            wr,
225            depth,
226            config: RuntimeConfig::new(StructTupleConfig::new(config)),
227            _back_compat_config: PhantomData,
228        }
229    }
230
231    /// Consumes this serializer returning the new one, which will serialize some types in
232    /// human-readable representations (`Serializer::is_human_readable` will return `true`). Note
233    /// that the overall representation is still binary, but some types such as IP addresses will
234    /// be saved as human-readable strings.
235    ///
236    /// This is primarily useful if you need to interoperate with serializations produced by older
237    /// versions of `rmp-serde`.
238    #[inline]
239    pub fn with_human_readable(self) -> Serializer<W, HumanReadableConfig<C>> {
240        let Self { wr, depth, config, _back_compat_config: _ } = self;
241        Serializer {
242            wr,
243            depth,
244            config: RuntimeConfig::new(HumanReadableConfig::new(config)),
245            _back_compat_config: PhantomData,
246        }
247    }
248
249    /// Consumes this serializer returning the new one, which will serialize types as binary
250    /// (`Serializer::is_human_readable` will return `false`).
251    ///
252    /// This is the default MessagePack serialization mechanism, emitting the most compact
253    /// representation.
254    #[inline]
255    pub fn with_binary(self) -> Serializer<W, BinaryConfig<C>> {
256        let Self { wr, depth, config, _back_compat_config: _ } = self;
257        Serializer {
258            wr,
259            depth,
260            config: RuntimeConfig::new(BinaryConfig::new(config)),
261            _back_compat_config: PhantomData,
262        }
263    }
264
265    /// Prefer encoding sequences of `u8` as bytes, rather than
266    /// as a sequence of variable-size integers.
267    ///
268    /// This reduces overhead of binary data, but it may break
269    /// decodnig of some Serde types that happen to contain `[u8]`s,
270    /// but don't implement Serde's `visit_bytes`.
271    ///
272    /// ```rust
273    /// use serde::ser::Serialize;
274    /// let mut msgpack_data = Vec::new();
275    /// let mut serializer = rmp_serde::Serializer::new(&mut msgpack_data)
276    ///     .with_bytes(rmp_serde::config::BytesMode::ForceAll);
277    /// vec![255u8; 100].serialize(&mut serializer).unwrap();
278    /// ```
279    #[inline]
280    pub const fn with_bytes(mut self, mode: BytesMode) -> Self {
281        self.config.bytes = mode;
282        self
283    }
284}
285
286impl<W: Write, C> UnderlyingWrite for Serializer<W, C> {
287    type Write = W;
288
289    #[inline(always)]
290    fn get_ref(&self) -> &Self::Write {
291        &self.wr
292    }
293
294    #[inline(always)]
295    fn get_mut(&mut self) -> &mut Self::Write {
296        &mut self.wr
297    }
298
299    #[inline(always)]
300    fn into_inner(self) -> Self::Write {
301        self.wr
302    }
303}
304
305/// Hack to store fixed-size arrays (which serde says are tuples)
306#[derive(Debug)]
307#[doc(hidden)]
308pub struct Tuple<'a, W, C> {
309    len: u32,
310    // can't know if all elements are u8 until the end ;(
311    buf: Option<Vec<u8>>,
312    se: &'a mut Serializer<W, C>,
313}
314
315impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTuple for Tuple<'a, W, C> {
316    type Error = Error;
317    type Ok = ();
318
319    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
320        if let Some(buf) = &mut self.buf {
321            if let Ok(byte) = value.serialize(OnlyBytes) {
322                buf.push(byte);
323                return Ok(());
324            }
325
326            encode::write_array_len(&mut self.se.wr, self.len)?;
327            for b in buf {
328                b.serialize(&mut *self.se)?;
329            }
330            self.buf = None;
331        }
332        value.serialize(&mut *self.se)
333    }
334
335    fn end(self) -> Result<Self::Ok, Self::Error> {
336        if let Some(buf) = self.buf {
337            if self.len < 16 && buf.iter().all(|&b| b < 128) {
338                encode::write_array_len(&mut self.se.wr, self.len)?;
339            } else {
340                encode::write_bin_len(&mut self.se.wr, self.len)?;
341            }
342            self.se.wr.write_all(&buf)
343                .map_err(ValueWriteError::InvalidDataWrite)?;
344        }
345        Ok(())
346    }
347}
348
349/// Part of serde serialization API.
350#[derive(Debug)]
351#[doc(hidden)]
352pub struct Compound<'a, W, C> {
353    se: &'a mut Serializer<W, C>,
354}
355
356#[derive(Debug)]
357#[allow(missing_docs)]
358pub struct ExtFieldSerializer<'a, W> {
359    wr: &'a mut W,
360    tag: Option<i8>,
361    finish: bool,
362}
363
364/// Represents MessagePack serialization implementation for Ext.
365#[derive(Debug)]
366pub struct ExtSerializer<'a, W> {
367    fields_se: ExtFieldSerializer<'a, W>,
368    tuple_received: bool,
369}
370
371impl<'a, W: Write + 'a, C: SerializerConfig> SerializeSeq for Compound<'a, W, C> {
372    type Error = Error;
373    type Ok = ();
374
375    #[inline]
376    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
377        value.serialize(&mut *self.se)
378    }
379
380    #[inline(always)]
381    fn end(self) -> Result<Self::Ok, Self::Error> {
382        Ok(())
383    }
384}
385
386impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTuple for Compound<'a, W, C> {
387    type Error = Error;
388    type Ok = ();
389
390    #[inline]
391    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
392        value.serialize(&mut *self.se)
393    }
394
395    #[inline(always)]
396    fn end(self) -> Result<Self::Ok, Self::Error> {
397        Ok(())
398    }
399}
400
401impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTupleStruct for Compound<'a, W, C> {
402    type Error = Error;
403    type Ok = ();
404
405    #[inline]
406    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
407        value.serialize(&mut *self.se)
408    }
409
410    #[inline(always)]
411    fn end(self) -> Result<Self::Ok, Self::Error> {
412        Ok(())
413    }
414}
415
416impl<'a, W: Write + 'a, C: SerializerConfig> SerializeStruct for Compound<'a, W, C> {
417    type Error = Error;
418    type Ok = ();
419
420    #[inline]
421    fn serialize_field<T: ?Sized + Serialize>(
422        &mut self,
423        key: &'static str,
424        value: &T,
425    ) -> Result<(), Self::Error> {
426        if self.se.config.is_named {
427            encode::write_str(self.se.get_mut(), key)?;
428        }
429        value.serialize(&mut *self.se)
430    }
431
432    #[inline(always)]
433    fn end(self) -> Result<Self::Ok, Self::Error> {
434        Ok(())
435    }
436}
437
438impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTupleVariant for Compound<'a, W, C> {
439    type Error = Error;
440    type Ok = ();
441
442    #[inline]
443    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
444        value.serialize(&mut *self.se)
445    }
446
447    #[inline(always)]
448    fn end(self) -> Result<Self::Ok, Self::Error> {
449        Ok(())
450    }
451}
452
453impl<'a, W: Write + 'a, C: SerializerConfig> SerializeStructVariant for Compound<'a, W, C> {
454    type Error = Error;
455    type Ok = ();
456
457    fn serialize_field<T: ?Sized + Serialize>(
458        &mut self,
459        key: &'static str,
460        value: &T,
461    ) -> Result<(), Self::Error> {
462        if self.se.config.is_named {
463            encode::write_str(self.se.get_mut(), key)?;
464        }
465        value.serialize(&mut *self.se)
466    }
467
468    #[inline(always)]
469    fn end(self) -> Result<Self::Ok, Self::Error> {
470        Ok(())
471    }
472}
473
474/// Contains a `Serializer` for sequences and maps whose length is not yet known
475/// and a counter for the number of elements that are encoded by the `Serializer`.
476#[derive(Debug)]
477struct UnknownLengthCompound {
478    se: Serializer<Vec<u8>, DefaultConfig>,
479    elem_count: u32,
480}
481
482impl<W, C: SerializerConfig> From<&Serializer<W, C>> for UnknownLengthCompound {
483    fn from(se: &Serializer<W, C>) -> Self {
484        Self {
485            se: Serializer {
486                wr: Vec::with_capacity(128),
487                config: RuntimeConfig::new(se.config),
488                depth: se.depth,
489                _back_compat_config: PhantomData,
490            },
491            elem_count: 0,
492        }
493    }
494}
495
496/// Contains a `Serializer` for encoding elements of sequences and maps.
497///
498/// # Note
499///
500/// If , for example, a field inside a struct is tagged with `#serde(flatten)` the total number of
501/// fields of this struct will be unknown to serde because flattened fields may have name clashes
502/// and then will be overwritten. So, serde wants to serialize the struct as a map with an unknown
503/// length.
504///
505/// For the described case a `UnknownLengthCompound` is used to encode the elements. On `end()`
506/// the counted length and the encoded elements will be written to the `Serializer`. A caveat is,
507/// that structs that contain flattened fields arem always written as a map, even when compact
508/// representaion is desired.
509///
510/// Otherwise, if the length is known, the elements will be encoded directly by the `Serializer`.
511#[derive(Debug)]
512#[doc(hidden)]
513pub struct MaybeUnknownLengthCompound<'a, W, C> {
514    se: &'a mut Serializer<W, C>,
515    compound: Option<UnknownLengthCompound>,
516}
517
518impl<'a, W: Write + 'a, C: SerializerConfig> SerializeSeq for MaybeUnknownLengthCompound<'a, W, C> {
519    type Error = Error;
520    type Ok = ();
521
522    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
523        match self.compound.as_mut() {
524            None => value.serialize(&mut *self.se),
525            Some(buf) => {
526                value.serialize(&mut buf.se)?;
527                buf.elem_count += 1;
528                Ok(())
529            },
530        }
531    }
532
533    fn end(self) -> Result<Self::Ok, Self::Error> {
534        if let Some(compound) = self.compound {
535            encode::write_array_len(&mut self.se.wr, compound.elem_count)?;
536            self.se.wr.write_all(&compound.se.into_inner())
537                .map_err(ValueWriteError::InvalidDataWrite)?;
538        }
539        Ok(())
540    }
541}
542
543impl<'a, W: Write + 'a, C: SerializerConfig> SerializeMap for MaybeUnknownLengthCompound<'a, W, C> {
544    type Error = Error;
545    type Ok = ();
546
547    fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error> {
548        <Self as SerializeSeq>::serialize_element(self, key)
549    }
550
551    fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
552        <Self as SerializeSeq>::serialize_element(self, value)
553    }
554
555    fn end(self) -> Result<Self::Ok, Self::Error> {
556        if let Some(compound) = self.compound {
557            encode::write_map_len(&mut self.se.wr, compound.elem_count / 2)?;
558            self.se.wr.write_all(&compound.se.into_inner())
559                .map_err(ValueWriteError::InvalidDataWrite)?;
560        }
561        Ok(())
562    }
563}
564
565impl<'a, W, C> serde::Serializer for &'a mut Serializer<W, C>
566where
567    W: Write,
568    C: SerializerConfig,
569{
570    type Error = Error;
571    type Ok = ();
572    type SerializeMap = MaybeUnknownLengthCompound<'a, W, C>;
573    type SerializeSeq = MaybeUnknownLengthCompound<'a, W, C>;
574    type SerializeStruct = Compound<'a, W, C>;
575    type SerializeStructVariant = Compound<'a, W, C>;
576    type SerializeTuple = Tuple<'a, W, C>;
577    type SerializeTupleStruct = Compound<'a, W, C>;
578    type SerializeTupleVariant = Compound<'a, W, C>;
579
580    #[inline]
581    fn is_human_readable(&self) -> bool {
582        self.config.is_human_readable
583    }
584
585    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
586        encode::write_bool(&mut self.wr, v)
587            .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidMarkerWrite(err)))
588    }
589
590    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
591        self.serialize_i64(i64::from(v))
592    }
593
594    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
595        self.serialize_i64(i64::from(v))
596    }
597
598    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
599        self.serialize_i64(i64::from(v))
600    }
601
602    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
603        encode::write_sint(&mut self.wr, v)?;
604        Ok(())
605    }
606
607    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
608        self.serialize_bytes(&v.to_be_bytes())
609    }
610
611    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
612        self.serialize_u64(u64::from(v))
613    }
614
615    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
616        self.serialize_u64(u64::from(v))
617    }
618
619    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
620        self.serialize_u64(u64::from(v))
621    }
622
623    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
624        encode::write_uint(&mut self.wr, v)?;
625        Ok(())
626    }
627
628    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
629        self.serialize_bytes(&v.to_be_bytes())
630    }
631
632    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
633        encode::write_f32(&mut self.wr, v)?;
634        Ok(())
635    }
636
637    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
638        encode::write_f64(&mut self.wr, v)?;
639        Ok(())
640    }
641
642    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
643        // A char encoded as UTF-8 takes 4 bytes at most.
644        let mut buf = [0; 4];
645        self.serialize_str(v.encode_utf8(&mut buf))
646    }
647
648    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
649        encode::write_str(&mut self.wr, v)?;
650        Ok(())
651    }
652
653    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
654        Ok(encode::write_bin(&mut self.wr, value)?)
655    }
656
657    fn serialize_none(self) -> Result<(), Self::Error> {
658        self.serialize_unit()
659    }
660
661    fn serialize_some<T: ?Sized + serde::Serialize>(self, v: &T) -> Result<(), Self::Error> {
662        v.serialize(self)
663    }
664
665    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
666        encode::write_nil(&mut self.wr)
667            .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidMarkerWrite(err)))
668    }
669
670    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
671        encode::write_array_len(&mut self.wr, 0)?;
672        Ok(())
673    }
674
675    fn serialize_unit_variant(self, _name: &str, _: u32, variant: &'static str) ->
676        Result<Self::Ok, Self::Error>
677    {
678        self.serialize_str(variant)
679    }
680
681    fn serialize_newtype_struct<T: ?Sized + serde::Serialize>(self, name: &'static str, value: &T) -> Result<(), Self::Error> {
682        if name == MSGPACK_EXT_STRUCT_NAME {
683            let mut ext_se = ExtSerializer::new(self);
684            value.serialize(&mut ext_se)?;
685
686            return ext_se.end();
687        }
688
689        // Encode as if it's inner type.
690        value.serialize(self)
691    }
692
693    fn serialize_newtype_variant<T: ?Sized + serde::Serialize>(self, _name: &'static str, _: u32, variant: &'static str, value: &T) -> Result<Self::Ok, Self::Error> {
694        // encode as a map from variant idx to its attributed data, like: {idx => value}
695        encode::write_map_len(&mut self.wr, 1)?;
696        self.serialize_str(variant)?;
697        value.serialize(self)
698    }
699
700    #[inline]
701    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
702        self.maybe_unknown_len_compound(len.map(|len| len as u32), |wr, len| encode::write_array_len(wr, len))
703    }
704
705    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
706        Ok(Tuple {
707            buf: if self.config.bytes == BytesMode::ForceAll && len > 0 {
708                Some(Vec::new())
709            } else {
710                encode::write_array_len(&mut self.wr, len as u32)?;
711                None
712            },
713            len: len as u32,
714            se: self,
715        })
716    }
717
718    fn serialize_tuple_struct(
719        self, _name: &'static str, len: usize,
720    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
721        encode::write_array_len(&mut self.wr, len as u32)?;
722
723        Ok(self.compound())
724    }
725
726    fn serialize_tuple_variant(self, _name: &'static str, _: u32, variant: &'static str, len: usize) ->
727        Result<Self::SerializeTupleVariant, Error>
728    {
729        // encode as a map from variant idx to a sequence of its attributed data, like: {idx => [v1,...,vN]}
730        encode::write_map_len(&mut self.wr, 1)?;
731        self.serialize_str(variant)?;
732        encode::write_array_len(&mut self.wr, len as u32)?;
733        Ok(self.compound())
734    }
735
736    #[inline]
737    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Error> {
738        self.maybe_unknown_len_compound(len.map(|len| len as u32), |wr, len| encode::write_map_len(wr, len))
739    }
740
741    fn serialize_struct(
742        self,
743        _name: &'static str,
744        len: usize,
745    ) -> Result<Self::SerializeStruct, Self::Error> {
746        if self.config.is_named {
747            encode::write_map_len(self.get_mut(), len as u32)?;
748        } else {
749            encode::write_array_len(self.get_mut(), len as u32)?;
750        }
751        Ok(self.compound())
752    }
753
754    fn serialize_struct_variant(self, name: &'static str, _: u32, variant: &'static str, len: usize) ->
755        Result<Self::SerializeStructVariant, Error>
756    {
757        // encode as a map from variant idx to a sequence of its attributed data, like: {idx => [v1,...,vN]}
758        encode::write_map_len(&mut self.wr, 1)?;
759        self.serialize_str(variant)?;
760        self.serialize_struct(name, len)
761    }
762
763    fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> where I: IntoIterator, I::Item: Serialize {
764        let iter = iter.into_iter();
765        let len = match iter.size_hint() {
766            (lo, Some(hi)) if lo == hi && u32::try_from(lo).is_ok() => Some(lo as u32),
767            _ => None,
768        };
769
770        const MAX_ITER_SIZE: usize = std::mem::size_of::<<&[u8] as IntoIterator>::IntoIter>();
771        const ITEM_PTR_SIZE: usize = std::mem::size_of::<&u8>();
772
773        // Estimate whether the input is `&[u8]` or similar (hacky, because Rust lacks proper specialization)
774        let might_be_a_bytes_iter = (std::mem::size_of::<I::Item>() == 1 || std::mem::size_of::<I::Item>() == ITEM_PTR_SIZE)
775            // Complex types like HashSet<u8> don't support reading bytes.
776            // The simplest iterator is ptr+len.
777            && std::mem::size_of::<I::IntoIter>() <= MAX_ITER_SIZE;
778
779        let mut iter = iter.peekable();
780        if might_be_a_bytes_iter && self.config.bytes != BytesMode::Normal {
781            if let Some(len) = len {
782                // The `OnlyBytes` serializer emits `Err` for everything except `u8`
783                if iter.peek().is_some_and(|item| item.serialize(OnlyBytes).is_ok()) {
784                    return self.bytes_from_iter(iter, len);
785                }
786            }
787        }
788
789        let mut serializer = self.serialize_seq(len.map(|len| len as usize))?;
790        iter.try_for_each(|item| serializer.serialize_element(&item))?;
791        SerializeSeq::end(serializer)
792    }
793}
794
795impl<W: Write, C: SerializerConfig> Serializer<W, C> {
796    fn bytes_from_iter<I>(&mut self, mut iter: I, len: u32) -> Result<(), <&mut Self as serde::Serializer>::Error> where I: Iterator, I::Item: Serialize {
797        encode::write_bin_len(&mut self.wr, len)?;
798        iter.try_for_each(|item| {
799            self.wr.write(std::slice::from_ref(&item.serialize(OnlyBytes)
800                .map_err(|_| Error::InvalidDataModel("BytesMode"))?))
801                .map_err(ValueWriteError::InvalidDataWrite)?;
802            Ok(())
803        })
804    }
805}
806
807impl<'a, W: Write + 'a> serde::Serializer for &mut ExtFieldSerializer<'a, W> {
808    type Error = Error;
809    type Ok = ();
810    type SerializeMap = serde::ser::Impossible<(), Error>;
811    type SerializeSeq = serde::ser::Impossible<(), Error>;
812    type SerializeStruct = serde::ser::Impossible<(), Error>;
813    type SerializeStructVariant = serde::ser::Impossible<(), Error>;
814    type SerializeTuple = serde::ser::Impossible<(), Error>;
815    type SerializeTupleStruct = serde::ser::Impossible<(), Error>;
816    type SerializeTupleVariant = serde::ser::Impossible<(), Error>;
817
818    #[inline]
819    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
820        if self.tag.is_none() {
821            self.tag.replace(value);
822            Ok(())
823        } else {
824            Err(Error::InvalidDataModel("expected i8 and bytes"))
825        }
826    }
827
828    #[inline]
829    fn serialize_bytes(self, val: &[u8]) -> Result<Self::Ok, Self::Error> {
830        if let Some(tag) = self.tag.take() {
831            encode::write_ext_meta(self.wr, val.len() as u32, tag)?;
832            self.wr
833                .write_all(val)
834                .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidDataWrite(err)))?;
835
836            self.finish = true;
837
838            Ok(())
839        } else {
840            Err(Error::InvalidDataModel("expected i8 and bytes"))
841        }
842    }
843
844    #[inline]
845    fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
846        Err(Error::InvalidDataModel("expected i8 and bytes"))
847    }
848
849    #[inline]
850    fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
851        Err(Error::InvalidDataModel("expected i8 and bytes"))
852    }
853
854    #[inline]
855    fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
856        Err(Error::InvalidDataModel("expected i8 and bytes"))
857    }
858
859    #[inline]
860    fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
861        Err(Error::InvalidDataModel("expected i8 and bytes"))
862    }
863
864    #[inline]
865    fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
866        Err(Error::InvalidDataModel("expected i8 and bytes"))
867    }
868
869    #[inline]
870    fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
871        Err(Error::InvalidDataModel("expected i8 and bytes"))
872    }
873
874    #[inline]
875    fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
876        Err(Error::InvalidDataModel("expected i8 and bytes"))
877    }
878
879    #[inline]
880    fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
881        Err(Error::InvalidDataModel("expected i8 and bytes"))
882    }
883
884    #[inline]
885    fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
886        Err(Error::InvalidDataModel("expected i8 and bytes"))
887    }
888
889    #[inline]
890    fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
891        Err(Error::InvalidDataModel("expected i8 and bytes"))
892    }
893
894    #[inline]
895    fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
896        Err(Error::InvalidDataModel("expected i8 and bytes"))
897    }
898
899    #[inline]
900    fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
901        Err(Error::InvalidDataModel("expected i8 and bytes"))
902    }
903
904    #[inline]
905    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
906        Err(Error::InvalidDataModel("expected i8 and bytes"))
907    }
908
909    #[inline]
910    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
911        Err(Error::InvalidDataModel("expected i8 and bytes"))
912    }
913
914    #[inline]
915    fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
916        Err(Error::InvalidDataModel("expected i8 and bytes"))
917    }
918
919    #[inline]
920    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
921        where T: Serialize + ?Sized
922    {
923        Err(Error::InvalidDataModel("expected i8 and bytes"))
924    }
925
926    fn serialize_newtype_variant<T>(self, _name: &'static str, _idx: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
927        where T: Serialize + ?Sized
928    {
929        Err(Error::InvalidDataModel("expected i8 and bytes"))
930    }
931
932    #[inline]
933    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
934        Err(Error::InvalidDataModel("expected i8 and bytes"))
935    }
936
937    #[inline]
938    fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
939        where T: Serialize + ?Sized
940    {
941        Err(Error::InvalidDataModel("expected i8 and bytes"))
942    }
943
944    #[inline]
945    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
946        Err(Error::InvalidDataModel("expected i8 and bytes"))
947    }
948
949    #[inline]
950    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
951        Err(Error::InvalidDataModel("expected i8 and bytes"))
952    }
953
954    #[inline]
955    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct, Error> {
956        Err(Error::InvalidDataModel("expected i8 and bytes"))
957    }
958
959    #[inline]
960    fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant, Error> {
961        Err(Error::InvalidDataModel("expected i8 and bytes"))
962    }
963
964    #[inline]
965    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
966        Err(Error::InvalidDataModel("expected i8 and bytes"))
967    }
968
969    #[inline]
970    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct, Error> {
971        Err(Error::InvalidDataModel("expected i8 and bytes"))
972    }
973
974    #[inline]
975    fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant, Error> {
976        Err(Error::InvalidDataModel("expected i8 and bytes"))
977    }
978}
979
980impl<'a, W: Write + 'a> serde::ser::Serializer for &mut ExtSerializer<'a, W> {
981    type Error = Error;
982    type Ok = ();
983    type SerializeMap = serde::ser::Impossible<(), Error>;
984    type SerializeSeq = serde::ser::Impossible<(), Error>;
985    type SerializeStruct = serde::ser::Impossible<(), Error>;
986    type SerializeStructVariant = serde::ser::Impossible<(), Error>;
987    type SerializeTuple = Self;
988    type SerializeTupleStruct = serde::ser::Impossible<(), Error>;
989    type SerializeTupleVariant = serde::ser::Impossible<(), Error>;
990
991    #[inline]
992    fn serialize_bytes(self, _val: &[u8]) -> Result<Self::Ok, Self::Error> {
993        Err(Error::InvalidDataModel("expected tuple"))
994    }
995
996    #[inline]
997    fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
998        Err(Error::InvalidDataModel("expected tuple"))
999    }
1000
1001    #[inline]
1002    fn serialize_i8(self, _value: i8) -> Result<Self::Ok, Self::Error> {
1003        Err(Error::InvalidDataModel("expected tuple"))
1004    }
1005
1006    #[inline]
1007    fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
1008        Err(Error::InvalidDataModel("expected tuple"))
1009    }
1010
1011    #[inline]
1012    fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
1013        Err(Error::InvalidDataModel("expected tuple"))
1014    }
1015
1016    #[inline]
1017    fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
1018        Err(Error::InvalidDataModel("expected tuple"))
1019    }
1020
1021    #[inline]
1022    fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
1023        Err(Error::InvalidDataModel("expected tuple"))
1024    }
1025
1026    #[inline]
1027    fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
1028        Err(Error::InvalidDataModel("expected tuple"))
1029    }
1030
1031    #[inline]
1032    fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
1033        Err(Error::InvalidDataModel("expected tuple"))
1034    }
1035
1036    #[inline]
1037    fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
1038        Err(Error::InvalidDataModel("expected tuple"))
1039    }
1040
1041    #[inline]
1042    fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
1043        Err(Error::InvalidDataModel("expected tuple"))
1044    }
1045
1046    #[inline]
1047    fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
1048        Err(Error::InvalidDataModel("expected tuple"))
1049    }
1050
1051    #[inline]
1052    fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
1053        Err(Error::InvalidDataModel("expected tuple"))
1054    }
1055
1056    #[inline]
1057    fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
1058        Err(Error::InvalidDataModel("expected tuple"))
1059    }
1060
1061    #[inline]
1062    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
1063        Err(Error::InvalidDataModel("expected tuple"))
1064    }
1065
1066    #[inline]
1067    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
1068        Err(Error::InvalidDataModel("expected tuple"))
1069    }
1070
1071    #[inline]
1072    fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
1073        Err(Error::InvalidDataModel("expected tuple"))
1074    }
1075
1076    #[inline]
1077    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
1078        where T: Serialize + ?Sized
1079    {
1080        Err(Error::InvalidDataModel("expected tuple"))
1081    }
1082
1083    #[inline]
1084    fn serialize_newtype_variant<T>(self, _name: &'static str, _idx: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
1085        where T: Serialize + ?Sized
1086    {
1087        Err(Error::InvalidDataModel("expected tuple"))
1088    }
1089
1090    #[inline]
1091    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1092        Err(Error::InvalidDataModel("expected tuple"))
1093    }
1094
1095    #[inline]
1096    fn serialize_some<T>(self, _value: &T) -> Result<Self::Ok, Self::Error>
1097        where T: Serialize + ?Sized
1098    {
1099        Err(Error::InvalidDataModel("expected tuple"))
1100    }
1101
1102    #[inline]
1103    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1104        Err(Error::InvalidDataModel("expected tuple"))
1105    }
1106
1107    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
1108        // FIXME check len
1109        self.tuple_received = true;
1110
1111        Ok(self)
1112    }
1113
1114    #[inline]
1115    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct, Error> {
1116        Err(Error::InvalidDataModel("expected tuple"))
1117    }
1118
1119    #[inline]
1120    fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant, Error> {
1121        Err(Error::InvalidDataModel("expected tuple"))
1122    }
1123
1124    #[inline]
1125    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
1126        Err(Error::InvalidDataModel("expected tuple"))
1127    }
1128
1129    #[inline]
1130    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct, Error> {
1131        Err(Error::InvalidDataModel("expected tuple"))
1132    }
1133
1134    #[inline]
1135    fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant, Error> {
1136        Err(Error::InvalidDataModel("expected tuple"))
1137    }
1138}
1139
1140impl<'a, W: Write + 'a> SerializeTuple for &mut ExtSerializer<'a, W> {
1141    type Error = Error;
1142    type Ok = ();
1143
1144    #[inline]
1145    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
1146        value.serialize(&mut self.fields_se)
1147    }
1148
1149    #[inline(always)]
1150    fn end(self) -> Result<Self::Ok, Self::Error> {
1151        Ok(())
1152    }
1153}
1154
1155impl<'a, W: Write + 'a> ExtSerializer<'a, W> {
1156    #[inline]
1157    fn new<C>(ser: &'a mut Serializer<W, C>) -> Self {
1158        Self {
1159            fields_se: ExtFieldSerializer::new(ser),
1160            tuple_received: false,
1161        }
1162    }
1163
1164    #[inline]
1165    const fn end(self) -> Result<(), Error> {
1166        if self.tuple_received {
1167            self.fields_se.end()
1168        } else {
1169            Err(Error::InvalidDataModel("expected tuple"))
1170        }
1171    }
1172}
1173
1174impl<'a, W: Write + 'a> ExtFieldSerializer<'a, W> {
1175    #[inline]
1176    fn new<C>(ser: &'a mut Serializer<W, C>) -> Self {
1177        Self {
1178            wr: UnderlyingWrite::get_mut(ser),
1179            tag: None,
1180            finish: false,
1181        }
1182    }
1183
1184    #[inline]
1185    const fn end(self) -> Result<(), Error> {
1186        if self.finish {
1187            Ok(())
1188        } else {
1189            Err(Error::InvalidDataModel("expected i8 and bytes"))
1190        }
1191    }
1192}
1193
1194/// Serialize the given data structure as MessagePack into the I/O stream.
1195/// This function uses compact representation - structures as arrays
1196///
1197/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1198#[inline]
1199pub fn write<W, T>(wr: &mut W, val: &T) -> Result<(), Error>
1200where
1201    W: Write + ?Sized,
1202    T: Serialize + ?Sized,
1203{
1204    val.serialize(&mut Serializer::new(wr))
1205}
1206
1207/// Serialize the given data structure as MessagePack into the I/O stream.
1208/// This function serializes structures as maps
1209///
1210/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1211pub fn write_named<W, T>(wr: &mut W, val: &T) -> Result<(), Error>
1212where
1213    W: Write + ?Sized,
1214    T: Serialize + ?Sized,
1215{
1216    let mut se = Serializer::new(wr);
1217    // Avoids another monomorphisation of `StructMapConfig`
1218    se.config = RuntimeConfig::new(StructMapConfig::new(se.config));
1219    val.serialize(&mut se)
1220}
1221
1222/// Serialize the given data structure as a MessagePack byte vector.
1223/// This method uses compact representation, structs are serialized as arrays
1224///
1225/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1226#[inline]
1227pub fn to_vec<T>(val: &T) -> Result<Vec<u8>, Error>
1228where
1229    T: Serialize + ?Sized,
1230{
1231    let mut wr = FallibleWriter(Vec::new());
1232    write(&mut wr, val)?;
1233    Ok(wr.0)
1234}
1235
1236/// Serializes data structure into byte vector as a map
1237/// Resulting MessagePack message will contain field names
1238///
1239/// # Errors
1240///
1241/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1242#[inline]
1243pub fn to_vec_named<T>(val: &T) -> Result<Vec<u8>, Error>
1244where
1245    T: Serialize + ?Sized,
1246{
1247    let mut wr = FallibleWriter(Vec::new());
1248    write_named(&mut wr, val)?;
1249    Ok(wr.0)
1250}
1251
1252#[repr(transparent)]
1253struct FallibleWriter(Vec<u8>);
1254
1255impl Write for FallibleWriter {
1256    #[inline(always)]
1257    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1258        self.write_all(buf)?;
1259        Ok(buf.len())
1260    }
1261
1262    #[inline]
1263    fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
1264        self.0.try_reserve(buf.len()).map_err(|_| std::io::ErrorKind::OutOfMemory)?;
1265        self.0.extend_from_slice(buf);
1266        Ok(())
1267    }
1268
1269    fn flush(&mut self) -> std::io::Result<()> {
1270        Ok(())
1271    }
1272}