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            Error::InvalidValueWrite(ref err) => Some(err),
47            Error::UnknownLength => None,
48            Error::InvalidDataModel(_) => None,
49            Error::DepthLimitExceeded => None,
50            Error::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            Error::InvalidValueWrite(ref err) => write!(f, "invalid value write: {err}"),
60            Error::UnknownLength => {
61                f.write_str("attempt to serialize struct, sequence or map with unknown length")
62            }
63            Error::InvalidDataModel(r) => write!(f, "serialize data model is invalid: {r}"),
64            Error::DepthLimitExceeded => f.write_str("depth limit exceeded"),
65            Error::Syntax(ref msg) => f.write_str(msg),
66        }
67    }
68}
69
70impl From<ValueWriteError> for Error {
71    #[cold]
72    fn from(err: ValueWriteError) -> Error {
73        Error::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) -> Error {
81        Error::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        Serializer {
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    fn compound(&'a mut self) -> Result<Compound<'a, W, C>, Error> {
177        Ok(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 Serializer { 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 Serializer { 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 Serializer { 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 Serializer { 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 fn with_bytes(mut self, mode: BytesMode) -> Serializer<W, C> {
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 Ok = ();
317    type Error = Error;
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            } else {
325                encode::write_array_len(&mut self.se.wr, self.len)?;
326                for b in buf {
327                    b.serialize(&mut *self.se)?;
328                }
329                self.buf = None;
330            }
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 Ok = ();
373    type Error = Error;
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 Ok = ();
388    type Error = Error;
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 Ok = ();
403    type Error = Error;
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 Ok = ();
418    type Error = Error;
419
420    #[inline]
421    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) ->
422        Result<(), Self::Error>
423    {
424        if self.se.config.is_named {
425            encode::write_str(self.se.get_mut(), key)?;
426        }
427        value.serialize(&mut *self.se)
428    }
429
430    #[inline(always)]
431    fn end(self) -> Result<Self::Ok, Self::Error> {
432        Ok(())
433    }
434}
435
436impl<'a, W: Write + 'a, C: SerializerConfig> SerializeTupleVariant for Compound<'a, W, C> {
437    type Ok = ();
438    type Error = Error;
439
440    #[inline]
441    fn serialize_field<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
442        value.serialize(&mut *self.se)
443    }
444
445    #[inline(always)]
446    fn end(self) -> Result<Self::Ok, Self::Error> {
447        Ok(())
448    }
449}
450
451impl<'a, W: Write + 'a, C: SerializerConfig> SerializeStructVariant for Compound<'a, W, C> {
452    type Ok = ();
453    type Error = Error;
454
455    fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, value: &T) ->
456        Result<(), Self::Error>
457    {
458        if self.se.config.is_named {
459            encode::write_str(self.se.get_mut(), key)?;
460            value.serialize(&mut *self.se)
461        } else {
462            value.serialize(&mut *self.se)
463        }
464    }
465
466    #[inline(always)]
467    fn end(self) -> Result<Self::Ok, Self::Error> {
468        Ok(())
469    }
470}
471
472/// Contains a `Serializer` for sequences and maps whose length is not yet known
473/// and a counter for the number of elements that are encoded by the `Serializer`.
474#[derive(Debug)]
475struct UnknownLengthCompound {
476    se: Serializer<Vec<u8>, DefaultConfig>,
477    elem_count: u32,
478}
479
480impl<W, C: SerializerConfig> From<&Serializer<W, C>> for UnknownLengthCompound {
481    fn from(se: &Serializer<W, C>) -> Self {
482        Self {
483            se: Serializer {
484                wr: Vec::with_capacity(128),
485                config: RuntimeConfig::new(se.config),
486                depth: se.depth,
487                _back_compat_config: PhantomData,
488            },
489            elem_count: 0
490        }
491    }
492}
493
494/// Contains a `Serializer` for encoding elements of sequences and maps.
495///
496/// # Note
497///
498/// If , for example, a field inside a struct is tagged with `#serde(flatten)` the total number of
499/// fields of this struct will be unknown to serde because flattened fields may have name clashes
500/// and then will be overwritten. So, serde wants to serialize the struct as a map with an unknown
501/// length.
502///
503/// For the described case a `UnknownLengthCompound` is used to encode the elements. On `end()`
504/// the counted length and the encoded elements will be written to the `Serializer`. A caveat is,
505/// that structs that contain flattened fields arem always written as a map, even when compact
506/// representaion is desired.
507///
508/// Otherwise, if the length is known, the elements will be encoded directly by the `Serializer`.
509#[derive(Debug)]
510#[doc(hidden)]
511pub struct MaybeUnknownLengthCompound<'a, W, C> {
512    se: &'a mut Serializer<W, C>,
513    compound: Option<UnknownLengthCompound>,
514}
515
516impl<'a, W: Write + 'a, C: SerializerConfig> SerializeSeq for MaybeUnknownLengthCompound<'a, W, C> {
517    type Ok = ();
518    type Error = Error;
519
520    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
521        match self.compound.as_mut() {
522            None => value.serialize(&mut *self.se),
523            Some(buf) => {
524                value.serialize(&mut buf.se)?;
525                buf.elem_count += 1;
526                Ok(())
527            }
528        }
529    }
530
531    fn end(self) -> Result<Self::Ok, Self::Error> {
532        if let Some(compound) = self.compound {
533            encode::write_array_len(&mut self.se.wr, compound.elem_count)?;
534            self.se.wr.write_all(&compound.se.into_inner())
535                .map_err(ValueWriteError::InvalidDataWrite)?;
536        }
537        Ok(())
538    }
539}
540
541impl<'a, W: Write + 'a, C: SerializerConfig> SerializeMap for MaybeUnknownLengthCompound<'a, W, C> {
542    type Ok = ();
543    type Error = Error;
544
545    fn serialize_key<T: ?Sized + Serialize>(&mut self, key: &T) -> Result<(), Self::Error> {
546        <Self as SerializeSeq>::serialize_element(self, key)
547    }
548
549    fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
550        <Self as SerializeSeq>::serialize_element(self, value)
551    }
552
553    fn end(self) -> Result<Self::Ok, Self::Error> {
554        if let Some(compound) = self.compound {
555            encode::write_map_len(&mut self.se.wr, compound.elem_count / 2)?;
556            self.se.wr.write_all(&compound.se.into_inner())
557                .map_err(ValueWriteError::InvalidDataWrite)?;
558        }
559        Ok(())
560    }
561}
562
563impl<'a, W, C> serde::Serializer for &'a mut Serializer<W, C>
564where
565    W: Write,
566    C: SerializerConfig,
567{
568    type Ok = ();
569    type Error = Error;
570
571    type SerializeSeq = MaybeUnknownLengthCompound<'a, W, C>;
572    type SerializeTuple = Tuple<'a, W, C>;
573    type SerializeTupleStruct = Compound<'a, W, C>;
574    type SerializeTupleVariant = Compound<'a, W, C>;
575    type SerializeMap = MaybeUnknownLengthCompound<'a, W, C>;
576    type SerializeStruct = Compound<'a, W, C>;
577    type SerializeStructVariant = Compound<'a, W, C>;
578
579    #[inline]
580    fn is_human_readable(&self) -> bool {
581        self.config.is_human_readable
582    }
583
584    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
585        encode::write_bool(&mut self.wr, v)
586            .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidMarkerWrite(err)))
587    }
588
589    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
590        self.serialize_i64(i64::from(v))
591    }
592
593    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
594        self.serialize_i64(i64::from(v))
595    }
596
597    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
598        self.serialize_i64(i64::from(v))
599    }
600
601    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
602        encode::write_sint(&mut self.wr, v)?;
603        Ok(())
604    }
605
606    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
607        self.serialize_bytes(&v.to_be_bytes())
608    }
609
610    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
611        self.serialize_u64(u64::from(v))
612    }
613
614    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
615        self.serialize_u64(u64::from(v))
616    }
617
618    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
619        self.serialize_u64(u64::from(v))
620    }
621
622    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
623        encode::write_uint(&mut self.wr, v)?;
624        Ok(())
625    }
626
627    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
628        self.serialize_bytes(&v.to_be_bytes())
629    }
630
631    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
632        encode::write_f32(&mut self.wr, v)?;
633        Ok(())
634    }
635
636    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
637        encode::write_f64(&mut self.wr, v)?;
638        Ok(())
639    }
640
641    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
642        // A char encoded as UTF-8 takes 4 bytes at most.
643        let mut buf = [0; 4];
644        self.serialize_str(v.encode_utf8(&mut buf))
645    }
646
647    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
648        encode::write_str(&mut self.wr, v)?;
649        Ok(())
650    }
651
652    fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
653        Ok(encode::write_bin(&mut self.wr, value)?)
654    }
655
656    fn serialize_none(self) -> Result<(), Self::Error> {
657        self.serialize_unit()
658    }
659
660    fn serialize_some<T: ?Sized + serde::Serialize>(self, v: &T) -> Result<(), Self::Error> {
661        v.serialize(self)
662    }
663
664    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
665        encode::write_nil(&mut self.wr)
666            .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidMarkerWrite(err)))
667    }
668
669    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
670        encode::write_array_len(&mut self.wr, 0)?;
671        Ok(())
672    }
673
674    fn serialize_unit_variant(self, _name: &str, _: u32, variant: &'static str) ->
675        Result<Self::Ok, Self::Error>
676    {
677        self.serialize_str(variant)
678    }
679
680    fn serialize_newtype_struct<T: ?Sized + serde::Serialize>(self, name: &'static str, value: &T) -> Result<(), Self::Error> {
681        if name == MSGPACK_EXT_STRUCT_NAME {
682            let mut ext_se = ExtSerializer::new(self);
683            value.serialize(&mut ext_se)?;
684
685            return ext_se.end();
686        }
687
688        // Encode as if it's inner type.
689        value.serialize(self)
690    }
691
692    fn serialize_newtype_variant<T: ?Sized + serde::Serialize>(self, _name: &'static str, _: u32, variant: &'static str, value: &T) -> Result<Self::Ok, Self::Error> {
693        // encode as a map from variant idx to its attributed data, like: {idx => value}
694        encode::write_map_len(&mut self.wr, 1)?;
695        self.serialize_str(variant)?;
696        value.serialize(self)
697    }
698
699    #[inline]
700    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> {
701        self.maybe_unknown_len_compound(len.map(|len| len as u32), |wr, len| encode::write_array_len(wr, len))
702    }
703
704    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
705        Ok(Tuple {
706            buf: if self.config.bytes == BytesMode::ForceAll && len > 0 {
707                Some(Vec::new())
708            } else {
709                encode::write_array_len(&mut self.wr, len as u32)?;
710                None
711            },
712            len: len as u32,
713            se: self,
714        })
715    }
716
717    fn serialize_tuple_struct(self, _name: &'static str, len: usize) ->
718        Result<Self::SerializeTupleStruct, Self::Error>
719    {
720        encode::write_array_len(&mut self.wr, len as u32)?;
721
722        self.compound()
723    }
724
725    fn serialize_tuple_variant(self, _name: &'static str, _: u32, variant: &'static str, len: usize) ->
726        Result<Self::SerializeTupleVariant, Error>
727    {
728        // encode as a map from variant idx to a sequence of its attributed data, like: {idx => [v1,...,vN]}
729        encode::write_map_len(&mut self.wr, 1)?;
730        self.serialize_str(variant)?;
731        encode::write_array_len(&mut self.wr, len as u32)?;
732        self.compound()
733    }
734
735    #[inline]
736    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Error> {
737        self.maybe_unknown_len_compound(len.map(|len| len as u32), |wr, len| encode::write_map_len(wr, len))
738    }
739
740    fn serialize_struct(self, _name: &'static str, len: usize) ->
741        Result<Self::SerializeStruct, Self::Error>
742    {
743        if self.config.is_named {
744            encode::write_map_len(self.get_mut(), len as u32)?;
745        } else {
746            encode::write_array_len(self.get_mut(), len as u32)?;
747        }
748        self.compound()
749    }
750
751    fn serialize_struct_variant(self, name: &'static str, _: u32, variant: &'static str, len: usize) ->
752        Result<Self::SerializeStructVariant, Error>
753    {
754        // encode as a map from variant idx to a sequence of its attributed data, like: {idx => [v1,...,vN]}
755        encode::write_map_len(&mut self.wr, 1)?;
756        self.serialize_str(variant)?;
757        self.serialize_struct(name, len)
758    }
759
760    fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> where I: IntoIterator, I::Item: Serialize {
761        let iter = iter.into_iter();
762        let len = match iter.size_hint() {
763            (lo, Some(hi)) if lo == hi && lo <= u32::MAX as usize => Some(lo as u32),
764            _ => None,
765        };
766
767        const MAX_ITER_SIZE: usize = std::mem::size_of::<<&[u8] as IntoIterator>::IntoIter>();
768        const ITEM_PTR_SIZE: usize = std::mem::size_of::<&u8>();
769
770        // Estimate whether the input is `&[u8]` or similar (hacky, because Rust lacks proper specialization)
771        let might_be_a_bytes_iter = (std::mem::size_of::<I::Item>() == 1 || std::mem::size_of::<I::Item>() == ITEM_PTR_SIZE)
772            // Complex types like HashSet<u8> don't support reading bytes.
773            // The simplest iterator is ptr+len.
774            && std::mem::size_of::<I::IntoIter>() <= MAX_ITER_SIZE;
775
776        let mut iter = iter.peekable();
777        if might_be_a_bytes_iter && self.config.bytes != BytesMode::Normal {
778            if let Some(len) = len {
779                // The `OnlyBytes` serializer emits `Err` for everything except `u8`
780                if iter.peek().map_or(false, |item| item.serialize(OnlyBytes).is_ok()) {
781                    return self.bytes_from_iter(iter, len);
782                }
783            }
784        }
785
786        let mut serializer = self.serialize_seq(len.map(|len| len as usize))?;
787        iter.try_for_each(|item| serializer.serialize_element(&item))?;
788        SerializeSeq::end(serializer)
789    }
790}
791
792impl<W: Write, C: SerializerConfig> Serializer<W, C> {
793    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 {
794        encode::write_bin_len(&mut self.wr, len)?;
795        iter.try_for_each(|item| {
796            self.wr.write(std::slice::from_ref(&item.serialize(OnlyBytes)
797                .map_err(|_| Error::InvalidDataModel("BytesMode"))?))
798                .map_err(ValueWriteError::InvalidDataWrite)?;
799             Ok(())
800        })
801    }
802}
803
804impl<'a, W: Write + 'a> serde::Serializer for &mut ExtFieldSerializer<'a, W> {
805    type Ok = ();
806    type Error = Error;
807
808    type SerializeSeq = serde::ser::Impossible<(), Error>;
809    type SerializeTuple = serde::ser::Impossible<(), Error>;
810    type SerializeTupleStruct = serde::ser::Impossible<(), Error>;
811    type SerializeTupleVariant = serde::ser::Impossible<(), Error>;
812    type SerializeMap = serde::ser::Impossible<(), Error>;
813    type SerializeStruct = serde::ser::Impossible<(), Error>;
814    type SerializeStructVariant = serde::ser::Impossible<(), Error>;
815
816    #[inline]
817    fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
818        if self.tag.is_none() {
819            self.tag.replace(value);
820            Ok(())
821        } else {
822            Err(Error::InvalidDataModel("expected i8 and bytes"))
823        }
824    }
825
826    #[inline]
827    fn serialize_bytes(self, val: &[u8]) -> Result<Self::Ok, Self::Error> {
828        if let Some(tag) = self.tag.take() {
829            encode::write_ext_meta(self.wr, val.len() as u32, tag)?;
830            self.wr
831                .write_all(val)
832                .map_err(|err| Error::InvalidValueWrite(ValueWriteError::InvalidDataWrite(err)))?;
833
834            self.finish = true;
835
836            Ok(())
837        } else {
838            Err(Error::InvalidDataModel("expected i8 and bytes"))
839        }
840    }
841
842    #[inline]
843    fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
844        Err(Error::InvalidDataModel("expected i8 and bytes"))
845    }
846
847    #[inline]
848    fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
849        Err(Error::InvalidDataModel("expected i8 and bytes"))
850    }
851
852    #[inline]
853    fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
854        Err(Error::InvalidDataModel("expected i8 and bytes"))
855    }
856
857    #[inline]
858    fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
859        Err(Error::InvalidDataModel("expected i8 and bytes"))
860    }
861
862    #[inline]
863    fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
864        Err(Error::InvalidDataModel("expected i8 and bytes"))
865    }
866
867    #[inline]
868    fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
869        Err(Error::InvalidDataModel("expected i8 and bytes"))
870    }
871
872    #[inline]
873    fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
874        Err(Error::InvalidDataModel("expected i8 and bytes"))
875    }
876
877    #[inline]
878    fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
879        Err(Error::InvalidDataModel("expected i8 and bytes"))
880    }
881
882    #[inline]
883    fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
884        Err(Error::InvalidDataModel("expected i8 and bytes"))
885    }
886
887    #[inline]
888    fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
889        Err(Error::InvalidDataModel("expected i8 and bytes"))
890    }
891
892    #[inline]
893    fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
894        Err(Error::InvalidDataModel("expected i8 and bytes"))
895    }
896
897    #[inline]
898    fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
899        Err(Error::InvalidDataModel("expected i8 and bytes"))
900    }
901
902    #[inline]
903    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
904        Err(Error::InvalidDataModel("expected i8 and bytes"))
905    }
906
907    #[inline]
908    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
909        Err(Error::InvalidDataModel("expected i8 and bytes"))
910    }
911
912    #[inline]
913    fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
914        Err(Error::InvalidDataModel("expected i8 and bytes"))
915    }
916
917    #[inline]
918    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
919        where T: Serialize
920    {
921        Err(Error::InvalidDataModel("expected i8 and bytes"))
922    }
923
924    fn serialize_newtype_variant<T: ?Sized>(self, _name: &'static str, _idx: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
925        where T: Serialize
926    {
927        Err(Error::InvalidDataModel("expected i8 and bytes"))
928    }
929
930    #[inline]
931    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
932        Err(Error::InvalidDataModel("expected i8 and bytes"))
933    }
934
935    #[inline]
936    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
937        where T: Serialize
938    {
939        Err(Error::InvalidDataModel("expected i8 and bytes"))
940    }
941
942    #[inline]
943    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
944        Err(Error::InvalidDataModel("expected i8 and bytes"))
945    }
946
947    #[inline]
948    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
949        Err(Error::InvalidDataModel("expected i8 and bytes"))
950    }
951
952    #[inline]
953    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct, Error> {
954        Err(Error::InvalidDataModel("expected i8 and bytes"))
955    }
956
957    #[inline]
958    fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant, Error> {
959        Err(Error::InvalidDataModel("expected i8 and bytes"))
960    }
961
962    #[inline]
963    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
964        Err(Error::InvalidDataModel("expected i8 and bytes"))
965    }
966
967    #[inline]
968    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct, Error> {
969        Err(Error::InvalidDataModel("expected i8 and bytes"))
970    }
971
972    #[inline]
973    fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant, Error> {
974        Err(Error::InvalidDataModel("expected i8 and bytes"))
975    }
976}
977
978impl<'a, W: Write + 'a> serde::ser::Serializer for &mut ExtSerializer<'a, W> {
979    type Ok = ();
980    type Error = Error;
981
982    type SerializeSeq = serde::ser::Impossible<(), Error>;
983    type SerializeTuple = Self;
984    type SerializeTupleStruct = serde::ser::Impossible<(), Error>;
985    type SerializeTupleVariant = serde::ser::Impossible<(), Error>;
986    type SerializeMap = serde::ser::Impossible<(), Error>;
987    type SerializeStruct = serde::ser::Impossible<(), Error>;
988    type SerializeStructVariant = serde::ser::Impossible<(), Error>;
989
990    #[inline]
991    fn serialize_bytes(self, _val: &[u8]) -> Result<Self::Ok, Self::Error> {
992        Err(Error::InvalidDataModel("expected tuple"))
993    }
994
995    #[inline]
996    fn serialize_bool(self, _val: bool) -> Result<Self::Ok, Self::Error> {
997        Err(Error::InvalidDataModel("expected tuple"))
998    }
999
1000    #[inline]
1001    fn serialize_i8(self, _value: i8) -> Result<Self::Ok, Self::Error> {
1002        Err(Error::InvalidDataModel("expected tuple"))
1003    }
1004
1005    #[inline]
1006    fn serialize_i16(self, _val: i16) -> Result<Self::Ok, Self::Error> {
1007        Err(Error::InvalidDataModel("expected tuple"))
1008    }
1009
1010    #[inline]
1011    fn serialize_i32(self, _val: i32) -> Result<Self::Ok, Self::Error> {
1012        Err(Error::InvalidDataModel("expected tuple"))
1013    }
1014
1015    #[inline]
1016    fn serialize_i64(self, _val: i64) -> Result<Self::Ok, Self::Error> {
1017        Err(Error::InvalidDataModel("expected tuple"))
1018    }
1019
1020    #[inline]
1021    fn serialize_u8(self, _val: u8) -> Result<Self::Ok, Self::Error> {
1022        Err(Error::InvalidDataModel("expected tuple"))
1023    }
1024
1025    #[inline]
1026    fn serialize_u16(self, _val: u16) -> Result<Self::Ok, Self::Error> {
1027        Err(Error::InvalidDataModel("expected tuple"))
1028    }
1029
1030    #[inline]
1031    fn serialize_u32(self, _val: u32) -> Result<Self::Ok, Self::Error> {
1032        Err(Error::InvalidDataModel("expected tuple"))
1033    }
1034
1035    #[inline]
1036    fn serialize_u64(self, _val: u64) -> Result<Self::Ok, Self::Error> {
1037        Err(Error::InvalidDataModel("expected tuple"))
1038    }
1039
1040    #[inline]
1041    fn serialize_f32(self, _val: f32) -> Result<Self::Ok, Self::Error> {
1042        Err(Error::InvalidDataModel("expected tuple"))
1043    }
1044
1045    #[inline]
1046    fn serialize_f64(self, _val: f64) -> Result<Self::Ok, Self::Error> {
1047        Err(Error::InvalidDataModel("expected tuple"))
1048    }
1049
1050    #[inline]
1051    fn serialize_char(self, _val: char) -> Result<Self::Ok, Self::Error> {
1052        Err(Error::InvalidDataModel("expected tuple"))
1053    }
1054
1055    #[inline]
1056    fn serialize_str(self, _val: &str) -> Result<Self::Ok, Self::Error> {
1057        Err(Error::InvalidDataModel("expected tuple"))
1058    }
1059
1060    #[inline]
1061    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
1062        Err(Error::InvalidDataModel("expected tuple"))
1063    }
1064
1065    #[inline]
1066    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
1067        Err(Error::InvalidDataModel("expected tuple"))
1068    }
1069
1070    #[inline]
1071    fn serialize_unit_variant(self, _name: &'static str, _idx: u32, _variant: &'static str) -> Result<Self::Ok, Self::Error> {
1072        Err(Error::InvalidDataModel("expected tuple"))
1073    }
1074
1075    #[inline]
1076    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
1077        where T: Serialize
1078    {
1079        Err(Error::InvalidDataModel("expected tuple"))
1080    }
1081
1082    #[inline]
1083    fn serialize_newtype_variant<T: ?Sized>(self, _name: &'static str, _idx: u32, _variant: &'static str, _value: &T) -> Result<Self::Ok, Self::Error>
1084        where T: Serialize
1085    {
1086        Err(Error::InvalidDataModel("expected tuple"))
1087    }
1088
1089    #[inline]
1090    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1091        Err(Error::InvalidDataModel("expected tuple"))
1092    }
1093
1094    #[inline]
1095    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
1096        where T: Serialize
1097    {
1098        Err(Error::InvalidDataModel("expected tuple"))
1099    }
1100
1101    #[inline]
1102    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1103        Err(Error::InvalidDataModel("expected tuple"))
1104    }
1105
1106    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Error> {
1107        // FIXME check len
1108        self.tuple_received = true;
1109
1110        Ok(self)
1111    }
1112
1113    #[inline]
1114    fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeTupleStruct, Error> {
1115        Err(Error::InvalidDataModel("expected tuple"))
1116    }
1117
1118    #[inline]
1119    fn serialize_tuple_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeTupleVariant, Error> {
1120        Err(Error::InvalidDataModel("expected tuple"))
1121    }
1122
1123    #[inline]
1124    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> {
1125        Err(Error::InvalidDataModel("expected tuple"))
1126    }
1127
1128    #[inline]
1129    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct, Error> {
1130        Err(Error::InvalidDataModel("expected tuple"))
1131    }
1132
1133    #[inline]
1134    fn serialize_struct_variant(self, _name: &'static str, _idx: u32, _variant: &'static str, _len: usize) -> Result<Self::SerializeStructVariant, Error> {
1135        Err(Error::InvalidDataModel("expected tuple"))
1136    }
1137}
1138
1139impl<'a, W: Write + 'a> SerializeTuple for &mut ExtSerializer<'a, W> {
1140    type Ok = ();
1141    type Error = Error;
1142
1143    #[inline]
1144    fn serialize_element<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), Self::Error> {
1145        value.serialize(&mut self.fields_se)
1146    }
1147
1148    #[inline(always)]
1149    fn end(self) -> Result<Self::Ok, Self::Error> {
1150        Ok(())
1151    }
1152}
1153
1154impl<'a, W: Write + 'a> ExtSerializer<'a, W> {
1155    #[inline]
1156    fn new<C>(ser: &'a mut Serializer<W, C>) -> Self {
1157        Self {
1158            fields_se: ExtFieldSerializer::new(ser),
1159            tuple_received: false,
1160        }
1161    }
1162
1163    #[inline]
1164    fn end(self) -> Result<(), Error> {
1165        if !self.tuple_received {
1166            Err(Error::InvalidDataModel("expected tuple"))
1167        } else {
1168            self.fields_se.end()
1169        }
1170    }
1171}
1172
1173impl<'a, W: Write + 'a> ExtFieldSerializer<'a, W> {
1174    #[inline]
1175    fn new<C>(ser: &'a mut Serializer<W, C>) -> Self {
1176        Self {
1177            wr: UnderlyingWrite::get_mut(ser),
1178            tag: None,
1179            finish: false,
1180        }
1181    }
1182
1183    #[inline]
1184    fn end(self) -> Result<(), Error> {
1185        if self.finish {
1186            Ok(())
1187        } else {
1188            Err(Error::InvalidDataModel("expected i8 and bytes"))
1189        }
1190    }
1191}
1192
1193/// Serialize the given data structure as MessagePack into the I/O stream.
1194/// This function uses compact representation - structures as arrays
1195///
1196/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1197#[inline]
1198pub fn write<W, T>(wr: &mut W, val: &T) -> Result<(), Error>
1199where
1200    W: Write + ?Sized,
1201    T: Serialize + ?Sized,
1202{
1203    val.serialize(&mut Serializer::new(wr))
1204}
1205
1206/// Serialize the given data structure as MessagePack into the I/O stream.
1207/// This function serializes structures as maps
1208///
1209/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1210pub fn write_named<W, T>(wr: &mut W, val: &T) -> Result<(), Error>
1211where
1212    W: Write + ?Sized,
1213    T: Serialize + ?Sized,
1214{
1215    let mut se = Serializer::new(wr);
1216    // Avoids another monomorphisation of `StructMapConfig`
1217    se.config = RuntimeConfig::new(StructMapConfig::new(se.config));
1218    val.serialize(&mut se)
1219}
1220
1221/// Serialize the given data structure as a MessagePack byte vector.
1222/// This method uses compact representation, structs are serialized as arrays
1223///
1224/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1225#[inline]
1226pub fn to_vec<T>(val: &T) -> Result<Vec<u8>, Error>
1227where
1228    T: Serialize + ?Sized,
1229{
1230    let mut wr = FallibleWriter(Vec::new());
1231    write(&mut wr, val)?;
1232    Ok(wr.0)
1233}
1234
1235/// Serializes data structure into byte vector as a map
1236/// Resulting MessagePack message will contain field names
1237///
1238/// # Errors
1239///
1240/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1241#[inline]
1242pub fn to_vec_named<T>(val: &T) -> Result<Vec<u8>, Error>
1243where
1244    T: Serialize + ?Sized,
1245{
1246    let mut wr = FallibleWriter(Vec::new());
1247    write_named(&mut wr, val)?;
1248    Ok(wr.0)
1249}
1250
1251#[repr(transparent)]
1252struct FallibleWriter(Vec<u8>);
1253
1254impl Write for FallibleWriter {
1255    #[inline(always)]
1256    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1257        self.write_all(buf)?;
1258        Ok(buf.len())
1259    }
1260
1261    #[inline]
1262    fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
1263        self.0.try_reserve(buf.len()).map_err(|_| std::io::ErrorKind::OutOfMemory)?;
1264        self.0.extend_from_slice(buf);
1265        Ok(())
1266    }
1267
1268    fn flush(&mut self) -> std::io::Result<()> {
1269        Ok(())
1270    }
1271}