1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
use std::{
    collections::VecDeque,
    fmt::{Debug, Display},
};

use displaydoc::Display;
use nom::{
    branch::alt,
    bytes::complete::tag,
    combinator::value,
    error::{ContextError, ParseError},
    sequence::preceded,
    sequence::tuple,
    IResult, Parser,
};
use num::rational::Ratio;
use num::Integer;
use thiserror::Error;

#[non_exhaustive]
#[derive(Display, Error, Debug, Clone)]
pub enum SerializeError {
    /// Number {0} is too big to be serialized
    NumberTooBig(String),
    /// General error {0}
    GeneralError(String),
    /// String too big {0},
    StringTooBig(String),
}

#[derive(Clone, Error)]
pub struct DeserializeError<'a> {
    errors: VecDeque<(&'a [u8], String)>,
}

impl<'a> ContextError<&'a [u8]> for DeserializeError<'a> {
    fn add_context(input: &'a [u8], ctx: &'static str, mut other: Self) -> Self {
        other.errors.push_front((input, ctx.to_string()));
        other
    }
}

impl<'a> ParseError<&'a [u8]> for DeserializeError<'a> {
    fn append(input: &'a [u8], kind: nom::error::ErrorKind, mut other: Self) -> Self {
        other
            .errors
            .push_front((input, kind.description().to_string()));
        other
    }
    fn from_error_kind(input: &'a [u8], kind: nom::error::ErrorKind) -> Self {
        let mut errors = VecDeque::new();
        errors.push_front((input, kind.description().to_string()));
        Self { errors }
    }
    fn from_char(input: &'a [u8], _: char) -> Self {
        Self::from_error_kind(input, nom::error::ErrorKind::Char)
    }
    fn or(self, other: Self) -> Self {
        other
    }
}

impl<'a> Display for DeserializeError<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for error in &self.errors {
            write!(f, "{} / ", error.1)?;
        }
        Ok(())
    }
}

impl<'a> Debug for DeserializeError<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut last_input = None;
        for error in &self.errors {
            write!(f, "{} / ", error.1)?;
            last_input = Some(error.0);
        }
        if let Some(last_input) = last_input {
            writeln!(f, "Input: {:?}", last_input)?;
        }
        Ok(())
    }
}

/// Trait that define the deserialize method that must be implemented for all types have serialize form in Massa.
///
/// This trait must be implemented on deserializers that will be defined for each type and can contains constraints.
/// Example:
/// ```
/// use std::ops::Bound;
/// use unsigned_varint::nom as varint_nom;
/// use nom::{IResult, error::{context, ContextError, ParseError}};
/// use massa_serialization::Deserializer;
/// use std::ops::RangeBounds;
///
/// pub struct U64VarIntDeserializer {
///     range: (Bound<u64>, Bound<u64>)
/// }
///
/// impl U64VarIntDeserializer {
///     fn new(min: Bound<u64>, max: Bound<u64>) -> Self {
///         Self {
///             range: (min, max)
///         }
///     }
/// }
///
/// impl Deserializer<u64> for U64VarIntDeserializer {
///     fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(&self, buffer: &'a [u8]) -> IResult<&'a [u8], u64, E> {
///         context(concat!("Failed u64 deserialization"), |input: &'a [u8]| {
///             let (rest, value) = varint_nom::u64(input).map_err(|_| nom::Err::Error(ParseError::from_error_kind(input, nom::error::ErrorKind::Fail)))?;
///             if !self.range.contains(&value) {
///                 return Err(nom::Err::Error(ParseError::from_error_kind(input, nom::error::ErrorKind::Fail)));
///             }
///             Ok((rest, value))
///         })(buffer)
///     }
/// }
/// ```
pub trait Deserializer<T> {
    /// Deserialize a value `T` from a buffer of `u8`.
    ///
    /// ## Parameters
    /// * buffer: the buffer that contains the whole serialized data.
    ///
    /// ## Returns
    /// A nom result with the rest of the serialized data and the decoded value.
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], T, E>;
}

/// This trait must be implemented to serializes all data in Massa.
///
/// Example:
/// ```
/// use std::ops::Bound;
/// use unsigned_varint::nom as varint_nom;
/// use nom::IResult;
/// use massa_serialization::Serializer;
/// use std::ops::RangeBounds;
/// use unsigned_varint::encode::u64_buffer;
/// use unsigned_varint::encode::u64;
/// use massa_serialization::SerializeError;
///
/// pub struct U64VarIntSerializer {
///     range: (Bound<u64>, Bound<u64>)
/// }
///
/// impl U64VarIntSerializer {
///     fn new(min: Bound<u64>, max: Bound<u64>) -> Self {
///         Self {
///             range: (min, max)
///         }
///     }
/// }
///
/// impl Serializer<u64> for U64VarIntSerializer {
///     fn serialize(&self, value: &u64, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
///         if !self.range.contains(value) {
///             return Err(SerializeError::NumberTooBig(format!("Value {:#?} is not in range {:#?}", value, self.range)));
///         }
///         buffer.extend_from_slice(u64(*value, &mut u64_buffer()));
///         Ok(())
///     }
/// }
/// ```
pub trait Serializer<T> {
    /// Serialize a value `T` into a buffer of `u8`.
    ///
    /// ## Parameters
    /// * value: the value to be serialized.
    ///
    /// ## Returns
    /// A Result with the serialized data.
    fn serialize(&self, value: &T, buffer: &mut Vec<u8>) -> Result<(), SerializeError>;
}

macro_rules! gen_varint {
    ($($type:ident, $s:ident, $bs:ident, $ds:ident, $d:expr);*) => {
        use std::ops::{Bound, RangeBounds};
        use nom::error::context;
        use unsigned_varint::nom as unsigned_nom;
        $(
            use unsigned_varint::encode::{$type, $bs};
            #[doc = " Serializer for "]
            #[doc = $d]
            #[doc = " in a varint form."]
            #[derive(Clone)]
            pub struct $s;

            impl $s {
                #[doc = "Create a basic serializer for "]
                #[doc = $d]
                #[doc = " in a varint form."]
                #[allow(dead_code)]
                pub const fn new() -> Self {
                    Self
                }
            }

            impl Default for $s {
                fn default() -> $s {
                    $s::new()
                }
            }

            impl Serializer<$type> for $s {
                fn serialize(&self, value: &$type, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
                    buffer.extend_from_slice($type(*value, &mut $bs()));
                    Ok(())
                }
            }

            #[doc = " Deserializer for "]
            #[doc = $d]
            #[doc = " in a varint form."]
            #[derive(Clone)]
            pub struct $ds {
                range: (Bound<$type>, Bound<$type>)
            }

            impl $ds {
                #[doc = "Create a basic deserializer for "]
                #[doc = $d]
                #[doc = " in a varint form."]
                #[allow(dead_code)]
                pub const fn new(min: Bound<$type>, max: Bound<$type>) -> Self {
                    Self {
                        range: (min, max)
                    }
                }
            }

            impl Deserializer<$type> for $ds {
                fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(&self, buffer: &'a [u8]) -> IResult<&'a [u8], $type, E> {
                    context(concat!("Failed ", stringify!($type), " deserialization"), |input: &'a [u8]| {
                        let (rest, value) = unsigned_nom::$type(input).map_err(|_| nom::Err::Error(ParseError::from_error_kind(input, nom::error::ErrorKind::Fail)))?;
                        if !self.range.contains(&value) {
                            return Err(nom::Err::Error(ParseError::from_error_kind(input, nom::error::ErrorKind::Fail)));
                        }
                        Ok((rest, value))
                    })(buffer)
                }
            }
        )*
    };
}

gen_varint! {
u16, U16VarIntSerializer, u16_buffer, U16VarIntDeserializer, "`u16`";
u32, U32VarIntSerializer, u32_buffer, U32VarIntDeserializer, "`u32`";
u64, U64VarIntSerializer, u64_buffer, U64VarIntDeserializer, "`u64`";
u128, U128VarIntSerializer, u128_buffer, U128VarIntDeserializer, "`u128`"
}

#[derive(Clone)]
pub struct OptionSerializer<T, ST>
where
    ST: Serializer<T>,
{
    data_serializer: ST,
    phantom_t: std::marker::PhantomData<T>,
}

impl<T, ST> OptionSerializer<T, ST>
where
    ST: Serializer<T>,
{
    pub fn new(data_serializer: ST) -> Self {
        OptionSerializer {
            data_serializer,
            phantom_t: std::marker::PhantomData,
        }
    }
}

impl<T, ST> Serializer<Option<T>> for OptionSerializer<T, ST>
where
    ST: Serializer<T>,
{
    fn serialize(&self, opt_value: &Option<T>, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        if let Some(value) = opt_value {
            buffer.push(b'1');
            self.data_serializer.serialize(value, buffer)?;
        } else {
            buffer.push(b'0');
        }
        Ok(())
    }
}

#[derive(Clone)]
pub struct OptionDeserializer<T, DT>
where
    T: Clone,
    DT: Deserializer<T>,
{
    data_deserializer: DT,
    phantom_t: std::marker::PhantomData<T>,
}

impl<T, DT> OptionDeserializer<T, DT>
where
    T: Clone,
    DT: Deserializer<T>,
{
    pub const fn new(data_deserializer: DT) -> Self {
        OptionDeserializer {
            data_deserializer,
            phantom_t: std::marker::PhantomData,
        }
    }
}

impl<T, DT> Deserializer<Option<T>> for OptionDeserializer<T, DT>
where
    T: Clone,
    DT: Deserializer<T>,
{
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], Option<T>, E> {
        context(
            "Option<_> deserializer failed",
            alt((
                context("None", value(None, tag(b"0"))),
                context(
                    "Some(_)",
                    preceded(tag(b"1"), |input| {
                        self.data_deserializer
                            .deserialize(input)
                            .map(|(rest, data)| (rest, Some(data)))
                    }),
                ),
            )),
        )
        .parse(buffer)
    }
}

/// Serializer for bool
#[derive(Clone, Debug, Default)]
pub struct BoolSerializer {}

impl BoolSerializer {
    /// ctor
    pub fn new() -> Self {
        Self {}
    }
}

impl Serializer<bool> for BoolSerializer {
    fn serialize(&self, value: &bool, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        buffer.push(*value as u8);
        Ok(())
    }
}

/// Deserializer for bool
#[derive(Clone, Debug, Default)]
pub struct BoolDeserializer {}

impl BoolDeserializer {
    /// ctor
    pub fn new() -> Self {
        Self {}
    }
}

impl Deserializer<bool> for BoolDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], bool, E> {
        context("Failed bool deserialization", |input: &'a [u8]| {
            let Some((first, rest)) = input.split_first() else {
                return Err(nom::Err::Error(ParseError::from_error_kind(
                    input,
                    nom::error::ErrorKind::Fail,
                )));
            };
            Ok((rest, {
                match first {
                    1 => Ok(true),
                    0 => Ok(false),
                    _ => Err(nom::Err::Error(ParseError::from_error_kind(
                        input,
                        nom::error::ErrorKind::Fail,
                    ))),
                }
            }?))
        })(buffer)
    }
}

/// Serializer for Ratio
#[derive(Clone, Debug, Default)]
pub struct RatioSerializer<T, ST>
where
    T: Integer + Clone,
    ST: Serializer<T>,
{
    data_serializer: ST,
    phantom_data: std::marker::PhantomData<T>,
}

impl<T, ST> RatioSerializer<T, ST>
where
    T: Integer + Clone,
    ST: Serializer<T>,
{
    pub fn new(data_serializer: ST) -> Self {
        Self {
            data_serializer,
            phantom_data: std::marker::PhantomData,
        }
    }
}

impl<T, ST> Serializer<Ratio<T>> for RatioSerializer<T, ST>
where
    T: Integer + Clone,
    ST: Serializer<T>,
{
    fn serialize(&self, value: &Ratio<T>, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        self.data_serializer.serialize(value.numer(), buffer)?;
        self.data_serializer.serialize(value.denom(), buffer)?;
        Ok(())
    }
}

#[derive(Clone)]
pub struct RatioDeserializer<T, DT>
where
    T: Integer + Clone,
    DT: Deserializer<T>,
{
    data_deserializer: DT,
    phantom_data: std::marker::PhantomData<T>,
}

impl<T, DT> RatioDeserializer<T, DT>
where
    T: Integer + Clone,
    DT: Deserializer<T>,
{
    pub fn new(data_deserializer: DT) -> Self {
        Self {
            data_deserializer,
            phantom_data: std::marker::PhantomData,
        }
    }
}

impl<T, DT> Deserializer<Ratio<T>> for RatioDeserializer<T, DT>
where
    T: Integer + Clone,
    DT: Deserializer<T>,
{
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], Ratio<T>, E> {
        context(
            "Ratio<_> deserializer failed",
            tuple((
                context("numer deser failed", |input| {
                    self.data_deserializer.deserialize(input)
                }),
                context("denom deser failed", |input| {
                    self.data_deserializer.deserialize(input)
                }),
            )),
        )
        .map(|(numer, denom)| Ratio::new(numer, denom))
        .parse(buffer)
    }
}

#[cfg(test)]
mod tests {
    use crate::{DeserializeError, Deserializer, Serializer};
    use num::rational::Ratio;
    use paste::paste;

    // This macro creates a suite of tests for all types of numbers declared as parameters. Ths list of the
    // tests for each type :
    // - Test with a normal case that everything works
    // - Test with a normal case but a more bigger number that everything works
    // - Test with a number that is out of the range of the deserializer
    // - Test to give an empty buffer to the deserializer
    macro_rules! gen_test_varint {
        ($($type:ident, $bs:ident, $ds:ident);*) => {
            $(
                paste! {
                    #[test]
                    fn [<test_ $type _serializer_deserializer_works>]() {
                        let [< $type _serializer >] = super::$bs::new();
                        let number = [<3 $type >];
                        let mut buffer = Vec::new();
                        [< $type _serializer >].serialize(&number, &mut buffer).expect(concat!("Failed to serialize ", stringify!($type), " 3"));
                        assert_eq!(buffer, vec![3]);
                        let [< $type _deserializer >] = super::$ds::new(std::ops::Bound::Included([<0 $type >]), std::ops::Bound::Included(number));
                        let result = [< $type _deserializer >].deserialize::<DeserializeError>(&buffer);
                        assert!(result.is_ok());
                        let (rest, value) = result.unwrap();
                        assert!(rest.is_empty());
                        assert_eq!(value, number);
                    }

                    #[test]
                    fn [<test $type _serializer_deserializer_works_big_number>]() {
                        let [< $type _serializer >] = super::$bs::new();
                        let number = [<60_500 $type>];
                        let mut buffer = Vec::new();
                        [< $type _serializer >].serialize(&number, &mut buffer).expect(concat!("Failed to serialize ", stringify!($type), " 10_000_000"));
                        assert_eq!(buffer, vec![212, 216, 3]);
                        let [< $type _deserializer >] = super::$ds::new(std::ops::Bound::Included([<0 $type >]), std::ops::Bound::Included(number));
                        let result = [< $type _deserializer >].deserialize::<DeserializeError>(&buffer);
                        assert!(result.is_ok());
                        let (rest, value) = result.unwrap();
                        assert!(rest.is_empty());
                        assert_eq!(value, number);
                    }

                    #[test]
                    fn [<test_ $type _serializer_deserializer_bad_limits>]() {
                        let [< $type _serializer >] = super::$bs::new();
                        let number = [<3 $type >];
                        let mut buffer = Vec::new();
                        [< $type _serializer >].serialize(&number, &mut buffer).expect(concat!("Failed to serialize ", stringify!($type), " 3"));
                        assert_eq!(buffer, vec![3]);
                        let [< $type _deserializer >] = super::$ds::new(std::ops::Bound::Included([<0 $type >]), std::ops::Bound::Excluded(number));
                        let result = [< $type _deserializer >].deserialize::<DeserializeError>(&buffer);
                        assert!(result.is_err());
                        let err = result.unwrap_err();
                        assert_eq!(format!("{}", err), concat!("Parsing Error: Failed ", stringify!($type), " deserialization / Fail / Input: [3]\n"));
                    }

                    #[test]
                    fn [<test_ $type _serializer_deserializer_empty_vec>]() {
                        let buffer = vec![];
                        let [< $type _deserializer >] = super::$ds::new(std::ops::Bound::Included([<0 $type >]), std::ops::Bound::Included($type::MAX));
                        let result = [< $type _deserializer >].deserialize::<DeserializeError>(&buffer);
                        assert!(result.is_err());
                        let err = result.unwrap_err();
                        assert_eq!(format!("{}", err), concat!("Parsing Error: Failed ", stringify!($type), " deserialization / Fail / Input: []\n"));
                    }
                }
            )*
        };
    }

    gen_test_varint!(
        u16, U16VarIntSerializer, U16VarIntDeserializer;
        u32, U32VarIntSerializer, U32VarIntDeserializer;
        u64, U64VarIntSerializer, U64VarIntDeserializer
    );

    #[test]
    fn test_u64_empty_vec() {
        let buffer = vec![];
        let u64_deserializer = super::U64VarIntDeserializer::new(
            std::ops::Bound::Included(0),
            std::ops::Bound::Included(3),
        );
        let result = u64_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            format!("{}", err),
            "Parsing Error: Failed u64 deserialization / Fail / Input: []\n"
        );
    }

    #[test]
    fn test_option_serializer_value_works() {
        let option_serializer = super::OptionSerializer::new(super::U64VarIntSerializer::new());
        let mut buffer = Vec::new();
        option_serializer
            .serialize(&Some(3u64), &mut buffer)
            .expect("Failed to serialize Some(3)");
        assert_eq!(buffer, vec![b'1', 3]);
        let option_deserializer =
            super::OptionDeserializer::new(super::U64VarIntDeserializer::new(
                std::ops::Bound::Included(0),
                std::ops::Bound::Included(3),
            ));
        let result = option_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_ok());
        let (rest, value) = result.unwrap();
        assert!(rest.is_empty());
        assert_eq!(value, Some(3u64));
    }

    #[test]
    fn test_option_serializer_none_works() {
        let option_serializer = super::OptionSerializer::new(super::U64VarIntSerializer::new());
        let mut buffer = Vec::new();
        option_serializer
            .serialize(&None, &mut buffer)
            .expect("Failed to serialize None");
        assert_eq!(buffer, vec![b'0']);
        let option_deserializer =
            super::OptionDeserializer::new(super::U64VarIntDeserializer::new(
                std::ops::Bound::Included(0),
                std::ops::Bound::Included(3),
            ));
        let result = option_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_ok());
        let (rest, value) = result.unwrap();
        assert!(rest.is_empty());
        assert_eq!(value, None);
    }

    #[test]
    fn test_option_bad_serialized_vec() {
        let buffer = vec![2];
        let option_deserializer =
            super::OptionDeserializer::new(super::U64VarIntDeserializer::new(
                std::ops::Bound::Included(0),
                std::ops::Bound::Included(3),
            ));
        let result = option_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(format!("{}", err), "Parsing Error: Option<_> deserializer failed / Alternative / Some(_) / Tag / Input: [2]\n");
    }

    #[test]
    fn test_option_empty_vec() {
        let buffer = vec![];
        let option_deserializer =
            super::OptionDeserializer::new(super::U64VarIntDeserializer::new(
                std::ops::Bound::Included(0),
                std::ops::Bound::Included(3),
            ));
        let result = option_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(format!("{}", err), "Parsing Error: Option<_> deserializer failed / Alternative / Some(_) / Tag / Input: []\n");
    }

    #[test]
    fn test_bool_serializer_deserializer_works() {
        let bool_serializer = super::BoolSerializer::new();
        let mut buffer = Vec::new();
        bool_serializer
            .serialize(&true, &mut buffer)
            .expect("Failed to serialize true");
        assert_eq!(buffer, vec![1]);
        let bool_deserializer = super::BoolDeserializer::new();
        let result = bool_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_ok());
        let (rest, value) = result.unwrap();
        assert!(rest.is_empty());
        assert!(value);
    }

    #[test]
    fn test_bool_bad_serialized_vec() {
        let buffer = vec![2];
        let bool_deserializer = super::BoolDeserializer::new();
        let result = bool_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            format!("{}", err),
            "Parsing Error: Failed bool deserialization / Fail / Input: [2]\n"
        );
    }

    #[test]
    fn test_bool_empty_vec() {
        let buffer = vec![];
        let bool_deserializer = super::BoolDeserializer::new();
        let result = bool_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            format!("{}", err),
            "Parsing Error: Failed bool deserialization / Fail / Input: []\n"
        );
    }

    #[test]
    fn test_ratio_serializer_deserializer_works() {
        let ratio_serializer = super::RatioSerializer::new(super::U64VarIntSerializer::new());
        let mut buffer = Vec::new();
        ratio_serializer
            .serialize(&Ratio::new(3u64, 4u64), &mut buffer)
            .expect("Failed to serialize Ratio(3, 4)");
        assert_eq!(buffer, vec![3, 4]);
        let ratio_deserializer = super::RatioDeserializer::new(super::U64VarIntDeserializer::new(
            std::ops::Bound::Included(0),
            std::ops::Bound::Included(4),
        ));
        let result = ratio_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_ok());
        let (rest, value) = result.unwrap();
        assert!(rest.is_empty());
        assert_eq!(value, Ratio::new(3u64, 4u64));
    }

    #[test]
    fn test_ratio_serializer_deserializer_bad_limits() {
        let ratio_serializer = super::RatioSerializer::new(super::U64VarIntSerializer::new());
        let mut buffer = Vec::new();
        ratio_serializer
            .serialize(&Ratio::new(3u64, 4u64), &mut buffer)
            .expect("Failed to serialize Ratio(3, 4)");
        assert_eq!(buffer, vec![3, 4]);
        let ratio_deserializer = super::RatioDeserializer::new(super::U64VarIntDeserializer::new(
            std::ops::Bound::Included(0),
            std::ops::Bound::Included(3),
        ));
        let result = ratio_deserializer.deserialize::<DeserializeError>(&buffer);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(format!("{}", err), "Parsing Error: Ratio<_> deserializer failed / denom deser failed / Failed u64 deserialization / Fail / Input: [4]\n");
    }
}