messpack_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,
22    StructMapConfig, StructTupleConfig,
23};
24use crate::MSGPACK_EXT_STRUCT_NAME;
25
26/// This type represents all possible errors that can occur when serializing or
27/// deserializing MessagePack data.
28#[derive(Debug)]
29pub enum Error {
30    /// Failed to write a MessagePack value.
31    InvalidValueWrite(ValueWriteError),
32    //TODO: This can be removed at some point
33    /// Failed to serialize struct, sequence or map, because its length is unknown.
34    UnknownLength,
35    /// Invalid Data model, i.e. Serialize trait is not implmented correctly
36    InvalidDataModel(&'static str),
37    /// Depth limit exceeded
38    DepthLimitExceeded,
39    /// Catchall for syntax error messages.
40    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    /// Raised when there is general error when deserializing a type.
80    #[cold]
81    fn custom<T: Display>(msg: T) -> Self {
82        Self::Syntax(msg.to_string())
83    }
84}
85
86/// Obtain the underlying writer.
87pub trait UnderlyingWrite {
88    /// Underlying writer type.
89    type Write: Write;
90
91    /// Gets a reference to the underlying writer.
92    fn get_ref(&self) -> &Self::Write;
93
94    /// Gets a mutable reference to the underlying writer.
95    ///
96    /// It is inadvisable to directly write to the underlying writer.
97    fn get_mut(&mut self) -> &mut Self::Write;
98
99    /// Unwraps this `Serializer`, returning the underlying writer.
100    fn into_inner(self) -> Self::Write;
101}
102
103/// Represents MessagePack serialization implementation.
104///
105/// # Note
106///
107/// MessagePack has no specification about how to encode enum types. Thus we are free to do
108/// whatever we want, so the given choice may be not ideal for you.
109///
110/// An enum value is represented as a single-entry map whose key is the variant
111/// id and whose value is a sequence containing all associated data. If the enum
112/// does not have associated data, the sequence is empty.
113///
114/// All instances of `ErrorKind::Interrupted` are handled by this function and the underlying
115/// operation is retried.
116// TODO: Docs. Examples.
117#[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    /// Gets a reference to the underlying writer.
127    #[inline(always)]
128    pub fn get_ref(&self) -> &W {
129        &self.wr
130    }
131
132    /// Gets a mutable reference to the underlying writer.
133    ///
134    /// It is inadvisable to directly write to the underlying writer.
135    #[inline(always)]
136    pub fn get_mut(&mut self) -> &mut W {
137        &mut self.wr
138    }
139
140    /// Unwraps this `Serializer`, returning the underlying writer.
141    #[inline(always)]
142    pub fn into_inner(self) -> W {
143        self.wr
144    }
145
146    /// Changes the maximum nesting depth that is allowed.
147    ///
148    /// Currently unused.
149    #[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    /// Constructs a new `MessagePack` serializer whose output will be written to the writer
158    /// specified.
159    ///
160    /// # Note
161    ///
162    /// This is the default constructor, which returns a serializer that will serialize structs
163    /// and enums using the most compact representation.
164    #[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    /// Consumes this serializer returning the new one, which will serialize structs as a map.
207    ///
208    /// This is used, when the default struct serialization as a tuple does not fit your
209    /// requirements.
210    #[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    /// Consumes this serializer returning the new one, which will serialize structs as a tuple
227    /// without field names.
228    ///
229    /// This is the default MessagePack serialization mechanism, emitting the most compact
230    /// representation.
231    #[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    /// Consumes this serializer returning the new one, which will serialize some types in
248    /// human-readable representations (`Serializer::is_human_readable` will return `true`). Note
249    /// that the overall representation is still binary, but some types such as IP addresses will
250    /// be saved as human-readable strings.
251    ///
252    /// This is primarily useful if you need to interoperate with serializations produced by older
253    /// versions of `rmp-serde`.
254    #[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    /// Consumes this serializer returning the new one, which will serialize types as binary
271    /// (`Serializer::is_human_readable` will return `false`).
272    ///
273    /// This is the default MessagePack serialization mechanism, emitting the most compact
274    /// representation.
275    #[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    /// Prefer encoding sequences of `u8` as bytes, rather than
292    /// as a sequence of variable-size integers.
293    ///
294    /// This reduces overhead of binary data, but it may break
295    /// decodnig of some Serde types that happen to contain `[u8]`s,
296    /// but don't implement Serde's `visit_bytes`.
297    ///
298    /// ```rust
299    /// use serde::ser::Serialize;
300    /// let mut msgpack_data = Vec::new();
301    /// let mut serializer = messpack_serde::Serializer::new(&mut msgpack_data)
302    ///     .with_bytes(messpack_serde::config::BytesMode::ForceAll);
303    /// vec![255u8; 100].serialize(&mut serializer).unwrap();
304    /// ```
305    #[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/// Hack to store fixed-size arrays (which serde says are tuples)
332#[derive(Debug)]
333#[doc(hidden)]
334pub struct Tuple<'a, W, C> {
335    len: u32,
336    // can't know if all elements are u8 until the end ;(
337    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/// Part of serde serialization API.
378#[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/// Represents MessagePack serialization implementation for Ext.
393#[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/// Contains a `Serializer` for sequences and maps whose length is not yet known
505/// and a counter for the number of elements that are encoded by the `Serializer`.
506#[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/// Contains a `Serializer` for encoding elements of sequences and maps.
527///
528/// # Note
529///
530/// If , for example, a field inside a struct is tagged with `#serde(flatten)` the total number of
531/// fields of this struct will be unknown to serde because flattened fields may have name clashes
532/// and then will be overwritten. So, serde wants to serialize the struct as a map with an unknown
533/// length.
534///
535/// For the described case a `UnknownLengthCompound` is used to encode the elements. On `end()`
536/// the counted length and the encoded elements will be written to the `Serializer`. A caveat is,
537/// that structs that contain flattened fields arem always written as a map, even when compact
538/// representaion is desired.
539///
540/// Otherwise, if the length is known, the elements will be encoded directly by the `Serializer`.
541#[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        // A char encoded as UTF-8 takes 4 bytes at most.
679        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        // Encode as if it's inner type.
732        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 as a map from variant idx to its attributed data, like: {idx => value}
743        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 as a map from variant idx to a sequence of its attributed data, like: {idx => [v1,...,vN]}
786        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 as a map from variant idx to a sequence of its attributed data, like: {idx => [v1,...,vN]}
820        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        // Estimate whether the input is `&[u8]` or similar (hacky, because Rust lacks proper specialization)
840        let might_be_a_bytes_iter = (std::mem::size_of::<I::Item>() == 1 || std::mem::size_of::<I::Item>() == ITEM_PTR_SIZE)
841            // Complex types like HashSet<u8> don't support reading bytes.
842            // The simplest iterator is ptr+len.
843            && 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                // The `OnlyBytes` serializer emits `Err` for everything except `u8`
849                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        // FIXME check len
1230        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/// Serialize the given data structure as MessagePack into the I/O stream.
1336/// This function uses compact representation - structures as arrays
1337///
1338/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1339#[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
1348/// Serialize the given data structure as MessagePack into the I/O stream.
1349/// This function serializes structures as maps
1350///
1351/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1352pub 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    // Avoids another monomorphisation of `StructMapConfig`
1359    se.config = RuntimeConfig::new(StructMapConfig::new(se.config));
1360    val.serialize(&mut se)
1361}
1362
1363/// Serialize the given data structure as a MessagePack byte vector.
1364/// This method uses compact representation, structs are serialized as arrays
1365///
1366/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1367#[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/// Serializes data structure into byte vector as a map
1378/// Resulting MessagePack message will contain field names
1379///
1380/// # Errors
1381///
1382/// Serialization can fail if `T`'s implementation of `Serialize` decides to fail.
1383#[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}