minicbor_ser/
ser.rs

1#![allow(unused_variables, dead_code)]
2use super::Config;
3pub use crate::error::en::Error;
4use crate::error::en::ErrorKind;
5use crate::lib::*;
6use core::fmt::Display;
7use minicbor::{encode::Write, Encoder};
8use serde::serde_if_integer128;
9use serde::{self, ser};
10
11pub struct Serializer<W> {
12    pub(crate) encoder: Encoder<W>,
13    depth: u32,
14    flatten_top: bool,
15}
16
17impl<T> Serializer<T>
18where
19    T: Write,
20{
21    pub fn new(w: T) -> Self {
22        Serializer {
23            encoder: Encoder::new(w),
24            depth: 0,
25            flatten_top: false,
26        }
27    }
28    pub fn new_with_config(w: T, cfg: Config) -> Self {
29        Serializer {
30            encoder: Encoder::new(w),
31            depth: 0,
32            flatten_top: cfg.top_flatten,
33        }
34    }
35    pub fn encoder(&mut self) -> &mut Encoder<T> {
36        &mut self.encoder
37    }
38}
39
40impl<'a, W> ser::Serializer for &'a mut Serializer<W>
41where
42    W: Write,
43    W::Error: Display + 'static,
44{
45    type Ok = ();
46    type Error = Error;
47    type SerializeSeq = Compound<'a, W>;
48    type SerializeTuple = Compound<'a, W>;
49    type SerializeTupleStruct = Compound<'a, W>;
50    type SerializeTupleVariant = Compound<'a, W>;
51    type SerializeMap = Compound<'a, W>;
52    type SerializeStruct = Compound<'a, W>;
53    type SerializeStructVariant = Compound<'a, W>;
54
55    #[inline]
56    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
57        self.encoder.bool(v)?;
58        Ok(())
59    }
60
61    #[inline]
62    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
63        self.encoder.i8(v)?;
64        Ok(())
65    }
66
67    #[inline]
68    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
69        self.encoder.i16(v)?;
70        Ok(())
71    }
72
73    #[inline]
74    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
75        self.encoder.i32(v)?;
76        Ok(())
77    }
78
79    #[inline]
80    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
81        self.encoder.i64(v)?;
82        Ok(())
83    }
84
85    #[inline]
86    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
87        self.encoder.u8(v)?;
88        Ok(())
89    }
90
91    #[inline]
92    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
93        self.encoder.u16(v)?;
94        Ok(())
95    }
96
97    #[inline]
98    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
99        self.encoder.u32(v)?;
100        Ok(())
101    }
102
103    #[inline]
104    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
105        self.encoder.u64(v)?;
106        Ok(())
107    }
108
109    #[inline]
110    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
111        self.encoder.f32(v)?;
112        Ok(())
113    }
114
115    #[inline]
116    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
117        self.encoder.f64(v)?;
118        Ok(())
119    }
120
121    #[inline]
122    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
123        self.encoder.char(v)?;
124        Ok(())
125    }
126
127    #[inline]
128    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
129        self.encoder.str(v)?;
130        Ok(())
131    }
132
133    #[inline]
134    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
135        self.encoder.bytes(v)?;
136        Ok(())
137    }
138
139    #[inline]
140    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
141        self.serialize_unit()
142    }
143
144    #[inline]
145    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
146    where
147        T: ser::Serialize,
148    {
149        value.serialize(self)
150    }
151
152    #[inline]
153    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
154        self.encoder.null()?;
155        Ok(())
156    }
157
158    #[inline]
159    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
160        self.serialize_unit()
161    }
162
163    #[inline]
164    fn serialize_unit_variant(
165        self,
166        name: &'static str,
167        variant_index: u32,
168        variant: &'static str,
169    ) -> Result<Self::Ok, Self::Error> {
170        self.serialize_str(variant)
171    }
172
173    #[inline]
174    fn serialize_newtype_struct<T: ?Sized>(
175        self,
176        name: &'static str,
177        value: &T,
178    ) -> Result<Self::Ok, Self::Error>
179    where
180        T: ser::Serialize,
181    {
182        value.serialize(self)
183    }
184
185    #[inline]
186    fn serialize_newtype_variant<T: ?Sized>(
187        self,
188        name: &'static str,
189        variant_index: u32,
190        variant: &'static str,
191        value: &T,
192    ) -> Result<Self::Ok, Self::Error>
193    where
194        T: ser::Serialize,
195    {
196        self.encoder.map(1)?.str(variant)?;
197        value.serialize(&mut *self)?;
198        Ok(())
199    }
200
201    #[inline]
202    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
203        if self.depth == 0 && self.flatten_top {
204            return Ok(Compound::Map {
205                ser: self,
206                state: State::FlattenFirst,
207            });
208        }
209        match len {
210            Some(le) => {
211                if le == 0 {
212                    self.encoder.array(0)?;
213                    Ok(Compound::Map {
214                        ser: self,
215                        state: State::Empty,
216                    })
217                } else {
218                    self.encoder.array(le as u64)?;
219                    Ok(Compound::Map {
220                        ser: self,
221                        state: State::First(Some(le)),
222                    })
223                }
224            }
225            None => {
226                self.encoder.begin_array()?;
227                Ok(Compound::Map {
228                    ser: self,
229                    state: State::First(None),
230                })
231            }
232        }
233    }
234
235    #[inline]
236    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
237        self.serialize_seq(Some(len))
238    }
239
240    #[inline]
241    fn serialize_tuple_struct(
242        self,
243        name: &'static str,
244        len: usize,
245    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
246        self.serialize_seq(Some(len))
247    }
248
249    #[inline]
250    fn serialize_tuple_variant(
251        self,
252        name: &'static str,
253        variant_index: u32,
254        variant: &'static str,
255        len: usize,
256    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
257        self.encoder.map(1)?.str(variant)?;
258        self.serialize_seq(Some(len))
259    }
260
261    #[inline]
262    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
263        if self.flatten_top && self.depth == 0 {
264            return Ok(Compound::Map {
265                ser: self,
266                state: State::FlattenFirst,
267            });
268        }
269        match len {
270            Some(le) => {
271                if le == 0 {
272                    self.encoder.map(0)?;
273                    Ok(Compound::Map {
274                        ser: self,
275                        state: State::Empty,
276                    })
277                } else {
278                    self.encoder.map(le as u64)?;
279                    Ok(Compound::Map {
280                        ser: self,
281                        state: State::First(Some(le)),
282                    })
283                }
284            }
285            None => {
286                self.encoder.begin_map()?;
287                Ok(Compound::Map {
288                    ser: self,
289                    state: State::First(None),
290                })
291            }
292        }
293    }
294
295    #[inline]
296    fn serialize_struct(
297        self,
298        name: &'static str,
299        len: usize,
300    ) -> Result<Self::SerializeStruct, Self::Error> {
301        self.serialize_map(Some(len))
302    }
303
304    #[inline]
305    fn serialize_struct_variant(
306        self,
307        name: &'static str,
308        variant_index: u32,
309        variant: &'static str,
310        len: usize,
311    ) -> Result<Self::SerializeStructVariant, Self::Error> {
312        if self.flatten_top && self.depth == 0 {
313            return Ok(Compound::Map {
314                ser: self,
315                state: State::FlattenFirst,
316            });
317        }
318        self.encoder.map(1)?.str(variant)?;
319        Ok(Compound::Map {
320            ser: self,
321            state: State::First(Some(len)),
322        })
323    }
324
325    #[inline]
326    fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
327    where
328        T: Display,
329    {
330        // Temporary:
331        #[cfg(feature = "alloc")]
332        { self.serialize_str(&value.to_string()) }
333        #[cfg(not(feature = "alloc"))]
334        { unreachable!() }
335    }
336
337    serde_if_integer128! {
338        #[inline]
339        fn serialize_i128(self, v:i128) ->Result<Self::Ok,Self::Error> {
340            Err(super::error::en::make_kind_err(ErrorKind::Unsupported128BitInteger, "128-bit integers are not currently supported."))
341        }
342    }
343    serde_if_integer128! {
344        #[inline]
345        fn serialize_u128(self, v:u128) ->Result<Self::Ok,Self::Error> {
346            Err(super::error::en::make_kind_err(ErrorKind::Unsupported128BitInteger, "128-bit integers are not currently supported."))
347        }
348    }
349}
350
351#[doc(hidden)]
352#[derive(PartialEq, Eq)]
353/// Not public API.
354pub enum State {
355    First(Option<usize>),
356    Empty,
357    Rest(Option<usize>),
358    FlattenFirst,
359    FlattenRest,
360}
361
362#[doc(hidden)]
363/// Not public API.
364pub enum Compound<'a, W: 'a> {
365    Map {
366        ser: &'a mut Serializer<W>,
367        state: State,
368    },
369}
370
371impl<'a, W> ser::SerializeSeq for Compound<'a, W>
372where
373    W: Write,
374    W::Error: Display + 'static,
375{
376    type Ok = ();
377    type Error = Error;
378
379    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
380    where
381        T: ser::Serialize,
382    {
383        match *self {
384            Compound::Map {
385                ref mut ser,
386                ref mut state,
387            } => {
388                match *state {
389                    State::First(size) => {
390                        ser.depth += 1;
391                        *state = State::Rest(size);
392                    }
393                    State::FlattenFirst => {
394                        ser.depth += 1;
395                        *state = State::FlattenRest;
396                    }
397                    _ => {}
398                }
399                value.serialize(&mut **ser)?;
400                Ok(())
401            }
402        }
403    }
404
405    fn end(self) -> Result<Self::Ok, Self::Error> {
406        match self {
407            Compound::Map { ser, state } => {
408                match state {
409                    State::Rest(size) => {
410                        if size.is_none() {
411                            ser.encoder.end()?;
412                        }
413                        ser.depth -= 1;
414                    }
415                    State::FlattenRest => {
416                        ser.depth -= 1;
417                    }
418                    _ => {}
419                }
420                Ok(())
421            }
422        }
423    }
424}
425
426impl<'a, W> ser::SerializeStruct for Compound<'a, W>
427where
428    W: Write,
429    W::Error: Display + 'static,
430{
431    type Ok = ();
432    type Error = Error;
433
434    fn serialize_field<T: ?Sized>(
435        &mut self,
436        key: &'static str,
437        value: &T,
438    ) -> Result<(), Self::Error>
439    where
440        T: ser::Serialize,
441    {
442        match *self {
443            Compound::Map { .. } => ser::SerializeMap::serialize_entry(self, key, value),
444        }
445    }
446
447    fn end(self) -> Result<Self::Ok, Self::Error> {
448        match self {
449            Compound::Map { .. } => ser::SerializeMap::end(self),
450        }
451    }
452}
453
454impl<'a, W> ser::SerializeTuple for Compound<'a, W>
455where
456    W: Write,
457    W::Error: Display + 'static,
458{
459    type Ok = ();
460    type Error = Error;
461
462    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
463    where
464        T: ser::Serialize,
465    {
466        ser::SerializeSeq::serialize_element(self, value)
467    }
468
469    fn end(self) -> Result<Self::Ok, Self::Error> {
470        ser::SerializeSeq::end(self)
471    }
472}
473
474impl<'a, W> ser::SerializeTupleStruct for Compound<'a, W>
475where
476    W: Write,
477    W::Error: Display + 'static,
478{
479    type Ok = ();
480    type Error = Error;
481
482    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
483    where
484        T: ser::Serialize,
485    {
486        ser::SerializeSeq::serialize_element(self, value)
487    }
488
489    fn end(self) -> Result<Self::Ok, Self::Error> {
490        ser::SerializeSeq::end(self)
491    }
492}
493
494impl<'a, W> ser::SerializeTupleVariant for Compound<'a, W>
495where
496    W: Write,
497    W::Error: Display + 'static,
498{
499    type Ok = ();
500    type Error = Error;
501
502    fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
503    where
504        T: ser::Serialize,
505    {
506        ser::SerializeSeq::serialize_element(self, value)
507    }
508
509    fn end(self) -> Result<Self::Ok, Self::Error> {
510        ser::SerializeSeq::end(self)
511    }
512}
513
514impl<'a, W> ser::SerializeMap for Compound<'a, W>
515where
516    W: Write,
517    W::Error: Display + 'static,
518{
519    type Ok = ();
520    type Error = Error;
521
522    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
523    where
524        T: ser::Serialize,
525    {
526        match *self {
527            Compound::Map {
528                ref mut ser,
529                ref mut state,
530            } => {
531                match *state {
532                    State::First(size) => {
533                        ser.depth += 1;
534                        *state = State::Rest(size);
535                    }
536                    State::FlattenFirst => {
537                        ser.depth += 1;
538                        *state = State::FlattenFirst;
539                    }
540                    _ => {}
541                }
542
543                // The CBOR Key type allows for any type that implements
544                key.serialize(&mut **ser)?;
545                Ok(())
546            }
547        }
548    }
549
550    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
551    where
552        T: ser::Serialize,
553    {
554        match *self {
555            Compound::Map {
556                ref mut ser,
557                ref mut state,
558            } => {
559                value.serialize(&mut **ser)?;
560                Ok(())
561            }
562        }
563    }
564
565    fn end(self) -> Result<Self::Ok, Self::Error> {
566        match self {
567            Compound::Map { ser, state } => {
568                match state {
569                    State::Rest(size) => {
570                        if size.is_none() {
571                            ser.encoder.end()?;
572                        }
573                        ser.depth -= 1;
574                    }
575                    State::FlattenRest => {
576                        ser.depth -= 1;
577                    }
578                    _ => {}
579                }
580                Ok(())
581            }
582        }
583    }
584}
585
586impl<'a, W> ser::SerializeStructVariant for Compound<'a, W>
587where
588    W: Write,
589    W::Error: Display + 'static,
590{
591    type Ok = ();
592    type Error = Error;
593
594    fn serialize_field<T: ?Sized>(
595        &mut self,
596        key: &'static str,
597        value: &T,
598    ) -> Result<(), Self::Error>
599    where
600        T: ser::Serialize,
601    {
602        match *self {
603            Compound::Map { .. } => ser::SerializeStruct::serialize_field(self, key, value),
604        }
605    }
606
607    fn end(self) -> Result<Self::Ok, Self::Error> {
608        ser::SerializeStruct::end(self)
609    }
610}
611
612#[cfg(feature = "alloc")]
613#[inline]
614/// Serialize a COBR to Vec.
615///
616/// Have to be aware of is, this function will map the top-level `Struct` and `Tuple` to a cbor `map` and `array`.
617/// If you want the top-level structure to be expanded, use the [`to_vec_flat`] function.
618pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
619where
620    T: ?Sized + ser::Serialize,
621{
622    let mut out = Vec::with_capacity(128);
623    to_writer(value, &mut out)?;
624    Ok(out)
625}
626
627#[cfg(feature = "alloc")]
628#[inline]
629/// Serialize a CBOR to Vec.
630///
631/// This function will serialize top-level `struct` and `tuple` in order.
632/// So you should make sure their fields are in the same order.
633pub fn to_vec_flat<T>(value: &T) -> Result<Vec<u8>, Error>
634where
635    T: ?Sized + ser::Serialize,
636{
637    let mut out = Vec::with_capacity(128);
638    to_writer_cfg(value, &mut out, Config { top_flatten: true })?;
639    Ok(out)
640}
641
642#[inline]
643pub fn to_writer_cfg<W, T>(value: &T, writer: W, cfg: Config) -> Result<(), Error>
644where
645    W: Write,
646    W::Error: Display + 'static,
647    T: ?Sized + ser::Serialize,
648{
649    let mut se = Serializer::new_with_config(writer, cfg);
650    value.serialize(&mut se)?;
651    Ok(())
652}
653
654#[inline]
655pub fn to_writer<W, T>(value: &T, writer: W) -> Result<(), Error>
656where
657    W: Write,
658    W::Error: Display + 'static,
659    T: ?Sized + ser::Serialize,
660{
661    let mut se = Serializer::new(writer);
662    value.serialize(&mut se)?;
663    Ok(())
664}
665
666#[inline]
667pub fn by_encoder<T, W>(v: T, serializer: &mut Serializer<W>) -> Result<(), Error>
668where
669    T: minicbor::Encode<()>,
670    W: Write,
671    W::Error: Display + 'static,
672{
673    serializer.encoder().encode(v)?;
674    Ok(())
675}
676
677#[cfg(all(test, feature = "alloc"))]
678mod ser_tests {
679
680    use serde::Serialize;
681
682    use super::*;
683
684    macro_rules! assert_result {
685        ($expect:expr, $data:expr , $flt:expr) => {{
686            let mut out = Vec::with_capacity(128);
687            to_writer_cfg(&$data, &mut out, Config { top_flatten: $flt }).unwrap();
688            let __s: Vec<u8> = out;
689            let __s = __s.as_slice();
690            assert_eq!(
691                $expect, __s,
692                "\n left hex: {:x?} \n right hex: {:x?}\n",
693                $expect, __s
694            );
695        }};
696        ($expect:expr, $data:expr $(,)?) => {{
697            assert_result!($expect, $data, false)
698        }};
699    }
700
701    #[test]
702    fn test_array() {
703        let expect = [
704            0x88u8, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x18, 0x18, 0x18, 0xFF,
705        ];
706        let const_array = [0u8, 1, 2, 3, 4, 5, 0x18, 0xff];
707        let vec_array = [0u8, 1, 2, 3, 4, 5, 0x18, 0xff].to_vec();
708        let exp_empty = [0x80]; //empty array
709        let empty_arr: [u8; 0] = [];
710
711        assert_result!(expect, const_array);
712        assert_result!(expect, vec_array);
713        assert_result!(exp_empty, empty_arr);
714    }
715
716    #[test]
717    fn test_map() {
718        // {"hello": "world"}
719        let expect = [
720            0xA1u8, 0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x65, 0x77, 0x6F, 0x72, 0x6C, 0x64,
721        ];
722        let mut map = BTreeMap::new();
723        map.insert("hello".to_string(), "world".to_string());
724        assert_result!(expect, map);
725        // {1:1}
726        let expect = [0xA1u8, 1, 1];
727        let mut map = BTreeMap::new();
728        map.insert(1, 1);
729        assert_result!(expect, map);
730    }
731
732    #[derive(Debug, Serialize)]
733    struct TestStruct {
734        hello: String,
735    }
736
737    #[derive(Debug, Serialize)]
738    struct TestStruct2 {
739        a: [u8; 2],
740        b: TestStruct,
741    }
742
743    #[test]
744    fn test_struct() {
745        let expect = [
746            0xA1u8, 0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x65, 0x77, 0x6F, 0x72, 0x6C, 0x64,
747        ];
748        let test_struct = TestStruct {
749            hello: "world".to_string(),
750        };
751        assert_result!(expect, test_struct);
752        let expect = [
753            0xA2, 0x61, 0x61, 0x82, 01, 02, 0x61, 0x62, 0xA1, 0x65, 0x68, 0x65, 0x6C, 0x6C, 0x6F,
754            0x65, 0x77, 0x6F, 0x72, 0x6C, 0x64,
755        ];
756        let test_struct2 = TestStruct2 {
757            a: [1, 2],
758            b: test_struct,
759        };
760        assert_result!(expect, test_struct2);
761    }
762
763    #[test]
764    fn test_tuple() {
765        let expect = [
766            0x88u8, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x18, 0x18, 0x18, 0xFF,
767        ];
768        let tuple_array = (0u8, 1, 2, 3, 4, 5, 0x18, 0xff);
769        assert_result!(expect, tuple_array);
770
771        let expect = [0x01u8, 0x18, 0xff, 0x65, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
772        let tuple_flatten = (0x01u8, 0xffu8, "hello");
773        assert_result!(expect, tuple_flatten, true);
774    }
775
776    #[derive(Debug, Serialize)]
777    enum TestEnum {
778        A,
779        B(i32),
780        C(TestStruct),
781        D(&'static [u8]),
782    }
783    #[test]
784    fn test_enum() {
785        let a = TestEnum::A;
786        let b = TestEnum::B(1);
787        let c = TestEnum::C(TestStruct {
788            hello: "world".to_string(),
789        });
790        let d = TestEnum::D(&[1, 2, 3, 4][..]);
791        assert_result!([0x61, 0x41], a);
792        assert_result!([0xa1, 0x61, 0x42, 0x1], b);
793        assert_result!(
794            [
795                0xa1, 0x61, 0x43, 0xa1, 0x65, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x65, 0x77, 0x6f, 0x72,
796                0x6c, 0x64
797            ],
798            c
799        );
800        assert_result!([0xa1, 0x61, 0x44, 0x84, 0x01, 0x02, 0x03, 0x04], d);
801    }
802}