postcard/ser/
serializer.rs

1use serde::{ser, Serialize};
2
3use crate::error::{Error, Result};
4use crate::ser::flavors::Flavor;
5use crate::varint::*;
6
7/// A `serde` compatible serializer, generic over "Flavors" of serializing plugins.
8///
9/// It should rarely be necessary to directly use this type unless you are implementing your
10/// own [`SerFlavor`].
11///
12/// See the docs for [`SerFlavor`] for more information about "flavors" of serialization
13///
14/// [`SerFlavor`]: crate::ser_flavors::Flavor
15pub struct Serializer<F>
16where
17    F: Flavor,
18{
19    /// This is the Flavor(s) that will be used to modify or store any bytes generated
20    /// by serialization
21    pub output: F,
22}
23
24impl<F: Flavor> Serializer<F> {
25    /// Attempt to push a variably encoded [usize] into the output data stream
26    #[inline]
27    pub(crate) fn try_push_varint_usize(&mut self, data: usize) -> Result<()> {
28        let mut buf = [0u8; varint_max::<usize>()];
29        let used_buf = varint_usize(data, &mut buf);
30        self.output.try_extend(used_buf)
31    }
32
33    /// Attempt to push a variably encoded [u128] into the output data stream
34    #[inline]
35    pub(crate) fn try_push_varint_u128(&mut self, data: u128) -> Result<()> {
36        let mut buf = [0u8; varint_max::<u128>()];
37        let used_buf = varint_u128(data, &mut buf);
38        self.output.try_extend(used_buf)
39    }
40
41    /// Attempt to push a variably encoded [u64] into the output data stream
42    #[inline]
43    pub(crate) fn try_push_varint_u64(&mut self, data: u64) -> Result<()> {
44        let mut buf = [0u8; varint_max::<u64>()];
45        let used_buf = varint_u64(data, &mut buf);
46        self.output.try_extend(used_buf)
47    }
48
49    /// Attempt to push a variably encoded [u32] into the output data stream
50    #[inline]
51    pub(crate) fn try_push_varint_u32(&mut self, data: u32) -> Result<()> {
52        let mut buf = [0u8; varint_max::<u32>()];
53        let used_buf = varint_u32(data, &mut buf);
54        self.output.try_extend(used_buf)
55    }
56
57    /// Attempt to push a variably encoded [u16] into the output data stream
58    #[inline]
59    pub(crate) fn try_push_varint_u16(&mut self, data: u16) -> Result<()> {
60        let mut buf = [0u8; varint_max::<u16>()];
61        let used_buf = varint_u16(data, &mut buf);
62        self.output.try_extend(used_buf)
63    }
64}
65
66impl<F> ser::Serializer for &mut Serializer<F>
67where
68    F: Flavor,
69{
70    type Ok = ();
71
72    type Error = Error;
73
74    // Associated types for keeping track of additional state while serializing
75    // compound data structures like sequences and maps. In this case no
76    // additional state is required beyond what is already stored in the
77    // Serializer struct.
78    type SerializeSeq = Self;
79    type SerializeTuple = Self;
80    type SerializeTupleStruct = Self;
81    type SerializeTupleVariant = Self;
82    type SerializeMap = Self;
83    type SerializeStruct = Self;
84    type SerializeStructVariant = Self;
85
86    #[inline]
87    fn is_human_readable(&self) -> bool {
88        false
89    }
90
91    #[inline]
92    fn serialize_bool(self, v: bool) -> Result<()> {
93        self.serialize_u8(if v { 1 } else { 0 })
94    }
95
96    #[inline]
97    fn serialize_i8(self, v: i8) -> Result<()> {
98        self.serialize_u8(v.to_le_bytes()[0])
99    }
100
101    #[inline]
102    fn serialize_i16(self, v: i16) -> Result<()> {
103        let zzv = zig_zag_i16(v);
104        self.try_push_varint_u16(zzv)
105            .map_err(|_| Error::SerializeBufferFull)
106    }
107
108    #[inline]
109    fn serialize_i32(self, v: i32) -> Result<()> {
110        let zzv = zig_zag_i32(v);
111        self.try_push_varint_u32(zzv)
112            .map_err(|_| Error::SerializeBufferFull)
113    }
114
115    #[inline]
116    fn serialize_i64(self, v: i64) -> Result<()> {
117        let zzv = zig_zag_i64(v);
118        self.try_push_varint_u64(zzv)
119            .map_err(|_| Error::SerializeBufferFull)
120    }
121
122    #[inline]
123    fn serialize_i128(self, v: i128) -> Result<()> {
124        let zzv = zig_zag_i128(v);
125        self.try_push_varint_u128(zzv)
126            .map_err(|_| Error::SerializeBufferFull)
127    }
128
129    #[inline]
130    fn serialize_u8(self, v: u8) -> Result<()> {
131        self.output
132            .try_push(v)
133            .map_err(|_| Error::SerializeBufferFull)
134    }
135
136    #[inline]
137    fn serialize_u16(self, v: u16) -> Result<()> {
138        self.try_push_varint_u16(v)
139            .map_err(|_| Error::SerializeBufferFull)
140    }
141
142    #[inline]
143    fn serialize_u32(self, v: u32) -> Result<()> {
144        self.try_push_varint_u32(v)
145            .map_err(|_| Error::SerializeBufferFull)
146    }
147
148    #[inline]
149    fn serialize_u64(self, v: u64) -> Result<()> {
150        self.try_push_varint_u64(v)
151            .map_err(|_| Error::SerializeBufferFull)
152    }
153
154    #[inline]
155    fn serialize_u128(self, v: u128) -> Result<()> {
156        self.try_push_varint_u128(v)
157            .map_err(|_| Error::SerializeBufferFull)
158    }
159
160    #[inline]
161    fn serialize_f32(self, v: f32) -> Result<()> {
162        let buf = v.to_bits().to_le_bytes();
163        self.output
164            .try_extend(&buf)
165            .map_err(|_| Error::SerializeBufferFull)
166    }
167
168    #[inline]
169    fn serialize_f64(self, v: f64) -> Result<()> {
170        let buf = v.to_bits().to_le_bytes();
171        self.output
172            .try_extend(&buf)
173            .map_err(|_| Error::SerializeBufferFull)
174    }
175
176    #[inline]
177    fn serialize_char(self, v: char) -> Result<()> {
178        let mut buf = [0u8; 4];
179        let strsl = v.encode_utf8(&mut buf);
180        strsl.serialize(self)
181    }
182
183    #[inline]
184    fn serialize_str(self, v: &str) -> Result<()> {
185        self.try_push_varint_usize(v.len())
186            .map_err(|_| Error::SerializeBufferFull)?;
187        self.output
188            .try_extend(v.as_bytes())
189            .map_err(|_| Error::SerializeBufferFull)?;
190        Ok(())
191    }
192
193    #[inline]
194    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
195        self.try_push_varint_usize(v.len())
196            .map_err(|_| Error::SerializeBufferFull)?;
197        self.output
198            .try_extend(v)
199            .map_err(|_| Error::SerializeBufferFull)
200    }
201
202    #[inline]
203    fn serialize_none(self) -> Result<()> {
204        self.serialize_u8(0)
205    }
206
207    #[inline]
208    fn serialize_some<T>(self, value: &T) -> Result<()>
209    where
210        T: ?Sized + Serialize,
211    {
212        self.serialize_u8(1)?;
213        value.serialize(self)
214    }
215
216    #[inline]
217    fn serialize_unit(self) -> Result<()> {
218        Ok(())
219    }
220
221    #[inline]
222    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
223        Ok(())
224    }
225
226    #[inline]
227    fn serialize_unit_variant(
228        self,
229        _name: &'static str,
230        variant_index: u32,
231        _variant: &'static str,
232    ) -> Result<()> {
233        self.try_push_varint_u32(variant_index)
234            .map_err(|_| Error::SerializeBufferFull)
235    }
236
237    #[inline]
238    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
239    where
240        T: ?Sized + Serialize,
241    {
242        value.serialize(self)
243    }
244
245    #[inline]
246    fn serialize_newtype_variant<T>(
247        self,
248        _name: &'static str,
249        variant_index: u32,
250        _variant: &'static str,
251        value: &T,
252    ) -> Result<()>
253    where
254        T: ?Sized + Serialize,
255    {
256        self.try_push_varint_u32(variant_index)
257            .map_err(|_| Error::SerializeBufferFull)?;
258        value.serialize(self)
259    }
260
261    #[inline]
262    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
263        self.try_push_varint_usize(len.ok_or(Error::SerializeSeqLengthUnknown)?)
264            .map_err(|_| Error::SerializeBufferFull)?;
265        Ok(self)
266    }
267
268    #[inline]
269    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
270        Ok(self)
271    }
272
273    #[inline]
274    fn serialize_tuple_struct(
275        self,
276        _name: &'static str,
277        _len: usize,
278    ) -> Result<Self::SerializeTupleStruct> {
279        Ok(self)
280    }
281
282    #[inline]
283    fn serialize_tuple_variant(
284        self,
285        _name: &'static str,
286        variant_index: u32,
287        _variant: &'static str,
288        _len: usize,
289    ) -> Result<Self::SerializeTupleVariant> {
290        self.try_push_varint_u32(variant_index)
291            .map_err(|_| Error::SerializeBufferFull)?;
292        Ok(self)
293    }
294
295    #[inline]
296    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
297        self.try_push_varint_usize(len.ok_or(Error::SerializeSeqLengthUnknown)?)
298            .map_err(|_| Error::SerializeBufferFull)?;
299        Ok(self)
300    }
301
302    #[inline]
303    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
304        Ok(self)
305    }
306
307    #[inline]
308    fn serialize_struct_variant(
309        self,
310        _name: &'static str,
311        variant_index: u32,
312        _variant: &'static str,
313        _len: usize,
314    ) -> Result<Self::SerializeStructVariant> {
315        self.try_push_varint_u32(variant_index)
316            .map_err(|_| Error::SerializeBufferFull)?;
317        Ok(self)
318    }
319
320    #[inline]
321    fn collect_str<T>(self, value: &T) -> Result<Self::Ok>
322    where
323        T: core::fmt::Display + ?Sized,
324    {
325        use core::fmt::Write;
326
327        // Unfortunately, we need to know the size of the serialized data before
328        // we can place it into the output. In order to do this, we run the formatting
329        // of the output data TWICE, the first time to determine the length, the
330        // second time to actually format the data
331        //
332        // There are potentially other ways to do this, such as:
333        //
334        // * Reserving a fixed max size, such as 5 bytes, for the length field, and
335        //     leaving non-canonical trailing zeroes at the end. This would work up
336        //     to some reasonable length, but might have some portability vs max size
337        //     tradeoffs, e.g. 64KiB if we pick 3 bytes, or 4GiB if we pick 5 bytes
338        // * Expose some kind of "memmove" capability to flavors, to allow us to
339        //     format into the buffer, then "scoot over" that many times.
340        //
341        // Despite the current approaches downside in speed, it is likely flexible
342        // enough for the rare-ish case where formatting a Debug impl is necessary.
343        // This is better than the previous panicking behavior, and can be improved
344        // in the future.
345        struct CountWriter {
346            ct: usize,
347        }
348        impl Write for CountWriter {
349            fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> {
350                self.ct += s.len();
351                Ok(())
352            }
353        }
354
355        let mut ctr = CountWriter { ct: 0 };
356
357        // This is the first pass through, where we just count the length of the
358        // data that we are given
359        write!(&mut ctr, "{value}").map_err(|_| Error::CollectStrError)?;
360        let len = ctr.ct;
361        self.try_push_varint_usize(len)
362            .map_err(|_| Error::SerializeBufferFull)?;
363
364        struct FmtWriter<'a, IF>
365        where
366            IF: Flavor,
367        {
368            output: &'a mut IF,
369        }
370        impl<IF> Write for FmtWriter<'_, IF>
371        where
372            IF: Flavor,
373        {
374            fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> {
375                self.output
376                    .try_extend(s.as_bytes())
377                    .map_err(|_| core::fmt::Error)
378            }
379        }
380
381        // This second pass actually inserts the data.
382        let mut fw = FmtWriter {
383            output: &mut self.output,
384        };
385        write!(&mut fw, "{value}").map_err(|_| Error::CollectStrError)?;
386
387        Ok(())
388    }
389}
390
391impl<F> ser::SerializeSeq for &mut Serializer<F>
392where
393    F: Flavor,
394{
395    // Must match the `Ok` type of the serializer.
396    type Ok = ();
397    // Must match the `Error` type of the serializer.
398    type Error = Error;
399
400    // Serialize a single element of the sequence.
401    #[inline]
402    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
403    where
404        T: ?Sized + Serialize,
405    {
406        value.serialize(&mut **self)
407    }
408
409    // Close the sequence.
410    #[inline]
411    fn end(self) -> Result<()> {
412        Ok(())
413    }
414}
415
416impl<F> ser::SerializeTuple for &mut Serializer<F>
417where
418    F: Flavor,
419{
420    type Ok = ();
421    type Error = Error;
422
423    #[inline]
424    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
425    where
426        T: ?Sized + Serialize,
427    {
428        value.serialize(&mut **self)
429    }
430
431    #[inline]
432    fn end(self) -> Result<()> {
433        Ok(())
434    }
435}
436
437impl<F> ser::SerializeTupleStruct for &mut Serializer<F>
438where
439    F: Flavor,
440{
441    type Ok = ();
442    type Error = Error;
443
444    #[inline]
445    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
446    where
447        T: ?Sized + Serialize,
448    {
449        value.serialize(&mut **self)
450    }
451
452    #[inline]
453    fn end(self) -> Result<()> {
454        Ok(())
455    }
456}
457
458impl<F> ser::SerializeTupleVariant for &mut Serializer<F>
459where
460    F: Flavor,
461{
462    type Ok = ();
463    type Error = Error;
464
465    #[inline]
466    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
467    where
468        T: ?Sized + Serialize,
469    {
470        value.serialize(&mut **self)
471    }
472
473    #[inline]
474    fn end(self) -> Result<()> {
475        Ok(())
476    }
477}
478
479impl<F> ser::SerializeMap for &mut Serializer<F>
480where
481    F: Flavor,
482{
483    type Ok = ();
484    type Error = Error;
485
486    #[inline]
487    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
488    where
489        T: ?Sized + Serialize,
490    {
491        key.serialize(&mut **self)
492    }
493
494    #[inline]
495    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
496    where
497        T: ?Sized + Serialize,
498    {
499        value.serialize(&mut **self)
500    }
501
502    #[inline]
503    fn end(self) -> Result<()> {
504        Ok(())
505    }
506}
507
508impl<F> ser::SerializeStruct for &mut Serializer<F>
509where
510    F: Flavor,
511{
512    type Ok = ();
513    type Error = Error;
514
515    #[inline]
516    fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<()>
517    where
518        T: ?Sized + Serialize,
519    {
520        value.serialize(&mut **self)
521    }
522
523    #[inline]
524    fn end(self) -> Result<()> {
525        Ok(())
526    }
527}
528
529impl<F> ser::SerializeStructVariant for &mut Serializer<F>
530where
531    F: Flavor,
532{
533    type Ok = ();
534    type Error = Error;
535
536    #[inline]
537    fn serialize_field<T>(&mut self, _key: &'static str, value: &T) -> Result<()>
538    where
539        T: ?Sized + Serialize,
540    {
541        value.serialize(&mut **self)
542    }
543
544    #[inline]
545    fn end(self) -> Result<()> {
546        Ok(())
547    }
548}
549
550fn zig_zag_i16(n: i16) -> u16 {
551    ((n << 1) ^ (n >> 15)) as u16
552}
553
554fn zig_zag_i32(n: i32) -> u32 {
555    ((n << 1) ^ (n >> 31)) as u32
556}
557
558fn zig_zag_i64(n: i64) -> u64 {
559    ((n << 1) ^ (n >> 63)) as u64
560}
561
562fn zig_zag_i128(n: i128) -> u128 {
563    ((n << 1) ^ (n >> 127)) as u128
564}