bincode_thin/ser/
mod.rs

1use std::io::Write;
2use std::u32;
3
4use serde;
5
6use byteorder::WriteBytesExt;
7
8use super::internal::SizeLimit;
9use super::{Error, ErrorKind, Result};
10use config::Options;
11
12/// An Serializer that encodes values directly into a Writer.
13///
14/// The specified byte-order will impact the endianness that is
15/// used during the encoding.
16///
17/// This struct should not be used often.
18/// For most cases, prefer the `encode_into` function.
19pub(crate) struct Serializer<W, O: Options> {
20    writer: W,
21    _options: O,
22}
23
24impl<W: Write, O: Options> Serializer<W, O> {
25    /// Creates a new Serializer with the given `Write`r.
26    pub fn new(w: W, options: O) -> Serializer<W, O> {
27        Serializer {
28            writer: w,
29            _options: options,
30        }
31    }
32}
33
34impl<'a, W: Write, O: Options> serde::Serializer for &'a mut Serializer<W, O> {
35    type Ok = ();
36    type Error = Error;
37    type SerializeSeq = Compound<'a, W, O>;
38    type SerializeTuple = Compound<'a, W, O>;
39    type SerializeTupleStruct = Compound<'a, W, O>;
40    type SerializeTupleVariant = Compound<'a, W, O>;
41    type SerializeMap = Compound<'a, W, O>;
42    type SerializeStruct = Compound<'a, W, O>;
43    type SerializeStructVariant = Compound<'a, W, O>;
44
45    fn serialize_unit(self) -> Result<()> {
46        Ok(())
47    }
48
49    fn serialize_unit_struct(self, _: &'static str) -> Result<()> {
50        Ok(())
51    }
52
53    fn serialize_bool(self, v: bool) -> Result<()> {
54        self.writer
55            .write_u8(if v { 1 } else { 0 })
56            .map_err(Into::into)
57    }
58
59    fn serialize_u8(self, v: u8) -> Result<()> {
60        self.writer.write_u8(v).map_err(Into::into)
61    }
62
63    fn serialize_u16(self, v: u16) -> Result<()> {
64        self.writer.write_u16::<O::Endian>(v).map_err(Into::into)
65    }
66
67    fn serialize_u32(self, v: u32) -> Result<()> {
68        self.writer.write_u32::<O::Endian>(v).map_err(Into::into)
69    }
70
71    fn serialize_u64(self, v: u64) -> Result<()> {
72        self.writer.write_u64::<O::Endian>(v).map_err(Into::into)
73    }
74
75    fn serialize_i8(self, v: i8) -> Result<()> {
76        self.writer.write_i8(v).map_err(Into::into)
77    }
78
79    fn serialize_i16(self, v: i16) -> Result<()> {
80        self.writer.write_i16::<O::Endian>(v).map_err(Into::into)
81    }
82
83    fn serialize_i32(self, v: i32) -> Result<()> {
84        self.writer.write_i32::<O::Endian>(v).map_err(Into::into)
85    }
86
87    fn serialize_i64(self, v: i64) -> Result<()> {
88        self.writer.write_i64::<O::Endian>(v).map_err(Into::into)
89    }
90
91    #[cfg(has_i128)]
92    fn serialize_u128(self, v: u128) -> Result<()> {
93        self.writer.write_u128::<O::Endian>(v).map_err(Into::into)
94    }
95
96    #[cfg(has_i128)]
97    fn serialize_i128(self, v: i128) -> Result<()> {
98        self.writer.write_i128::<O::Endian>(v).map_err(Into::into)
99    }
100
101    serde_if_integer128! {
102        #[cfg(not(has_i128))]
103        fn serialize_u128(self, v: u128) -> Result<()> {
104            use serde::ser::Error;
105
106            let _ = v;
107            Err(Error::custom("u128 is not supported. Use Rustc ≥ 1.26."))
108        }
109
110        #[cfg(not(has_i128))]
111        fn serialize_i128(self, v: i128) -> Result<()> {
112            use serde::ser::Error;
113
114            let _ = v;
115            Err(Error::custom("i128 is not supported. Use Rustc ≥ 1.26."))
116        }
117    }
118
119    fn serialize_f32(self, v: f32) -> Result<()> {
120        self.writer.write_f32::<O::Endian>(v).map_err(Into::into)
121    }
122
123    fn serialize_f64(self, v: f64) -> Result<()> {
124        self.writer.write_f64::<O::Endian>(v).map_err(Into::into)
125    }
126
127    fn serialize_str(self, v: &str) -> Result<()> {
128        try!(self.serialize_u64(v.len() as u64));
129        self.writer.write_all(v.as_bytes()).map_err(Into::into)
130    }
131
132    fn serialize_char(self, c: char) -> Result<()> {
133        self.writer
134            .write_all(encode_utf8(c).as_slice())
135            .map_err(Into::into)
136    }
137
138    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
139        try!(self.serialize_u64(v.len() as u64));
140        self.writer.write_all(v).map_err(Into::into)
141    }
142
143    fn serialize_none(self) -> Result<()> {
144        self.writer.write_u8(0).map_err(Into::into)
145    }
146
147    fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>
148    where
149        T: serde::Serialize,
150    {
151        try!(self.writer.write_u8(1));
152        v.serialize(self)
153    }
154
155    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
156        let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
157        try!(self.serialize_u64(len as u64));
158        Ok(Compound { ser: self })
159    }
160
161    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
162        Ok(Compound { ser: self })
163    }
164
165    fn serialize_tuple_struct(
166        self,
167        _name: &'static str,
168        _len: usize,
169    ) -> Result<Self::SerializeTupleStruct> {
170        Ok(Compound { ser: self })
171    }
172
173    fn serialize_tuple_variant(
174        self,
175        _name: &'static str,
176        variant_index: u32,
177        _variant: &'static str,
178        _len: usize,
179    ) -> Result<Self::SerializeTupleVariant> {
180        assert!(variant_index < 256);
181        try!(self.serialize_u8(variant_index as u8));
182        Ok(Compound { ser: self })
183    }
184
185    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
186        let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
187        try!(self.serialize_u64(len as u64));
188        Ok(Compound { ser: self })
189    }
190
191    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
192        Ok(Compound { ser: self })
193    }
194
195    fn serialize_struct_variant(
196        self,
197        _name: &'static str,
198        variant_index: u32,
199        _variant: &'static str,
200        _len: usize,
201    ) -> Result<Self::SerializeStructVariant> {
202        assert!(variant_index < 256);
203        try!(self.serialize_u8(variant_index as u8));
204        Ok(Compound { ser: self })
205    }
206
207    fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()>
208    where
209        T: serde::ser::Serialize,
210    {
211        value.serialize(self)
212    }
213
214    fn serialize_newtype_variant<T: ?Sized>(
215        self,
216        _name: &'static str,
217        variant_index: u32,
218        _variant: &'static str,
219        value: &T,
220    ) -> Result<()>
221    where
222        T: serde::ser::Serialize,
223    {
224        assert!(variant_index < 256);
225        try!(self.serialize_u8(variant_index as u8));
226        value.serialize(self)
227    }
228
229    fn serialize_unit_variant(
230        self,
231        _name: &'static str,
232        variant_index: u32,
233        _variant: &'static str,
234    ) -> Result<()> {
235        assert!(variant_index < 256);
236        self.serialize_u8(variant_index as u8)
237    }
238
239    fn is_human_readable(&self) -> bool {
240        false
241    }
242}
243
244pub(crate) struct SizeChecker<O: Options> {
245    pub options: O,
246}
247
248impl<O: Options> SizeChecker<O> {
249    pub fn new(options: O) -> SizeChecker<O> {
250        SizeChecker { options: options }
251    }
252
253    fn add_raw(&mut self, size: u64) -> Result<()> {
254        self.options.limit().add(size)
255    }
256
257    fn add_value<T>(&mut self, t: T) -> Result<()> {
258        use std::mem::size_of_val;
259        self.add_raw(size_of_val(&t) as u64)
260    }
261}
262
263impl<'a, O: Options> serde::Serializer for &'a mut SizeChecker<O> {
264    type Ok = ();
265    type Error = Error;
266    type SerializeSeq = SizeCompound<'a, O>;
267    type SerializeTuple = SizeCompound<'a, O>;
268    type SerializeTupleStruct = SizeCompound<'a, O>;
269    type SerializeTupleVariant = SizeCompound<'a, O>;
270    type SerializeMap = SizeCompound<'a, O>;
271    type SerializeStruct = SizeCompound<'a, O>;
272    type SerializeStructVariant = SizeCompound<'a, O>;
273
274    fn serialize_unit(self) -> Result<()> {
275        Ok(())
276    }
277
278    fn serialize_unit_struct(self, _: &'static str) -> Result<()> {
279        Ok(())
280    }
281
282    fn serialize_bool(self, _: bool) -> Result<()> {
283        self.add_value(0 as u8)
284    }
285
286    fn serialize_u8(self, v: u8) -> Result<()> {
287        self.add_value(v)
288    }
289
290    fn serialize_u16(self, v: u16) -> Result<()> {
291        self.add_value(v)
292    }
293
294    fn serialize_u32(self, v: u32) -> Result<()> {
295        self.add_value(v)
296    }
297
298    fn serialize_u64(self, v: u64) -> Result<()> {
299        self.add_value(v)
300    }
301
302    fn serialize_i8(self, v: i8) -> Result<()> {
303        self.add_value(v)
304    }
305
306    fn serialize_i16(self, v: i16) -> Result<()> {
307        self.add_value(v)
308    }
309
310    fn serialize_i32(self, v: i32) -> Result<()> {
311        self.add_value(v)
312    }
313
314    fn serialize_i64(self, v: i64) -> Result<()> {
315        self.add_value(v)
316    }
317
318    serde_if_integer128! {
319        fn serialize_u128(self, v: u128) -> Result<()> {
320            self.add_value(v)
321        }
322
323        fn serialize_i128(self, v: i128) -> Result<()> {
324            self.add_value(v)
325        }
326    }
327
328    fn serialize_f32(self, v: f32) -> Result<()> {
329        self.add_value(v)
330    }
331
332    fn serialize_f64(self, v: f64) -> Result<()> {
333        self.add_value(v)
334    }
335
336    fn serialize_str(self, v: &str) -> Result<()> {
337        try!(self.add_value(0 as u64));
338        self.add_raw(v.len() as u64)
339    }
340
341    fn serialize_char(self, c: char) -> Result<()> {
342        self.add_raw(encode_utf8(c).as_slice().len() as u64)
343    }
344
345    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
346        try!(self.add_value(0 as u64));
347        self.add_raw(v.len() as u64)
348    }
349
350    fn serialize_none(self) -> Result<()> {
351        self.add_value(0 as u8)
352    }
353
354    fn serialize_some<T: ?Sized>(self, v: &T) -> Result<()>
355    where
356        T: serde::Serialize,
357    {
358        try!(self.add_value(1 as u8));
359        v.serialize(self)
360    }
361
362    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
363        let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
364
365        try!(self.serialize_u64(len as u64));
366        Ok(SizeCompound { ser: self })
367    }
368
369    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
370        Ok(SizeCompound { ser: self })
371    }
372
373    fn serialize_tuple_struct(
374        self,
375        _name: &'static str,
376        _len: usize,
377    ) -> Result<Self::SerializeTupleStruct> {
378        Ok(SizeCompound { ser: self })
379    }
380
381    fn serialize_tuple_variant(
382        self,
383        _name: &'static str,
384        variant_index: u32,
385        _variant: &'static str,
386        _len: usize,
387    ) -> Result<Self::SerializeTupleVariant> {
388        assert!(variant_index < 256);
389        try!(self.add_value(variant_index as u8));
390        Ok(SizeCompound { ser: self })
391    }
392
393    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
394        let len = try!(len.ok_or(ErrorKind::SequenceMustHaveLength));
395
396        try!(self.serialize_u64(len as u64));
397        Ok(SizeCompound { ser: self })
398    }
399
400    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
401        Ok(SizeCompound { ser: self })
402    }
403
404    fn serialize_struct_variant(
405        self,
406        _name: &'static str,
407        variant_index: u32,
408        _variant: &'static str,
409        _len: usize,
410    ) -> Result<Self::SerializeStructVariant> {
411        assert!(variant_index < 256);
412        try!(self.add_value(variant_index as u8));
413        Ok(SizeCompound { ser: self })
414    }
415
416    fn serialize_newtype_struct<V: serde::Serialize + ?Sized>(
417        self,
418        _name: &'static str,
419        v: &V,
420    ) -> Result<()> {
421        v.serialize(self)
422    }
423
424    fn serialize_unit_variant(
425        self,
426        _name: &'static str,
427        variant_index: u32,
428        _variant: &'static str,
429    ) -> Result<()> {
430        assert!(variant_index < 256);
431        self.add_value(variant_index as u8)
432    }
433
434    fn serialize_newtype_variant<V: serde::Serialize + ?Sized>(
435        self,
436        _name: &'static str,
437        variant_index: u32,
438        _variant: &'static str,
439        value: &V,
440    ) -> Result<()> {
441        assert!(variant_index < 256);
442        try!(self.add_value(variant_index as u8));
443        value.serialize(self)
444    }
445
446    fn is_human_readable(&self) -> bool {
447        false
448    }
449}
450
451pub(crate) struct Compound<'a, W: 'a, O: Options + 'a> {
452    ser: &'a mut Serializer<W, O>,
453}
454
455impl<'a, W, O> serde::ser::SerializeSeq for Compound<'a, W, O>
456where
457    W: Write,
458    O: Options,
459{
460    type Ok = ();
461    type Error = Error;
462
463    #[inline]
464    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
465    where
466        T: serde::ser::Serialize,
467    {
468        value.serialize(&mut *self.ser)
469    }
470
471    #[inline]
472    fn end(self) -> Result<()> {
473        Ok(())
474    }
475}
476
477impl<'a, W, O> serde::ser::SerializeTuple for Compound<'a, W, O>
478where
479    W: Write,
480    O: Options,
481{
482    type Ok = ();
483    type Error = Error;
484
485    #[inline]
486    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
487    where
488        T: serde::ser::Serialize,
489    {
490        value.serialize(&mut *self.ser)
491    }
492
493    #[inline]
494    fn end(self) -> Result<()> {
495        Ok(())
496    }
497}
498
499impl<'a, W, O> serde::ser::SerializeTupleStruct for Compound<'a, W, O>
500where
501    W: Write,
502    O: Options,
503{
504    type Ok = ();
505    type Error = Error;
506
507    #[inline]
508    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
509    where
510        T: serde::ser::Serialize,
511    {
512        value.serialize(&mut *self.ser)
513    }
514
515    #[inline]
516    fn end(self) -> Result<()> {
517        Ok(())
518    }
519}
520
521impl<'a, W, O> serde::ser::SerializeTupleVariant for Compound<'a, W, O>
522where
523    W: Write,
524    O: Options,
525{
526    type Ok = ();
527    type Error = Error;
528
529    #[inline]
530    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
531    where
532        T: serde::ser::Serialize,
533    {
534        value.serialize(&mut *self.ser)
535    }
536
537    #[inline]
538    fn end(self) -> Result<()> {
539        Ok(())
540    }
541}
542
543impl<'a, W, O> serde::ser::SerializeMap for Compound<'a, W, O>
544where
545    W: Write,
546    O: Options,
547{
548    type Ok = ();
549    type Error = Error;
550
551    #[inline]
552    fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
553    where
554        K: serde::ser::Serialize,
555    {
556        value.serialize(&mut *self.ser)
557    }
558
559    #[inline]
560    fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
561    where
562        V: serde::ser::Serialize,
563    {
564        value.serialize(&mut *self.ser)
565    }
566
567    #[inline]
568    fn end(self) -> Result<()> {
569        Ok(())
570    }
571}
572
573impl<'a, W, O> serde::ser::SerializeStruct for Compound<'a, W, O>
574where
575    W: Write,
576    O: Options,
577{
578    type Ok = ();
579    type Error = Error;
580
581    #[inline]
582    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
583    where
584        T: serde::ser::Serialize,
585    {
586        value.serialize(&mut *self.ser)
587    }
588
589    #[inline]
590    fn end(self) -> Result<()> {
591        Ok(())
592    }
593}
594
595impl<'a, W, O> serde::ser::SerializeStructVariant for Compound<'a, W, O>
596where
597    W: Write,
598    O: Options,
599{
600    type Ok = ();
601    type Error = Error;
602
603    #[inline]
604    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
605    where
606        T: serde::ser::Serialize,
607    {
608        value.serialize(&mut *self.ser)
609    }
610
611    #[inline]
612    fn end(self) -> Result<()> {
613        Ok(())
614    }
615}
616
617pub(crate) struct SizeCompound<'a, S: Options + 'a> {
618    ser: &'a mut SizeChecker<S>,
619}
620
621impl<'a, O: Options> serde::ser::SerializeSeq for SizeCompound<'a, O> {
622    type Ok = ();
623    type Error = Error;
624
625    #[inline]
626    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
627    where
628        T: serde::ser::Serialize,
629    {
630        value.serialize(&mut *self.ser)
631    }
632
633    #[inline]
634    fn end(self) -> Result<()> {
635        Ok(())
636    }
637}
638
639impl<'a, O: Options> serde::ser::SerializeTuple for SizeCompound<'a, O> {
640    type Ok = ();
641    type Error = Error;
642
643    #[inline]
644    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
645    where
646        T: serde::ser::Serialize,
647    {
648        value.serialize(&mut *self.ser)
649    }
650
651    #[inline]
652    fn end(self) -> Result<()> {
653        Ok(())
654    }
655}
656
657impl<'a, O: Options> serde::ser::SerializeTupleStruct for SizeCompound<'a, O> {
658    type Ok = ();
659    type Error = Error;
660
661    #[inline]
662    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
663    where
664        T: serde::ser::Serialize,
665    {
666        value.serialize(&mut *self.ser)
667    }
668
669    #[inline]
670    fn end(self) -> Result<()> {
671        Ok(())
672    }
673}
674
675impl<'a, O: Options> serde::ser::SerializeTupleVariant for SizeCompound<'a, O> {
676    type Ok = ();
677    type Error = Error;
678
679    #[inline]
680    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
681    where
682        T: serde::ser::Serialize,
683    {
684        value.serialize(&mut *self.ser)
685    }
686
687    #[inline]
688    fn end(self) -> Result<()> {
689        Ok(())
690    }
691}
692
693impl<'a, O: Options + 'a> serde::ser::SerializeMap for SizeCompound<'a, O> {
694    type Ok = ();
695    type Error = Error;
696
697    #[inline]
698    fn serialize_key<K: ?Sized>(&mut self, value: &K) -> Result<()>
699    where
700        K: serde::ser::Serialize,
701    {
702        value.serialize(&mut *self.ser)
703    }
704
705    #[inline]
706    fn serialize_value<V: ?Sized>(&mut self, value: &V) -> Result<()>
707    where
708        V: serde::ser::Serialize,
709    {
710        value.serialize(&mut *self.ser)
711    }
712
713    #[inline]
714    fn end(self) -> Result<()> {
715        Ok(())
716    }
717}
718
719impl<'a, O: Options> serde::ser::SerializeStruct for SizeCompound<'a, O> {
720    type Ok = ();
721    type Error = Error;
722
723    #[inline]
724    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
725    where
726        T: serde::ser::Serialize,
727    {
728        value.serialize(&mut *self.ser)
729    }
730
731    #[inline]
732    fn end(self) -> Result<()> {
733        Ok(())
734    }
735}
736
737impl<'a, O: Options> serde::ser::SerializeStructVariant for SizeCompound<'a, O> {
738    type Ok = ();
739    type Error = Error;
740
741    #[inline]
742    fn serialize_field<T: ?Sized>(&mut self, _key: &'static str, value: &T) -> Result<()>
743    where
744        T: serde::ser::Serialize,
745    {
746        value.serialize(&mut *self.ser)
747    }
748
749    #[inline]
750    fn end(self) -> Result<()> {
751        Ok(())
752    }
753}
754const TAG_CONT: u8 = 0b1000_0000;
755const TAG_TWO_B: u8 = 0b1100_0000;
756const TAG_THREE_B: u8 = 0b1110_0000;
757const TAG_FOUR_B: u8 = 0b1111_0000;
758const MAX_ONE_B: u32 = 0x80;
759const MAX_TWO_B: u32 = 0x800;
760const MAX_THREE_B: u32 = 0x10000;
761
762fn encode_utf8(c: char) -> EncodeUtf8 {
763    let code = c as u32;
764    let mut buf = [0; 4];
765    let pos = if code < MAX_ONE_B {
766        buf[3] = code as u8;
767        3
768    } else if code < MAX_TWO_B {
769        buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
770        buf[3] = (code & 0x3F) as u8 | TAG_CONT;
771        2
772    } else if code < MAX_THREE_B {
773        buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
774        buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
775        buf[3] = (code & 0x3F) as u8 | TAG_CONT;
776        1
777    } else {
778        buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
779        buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
780        buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
781        buf[3] = (code & 0x3F) as u8 | TAG_CONT;
782        0
783    };
784    EncodeUtf8 { buf: buf, pos: pos }
785}
786
787struct EncodeUtf8 {
788    buf: [u8; 4],
789    pos: usize,
790}
791
792impl EncodeUtf8 {
793    fn as_slice(&self) -> &[u8] {
794        &self.buf[self.pos..]
795    }
796}