Coverage Report

Created: 2026-06-30 07:02

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