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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
// Copyright (c) 2022 MASSA LABS <info@massa.net>

use crate::error::ModelsError;
use crate::prehash::{PreHashSet, PreHashed};
use bitvec::prelude::BitVec;
use massa_serialization::{
    Deserializer, SerializeError, Serializer, U32VarIntDeserializer, U32VarIntSerializer,
    U64VarIntDeserializer, U64VarIntSerializer,
};
use nom::bytes::complete::take;
use nom::multi::{length_count, length_data};
use nom::sequence::preceded;
use nom::{branch::alt, Parser, ToUsize};
use nom::{
    error::{context, ContextError, ErrorKind, ParseError},
    IResult,
};
use num::integer::div_ceil;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::mem::size_of;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::ops::Bound;
use Bound::Included;

/// Serialize min big endian integer
pub trait SerializeMinBEInt {
    /// serializes with the minimal amount of big endian bytes
    fn to_be_bytes_min(self, max_value: Self) -> Result<Vec<u8>, ModelsError>;
}

impl SerializeMinBEInt for u32 {
    fn to_be_bytes_min(self, max_value: Self) -> Result<Vec<u8>, ModelsError> {
        if self > max_value {
            return Err(ModelsError::SerializeError("integer out of bounds".into()));
        }
        let skip_bytes = (max_value.leading_zeros() as usize) / 8;
        Ok(self.to_be_bytes()[skip_bytes..].to_vec())
    }
}

impl SerializeMinBEInt for u64 {
    fn to_be_bytes_min(self, max_value: Self) -> Result<Vec<u8>, ModelsError> {
        if self > max_value {
            return Err(ModelsError::SerializeError("integer out of bounds".into()));
        }
        let skip_bytes = (max_value.leading_zeros() as usize) / 8;
        Ok(self.to_be_bytes()[skip_bytes..].to_vec())
    }
}

/// Deserialize min big endian
pub trait DeserializeMinBEInt: Sized {
    /// Deserializes a minimally sized big endian integer to Self from the provided buffer and checks that its value is within given bounds.
    /// In case of success, return the deserialized data and the number of bytes read
    fn from_be_bytes_min(buffer: &[u8], max_value: Self) -> Result<(Self, usize), ModelsError>;
}

/// Compute the minimal big endian deserialization size
pub const fn u32_be_bytes_min_length(max_value: u32) -> usize {
    size_of::<u32>() - (max_value.leading_zeros() as usize) / 8
}

/// Compute the minimal big endian deserialization size
pub const fn u64_be_bytes_min_length(max_value: u64) -> usize {
    size_of::<u64>() - (max_value.leading_zeros() as usize) / 8
}
impl DeserializeMinBEInt for u32 {
    fn from_be_bytes_min(buffer: &[u8], max_value: Self) -> Result<(Self, usize), ModelsError> {
        let read_bytes = u32_be_bytes_min_length(max_value);
        let skip_bytes = size_of::<Self>() - read_bytes;
        if buffer.len() < read_bytes {
            return Err(ModelsError::SerializeError("unexpected buffer END".into()));
        }
        let mut buf = [0u8; size_of::<Self>()];
        buf[skip_bytes..].clone_from_slice(&buffer[..read_bytes]);
        let res = u32::from_be_bytes(buf);
        if res > max_value {
            return Err(ModelsError::SerializeError(
                "integer outside of bounds".into(),
            ));
        }
        Ok((res, read_bytes))
    }
}

impl DeserializeMinBEInt for u64 {
    fn from_be_bytes_min(buffer: &[u8], max_value: Self) -> Result<(Self, usize), ModelsError> {
        let read_bytes = u64_be_bytes_min_length(max_value);
        let skip_bytes = size_of::<Self>() - read_bytes;
        if buffer.len() < read_bytes {
            return Err(ModelsError::SerializeError("unexpected buffer END".into()));
        }
        let mut buf = [0u8; size_of::<Self>()];
        buf[skip_bytes..].clone_from_slice(&buffer[..read_bytes]);
        let res = u64::from_be_bytes(buf);
        if res > max_value {
            return Err(ModelsError::SerializeError(
                "integer outside of bounds".into(),
            ));
        }
        Ok((res, read_bytes))
    }
}

/// array from slice
pub fn array_from_slice<const ARRAY_SIZE: usize>(
    buffer: &[u8],
) -> Result<[u8; ARRAY_SIZE], ModelsError> {
    if buffer.len() < ARRAY_SIZE {
        return Err(ModelsError::BufferError(
            "slice too small to extract array".into(),
        ));
    }
    buffer[..ARRAY_SIZE].try_into().map_err(|err| {
        ModelsError::BufferError(format!("could not extract array from slice: {}", err))
    })
}

/// `u8` from slice
pub fn u8_from_slice(buffer: &[u8]) -> Result<u8, ModelsError> {
    if buffer.is_empty() {
        return Err(ModelsError::BufferError(
            "could not read u8 from empty buffer".into(),
        ));
    }
    Ok(buffer[0])
}

/// Serializer for `IpAddr`
#[derive(Default, Clone)]
pub struct IpAddrSerializer;

impl IpAddrSerializer {
    /// Creates a `IpAddrSerializer`
    pub const fn new() -> Self {
        Self
    }
}

impl Serializer<IpAddr> for IpAddrSerializer {
    /// ```
    /// use massa_models::{address::Address, amount::Amount, slot::Slot, serialization::IpAddrSerializer};
    /// use massa_serialization::Serializer;
    /// use std::str::FromStr;
    /// use std::net::{IpAddr, Ipv4Addr};
    ///
    /// let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
    /// let ip_serializer = IpAddrSerializer::new();
    /// let mut buffer = Vec::new();
    /// ip_serializer.serialize(&ip, &mut buffer).unwrap();
    /// ```
    fn serialize(&self, value: &IpAddr, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        match value {
            IpAddr::V4(ip_v4) => {
                buffer.push(4u8);
                buffer.extend(ip_v4.octets());
            }
            IpAddr::V6(ip_v6) => {
                buffer.push(6u8);
                buffer.extend(ip_v6.octets());
            }
        };
        Ok(())
    }
}

/// Deserializer for `IpAddr`
#[derive(Default, Clone)]
pub struct IpAddrDeserializer;

impl IpAddrDeserializer {
    /// Creates a `IpAddrDeserializer`
    pub const fn new() -> Self {
        Self
    }
}

impl Deserializer<IpAddr> for IpAddrDeserializer {
    /// ```
    /// use massa_models::{address::Address, amount::Amount, slot::Slot, serialization::{IpAddrSerializer, IpAddrDeserializer}};
    /// use massa_serialization::{Serializer, Deserializer, DeserializeError};
    /// use std::str::FromStr;
    /// use std::net::{IpAddr, Ipv6Addr};
    ///
    /// let ip = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
    /// let ip_serializer = IpAddrSerializer::new();
    /// let ip_deserializer = IpAddrDeserializer::new();
    /// let mut serialized = Vec::new();
    /// ip_serializer.serialize(&ip, &mut serialized).unwrap();
    /// let (rest, ip_deser) = ip_deserializer.deserialize::<DeserializeError>(&serialized).unwrap();
    /// assert!(rest.is_empty());
    /// assert_eq!(ip, ip_deser);
    /// ```
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], IpAddr, E> {
        context(
            "Failed IpAddr deserialization",
            alt((
                preceded(
                    |input| nom::bytes::complete::tag([4u8])(input),
                    |input: &'a [u8]| {
                        let (rest, addr) = take(4usize)(input)?;
                        let addr: [u8; 4] = addr.try_into().unwrap();
                        Ok((rest, IpAddr::V4(Ipv4Addr::from(addr))))
                    },
                ),
                preceded(
                    |input| nom::bytes::complete::tag([6u8])(input),
                    |input: &'a [u8]| {
                        let (rest, addr) = take(16usize)(input)?;
                        // Safe because take would fail just above if less then 16
                        let addr: [u8; 16] = addr.try_into().unwrap();
                        Ok((rest, IpAddr::V6(Ipv6Addr::from(addr))))
                    },
                ),
            )),
        )(buffer)
    }
}

/// Basic `Vec<u8>` serializer
#[derive(Clone)]
pub struct VecU8Serializer {
    len_serializer: U64VarIntSerializer,
}

impl VecU8Serializer {
    /// Creates a new `VecU8Serializer`
    pub fn new() -> Self {
        Self {
            len_serializer: U64VarIntSerializer::new(),
        }
    }
}

impl Default for VecU8Serializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<Vec<u8>> for VecU8Serializer {
    /// ```
    /// use std::ops::Bound::Included;
    /// use massa_serialization::Serializer;
    /// use massa_models::serialization::VecU8Serializer;
    ///
    /// let vec = vec![1, 2, 3];
    /// let mut buffer = Vec::new();
    /// let serializer = VecU8Serializer::new();
    /// serializer.serialize(&vec, &mut buffer).unwrap();
    /// ```
    fn serialize(&self, value: &Vec<u8>, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        let len: u64 = value.len().try_into().map_err(|err| {
            SerializeError::NumberTooBig(format!("too many entries data in VecU8: {}", err))
        })?;
        self.len_serializer.serialize(&len, buffer)?;
        buffer.extend(value);
        Ok(())
    }
}

/// Basic `Vec<u8>` deserializer
#[derive(Clone)]
pub struct VecU8Deserializer {
    varint_u64_deserializer: U64VarIntDeserializer,
}

impl VecU8Deserializer {
    /// Creates a new `VecU8Deserializer`
    pub const fn new(min_length: Bound<u64>, max_length: Bound<u64>) -> Self {
        Self {
            varint_u64_deserializer: U64VarIntDeserializer::new(min_length, max_length),
        }
    }
}

impl Deserializer<Vec<u8>> for VecU8Deserializer {
    /// ```
    /// use std::ops::Bound::Included;
    /// use massa_serialization::{Serializer, Deserializer, DeserializeError};
    /// use massa_models::serialization::{VecU8Serializer, VecU8Deserializer};
    ///
    /// let vec = vec![1, 2, 3];
    /// let mut serialized = Vec::new();
    /// let serializer = VecU8Serializer::new();
    /// let deserializer = VecU8Deserializer::new(Included(0), Included(1000000));
    /// serializer.serialize(&vec, &mut serialized).unwrap();
    /// let (rest, vec_deser) = deserializer.deserialize::<DeserializeError>(&serialized).unwrap();
    /// assert!(rest.is_empty());
    /// assert_eq!(vec, vec_deser);
    /// ```
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], Vec<u8>, E> {
        context("Failed Vec<u8> deserialization", |input| {
            length_data(|input| self.varint_u64_deserializer.deserialize(input))(input)
        })
        .map(|res| res.to_vec())
        .parse(buffer)
    }
}

/// Basic `Vec<_>` serializer
#[derive(Clone)]
pub struct VecSerializer<T, ST>
where
    ST: Serializer<T>,
{
    len_serializer: U64VarIntSerializer,
    data_serializer: ST,
    phantom_t: PhantomData<T>,
}

impl<T, ST> VecSerializer<T, ST>
where
    ST: Serializer<T>,
{
    /// Creates a new `VecSerializer`
    pub fn new(data_serializer: ST) -> Self {
        Self {
            len_serializer: U64VarIntSerializer::new(),
            data_serializer,
            phantom_t: PhantomData,
        }
    }
}

impl<T, ST> Serializer<Vec<T>> for VecSerializer<T, ST>
where
    ST: Serializer<T>,
{
    fn serialize(&self, value: &Vec<T>, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        self.len_serializer
            .serialize(&(value.len() as u64), buffer)?;
        for elem in value {
            self.data_serializer.serialize(elem, buffer)?;
        }
        Ok(())
    }
}

/// Basic `Vec<_>` deserializer
#[derive(Clone)]
pub struct VecDeserializer<T, ST>
where
    ST: Deserializer<T> + Clone,
{
    varint_u64_deserializer: U64VarIntDeserializer,
    data_deserializer: ST,
    phantom_t: PhantomData<T>,
}

impl<T, ST> VecDeserializer<T, ST>
where
    ST: Deserializer<T> + Clone,
{
    /// Creates a new `VecDeserializer`
    pub const fn new(
        data_deserializer: ST,
        min_length: Bound<u64>,
        max_length: Bound<u64>,
    ) -> Self {
        Self {
            varint_u64_deserializer: U64VarIntDeserializer::new(min_length, max_length),
            data_deserializer,
            phantom_t: PhantomData,
        }
    }
}

impl<T, ST> Deserializer<Vec<T>> for VecDeserializer<T, ST>
where
    ST: Deserializer<T> + Clone,
{
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], Vec<T>, E> {
        context("Failed Vec<_> deserialization", |input| {
            length_count(
                context("length", |input| {
                    self.varint_u64_deserializer.deserialize(input)
                }),
                context("data", |input| self.data_deserializer.deserialize(input)),
            )(input)
        })
        .parse(buffer)
    }
}

/// Basic `PreHashSet<_>` serializer
#[derive(Clone)]
pub struct PreHashSetSerializer<T, ST>
where
    ST: Serializer<T>,
{
    len_serializer: U64VarIntSerializer,
    data_serializer: ST,
    phantom_t: PhantomData<T>,
}

impl<T, ST> PreHashSetSerializer<T, ST>
where
    ST: Serializer<T>,
{
    /// Creates a new `PreHashSetSerializer`
    pub fn new(data_serializer: ST) -> Self {
        Self {
            len_serializer: U64VarIntSerializer::new(),
            data_serializer,
            phantom_t: PhantomData,
        }
    }
}

impl<T, ST> Serializer<PreHashSet<T>> for PreHashSetSerializer<T, ST>
where
    ST: Serializer<T>,
    T: PreHashed,
{
    fn serialize(&self, value: &PreHashSet<T>, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        self.len_serializer
            .serialize(&(value.len() as u64), buffer)?;
        for elem in value {
            self.data_serializer.serialize(elem, buffer)?;
        }
        Ok(())
    }
}

/// Basic `PreHashSet<_>` deserializer
#[derive(Clone)]
pub struct PreHashSetDeserializer<T, ST>
where
    ST: Deserializer<T> + Clone,
{
    varint_u64_deserializer: U64VarIntDeserializer,
    data_deserializer: ST,
    phantom_t: PhantomData<T>,
}

impl<T, ST> PreHashSetDeserializer<T, ST>
where
    ST: Deserializer<T> + Clone,
{
    /// Creates a new `PreHashSetDeserializer`
    pub const fn new(
        data_deserializer: ST,
        min_length: Bound<u64>,
        max_length: Bound<u64>,
    ) -> Self {
        Self {
            varint_u64_deserializer: U64VarIntDeserializer::new(min_length, max_length),
            data_deserializer,
            phantom_t: PhantomData,
        }
    }
}

impl<T, ST> Deserializer<PreHashSet<T>> for PreHashSetDeserializer<T, ST>
where
    ST: Deserializer<T> + Clone,
    T: PreHashed + std::cmp::Eq + std::hash::Hash,
{
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], PreHashSet<T>, E> {
        context("Failed PreHashSet<_> deserialization", |input| {
            length_count(
                context("length", |input| {
                    self.varint_u64_deserializer.deserialize(input)
                }),
                context("data", |input| self.data_deserializer.deserialize(input)),
            )(input)
        })
        .map(|vec| vec.into_iter().collect())
        .parse(buffer)
    }
}

#[derive(Clone)]
/// Serializer for `String` with generic serializer for the size of the string
pub struct StringSerializer<SL, L>
where
    SL: Serializer<L>,
    L: TryFrom<usize>,
{
    length_serializer: SL,
    marker_l: std::marker::PhantomData<L>,
}

impl<SL, L> StringSerializer<SL, L>
where
    SL: Serializer<L>,
    L: TryFrom<usize>,
{
    /// Creates a `StringSerializer`.
    ///
    /// # Arguments:
    /// - `length_serializer`: Serializer for the length of the string (should be one of `UXXVarIntSerializer`)
    pub fn new(length_serializer: SL) -> Self {
        Self {
            length_serializer,
            marker_l: std::marker::PhantomData,
        }
    }
}

impl<SL, L> Serializer<String> for StringSerializer<SL, L>
where
    SL: Serializer<L>,
    L: TryFrom<usize>,
{
    fn serialize(&self, value: &String, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        self.length_serializer.serialize(
            &value.len().try_into().map_err(|_| {
                SerializeError::StringTooBig("The string is too big to be serialized".to_string())
            })?,
            buffer,
        )?;
        buffer.extend(value.as_bytes());
        Ok(())
    }
}

/// Deserializer for `String` with generic deserializer for the size of the string
#[derive(Clone)]
pub struct StringDeserializer<DL, L>
where
    DL: Deserializer<L>,
    L: TryFrom<usize> + ToUsize,
{
    length_deserializer: DL,
    marker_l: std::marker::PhantomData<L>,
}

impl<DL, L> StringDeserializer<DL, L>
where
    DL: Deserializer<L>,
    L: TryFrom<usize> + ToUsize,
{
    /// Creates a `StringDeserializer`.
    ///
    /// # Arguments:
    /// - `length_deserializer`: Serializer for the length of the string (should be one of `UXXVarIntSerializer`)
    pub const fn new(length_deserializer: DL) -> Self {
        Self {
            length_deserializer,
            marker_l: std::marker::PhantomData,
        }
    }
}

impl<DL, L> Deserializer<String> for StringDeserializer<DL, L>
where
    DL: Deserializer<L>,
    L: TryFrom<usize> + ToUsize,
{
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], String, E> {
        let (rest, res) = length_data(|input| self.length_deserializer.deserialize(input))
            .map(|data| {
                String::from_utf8(data.to_vec()).map_err(|_| {
                    nom::Err::Error(ParseError::from_error_kind(
                        data,
                        nom::error::ErrorKind::Verify,
                    ))
                })
            })
            .parse(buffer)?;
        Ok((rest, res?))
    }
}

#[derive(Clone)]
/// `BitVec<u8>` Serializer
pub struct BitVecSerializer {
    u32_serializer: U32VarIntSerializer,
}

impl BitVecSerializer {
    /// Create a new `BitVec<u8>` Serializer
    pub fn new() -> BitVecSerializer {
        BitVecSerializer {
            u32_serializer: U32VarIntSerializer::new(),
        }
    }
}

impl Default for BitVecSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<BitVec<u8>> for BitVecSerializer {
    fn serialize(&self, value: &BitVec<u8>, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        let n_entries: u32 = value.len().try_into().map_err(|err| {
            SerializeError::NumberTooBig(format!(
                "too many entries when serializing a `BitVec<u8>`: {}",
                err
            ))
        })?;
        self.u32_serializer.serialize(&n_entries, buffer)?;
        buffer.extend(value.clone().into_vec());
        Ok(())
    }
}

#[derive(Clone)]
/// `BitVec<u8>` Deserializer
pub struct BitVecDeserializer {
    u32_deserializer: U32VarIntDeserializer,
}

impl BitVecDeserializer {
    /// Create a new `BitVec<u8>` Deserializer
    pub fn new() -> BitVecDeserializer {
        BitVecDeserializer {
            u32_deserializer: U32VarIntDeserializer::new(
                Bound::Included(u32::MIN),
                Included(u32::MAX),
            ),
        }
    }
}

impl Default for BitVecDeserializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Deserializer<BitVec<u8>> for BitVecDeserializer {
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], BitVec<u8>, E> {
        context("Failed rng_seed deserialization", |input| {
            let (rest, n_entries) = self.u32_deserializer.deserialize(input)?;
            let bits_u8_len = div_ceil(n_entries, u8::BITS) as usize;
            if rest.len() < bits_u8_len {
                return Err(nom::Err::Error(ParseError::from_error_kind(
                    input,
                    ErrorKind::Eof,
                )));
            }
            let mut rng_seed: BitVec<u8> = BitVec::try_from_vec(rest[..bits_u8_len].to_vec())
                .map_err(|_| nom::Err::Error(ParseError::from_error_kind(input, ErrorKind::Eof)))?;
            rng_seed.truncate(n_entries as usize);
            if rng_seed.len() != n_entries as usize {
                return Err(nom::Err::Error(ParseError::from_error_kind(
                    input,
                    ErrorKind::Eof,
                )));
            }
            Ok((&rest[bits_u8_len..], rng_seed))
        })
        .map(|elements| elements.into_iter().collect())
        .parse(buffer)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use massa_serialization::DeserializeError;
    use serial_test::serial;
    use std::ops::Bound::Included;
    #[test]
    #[serial]
    fn vec_u8() {
        let vec: Vec<u8> = vec![9, 8, 7];
        let vec_u8_serializer = VecU8Serializer::new();
        let vec_u8_deserializer = VecU8Deserializer::new(Included(u64::MIN), Included(u64::MAX));
        let mut serialized = Vec::new();
        vec_u8_serializer.serialize(&vec, &mut serialized).unwrap();
        let (rest, new_vec) = vec_u8_deserializer
            .deserialize::<DeserializeError>(&serialized)
            .unwrap();
        assert!(rest.is_empty());
        assert_eq!(vec, new_vec);
    }

    #[test]
    #[serial]
    fn vec_u8_big_length() {
        let vec: Vec<u8> = vec![9, 8, 7];
        let len: u64 = 10;
        let mut serialized = Vec::new();
        U64VarIntSerializer::new()
            .serialize(&len, &mut serialized)
            .unwrap();
        serialized.extend(vec);
        let vec_u8_deserializer = VecU8Deserializer::new(Included(u64::MIN), Included(u64::MAX));
        let _ = vec_u8_deserializer
            .deserialize::<DeserializeError>(&serialized)
            .expect_err("Should fail too long size");
    }

    #[test]
    #[serial]
    fn vec_u8_min_length() {
        let vec: Vec<u8> = vec![9, 8, 7];
        let len: u64 = 1;
        let mut serialized = Vec::new();
        U64VarIntSerializer::new()
            .serialize(&len, &mut serialized)
            .unwrap();
        serialized.extend(vec);
        let vec_u8_deserializer = VecU8Deserializer::new(Included(u64::MIN), Included(u64::MAX));
        let (rest, res) = vec_u8_deserializer
            .deserialize::<DeserializeError>(&serialized)
            .unwrap();
        assert_eq!(rest, &[8, 7]);
        assert_eq!(res, &[9])
    }

    #[test]
    #[serial]
    fn test_be_min() {
        let x32 = 70_000u32;
        let x64 = 10_000_000_000u64;

        // serialize
        let mut res: Vec<u8> = Vec::new();
        res.extend(x32.to_be_bytes_min(70_001).unwrap());
        assert_eq!(res.len(), 3);
        res.extend(x64.to_be_bytes_min(10_000_000_001).unwrap());
        assert_eq!(res.len(), 3 + 5);

        // serialize fail bounds
        assert!(x32.to_be_bytes_min(69_999).is_err());
        assert!(x64.to_be_bytes_min(9_999_999_999).is_err());

        // deserialize
        let buf = res.as_slice();
        let mut cursor = 0;
        let (out_x32, delta) = u32::from_be_bytes_min(&buf[cursor..], 70_001).unwrap();
        assert_eq!(out_x32, x32);
        cursor += delta;
        let (out_x64, delta) = u64::from_be_bytes_min(&buf[cursor..], 10_000_000_001).unwrap();
        assert_eq!(out_x64, x64);
        cursor += delta;
        assert_eq!(cursor, buf.len());
    }

    #[test]
    #[serial]
    fn test_array_from_slice_with_zero_u64() {
        let zero: u64 = 0;
        let res = array_from_slice(&zero.to_be_bytes()).unwrap();
        assert_eq!(zero, u64::from_be_bytes(res));
    }
}