casper_types/
bytesrepr.rs

1//! Contains serialization and deserialization code for types used throughout the system.
2mod bytes;
3
4use alloc::{
5    collections::{BTreeMap, BTreeSet, VecDeque},
6    str,
7    string::String,
8    vec,
9    vec::Vec,
10};
11#[cfg(debug_assertions)]
12use core::any;
13use core::{
14    convert::TryInto,
15    fmt::{self, Display, Formatter},
16    mem,
17};
18
19#[cfg(feature = "datasize")]
20use datasize::DataSize;
21use num_integer::Integer;
22use num_rational::Ratio;
23use serde::{Deserialize, Serialize};
24
25pub use bytes::Bytes;
26
27/// The number of bytes in a serialized `()`.
28pub const UNIT_SERIALIZED_LENGTH: usize = 0;
29/// The number of bytes in a serialized `bool`.
30pub const BOOL_SERIALIZED_LENGTH: usize = 1;
31/// The number of bytes in a serialized `i32`.
32pub const I32_SERIALIZED_LENGTH: usize = mem::size_of::<i32>();
33/// The number of bytes in a serialized `i64`.
34pub const I64_SERIALIZED_LENGTH: usize = mem::size_of::<i64>();
35/// The number of bytes in a serialized `u8`.
36pub const U8_SERIALIZED_LENGTH: usize = mem::size_of::<u8>();
37/// The number of bytes in a serialized `u16`.
38pub const U16_SERIALIZED_LENGTH: usize = mem::size_of::<u16>();
39/// The number of bytes in a serialized `u32`.
40pub const U32_SERIALIZED_LENGTH: usize = mem::size_of::<u32>();
41/// The number of bytes in a serialized `u64`.
42pub const U64_SERIALIZED_LENGTH: usize = mem::size_of::<u64>();
43/// The number of bytes in a serialized [`U128`](crate::U128).
44pub const U128_SERIALIZED_LENGTH: usize = mem::size_of::<u128>();
45/// The number of bytes in a serialized [`U256`](crate::U256).
46pub const U256_SERIALIZED_LENGTH: usize = U128_SERIALIZED_LENGTH * 2;
47/// The number of bytes in a serialized [`U512`](crate::U512).
48pub const U512_SERIALIZED_LENGTH: usize = U256_SERIALIZED_LENGTH * 2;
49/// The tag representing a `None` value.
50pub const OPTION_NONE_TAG: u8 = 0;
51/// The tag representing a `Some` value.
52pub const OPTION_SOME_TAG: u8 = 1;
53/// The tag representing an `Err` value.
54pub const RESULT_ERR_TAG: u8 = 0;
55/// The tag representing an `Ok` value.
56pub const RESULT_OK_TAG: u8 = 1;
57
58/// A type which can be serialized to a `Vec<u8>`.
59pub trait ToBytes {
60    /// Serializes `&self` to a `Vec<u8>`.
61    fn to_bytes(&self) -> Result<Vec<u8>, Error>;
62    /// Consumes `self` and serializes to a `Vec<u8>`.
63    fn into_bytes(self) -> Result<Vec<u8>, Error>
64    where
65        Self: Sized,
66    {
67        self.to_bytes()
68    }
69    /// Returns the length of the `Vec<u8>` which would be returned from a successful call to
70    /// `to_bytes()` or `into_bytes()`.  The data is not actually serialized, so this call is
71    /// relatively cheap.
72    fn serialized_length(&self) -> usize;
73
74    /// Writes `&self` into a mutable `writer`.
75    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
76        writer.extend(self.to_bytes()?);
77        Ok(())
78    }
79}
80
81/// A type which can be deserialized from a `Vec<u8>`.
82pub trait FromBytes: Sized {
83    /// Deserializes the slice into `Self`.
84    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error>;
85
86    /// Deserializes the `Vec<u8>` into `Self`.
87    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), Error> {
88        Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
89    }
90}
91
92/// Returns a `Vec<u8>` initialized with sufficient capacity to hold `to_be_serialized` after
93/// serialization.
94pub fn unchecked_allocate_buffer<T: ToBytes>(to_be_serialized: &T) -> Vec<u8> {
95    let serialized_length = to_be_serialized.serialized_length();
96    Vec::with_capacity(serialized_length)
97}
98
99/// Returns a `Vec<u8>` initialized with sufficient capacity to hold `to_be_serialized` after
100/// serialization, or an error if the capacity would exceed `u32::max_value()`.
101pub fn allocate_buffer<T: ToBytes>(to_be_serialized: &T) -> Result<Vec<u8>, Error> {
102    let serialized_length = to_be_serialized.serialized_length();
103    if serialized_length > u32::max_value() as usize {
104        return Err(Error::OutOfMemory);
105    }
106    Ok(Vec::with_capacity(serialized_length))
107}
108
109/// Serialization and deserialization errors.
110#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
111#[cfg_attr(feature = "datasize", derive(DataSize))]
112#[repr(u8)]
113#[non_exhaustive]
114pub enum Error {
115    /// Early end of stream while deserializing.
116    EarlyEndOfStream = 0,
117    /// Formatting error while deserializing.
118    Formatting,
119    /// Not all input bytes were consumed in [`deserialize`].
120    LeftOverBytes,
121    /// Out of memory error.
122    OutOfMemory,
123    /// No serialized representation is available for a value.
124    NotRepresentable,
125    /// Exceeded a recursion depth limit.
126    ExceededRecursionDepth,
127}
128
129impl Display for Error {
130    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
131        match self {
132            Error::EarlyEndOfStream => {
133                formatter.write_str("Deserialization error: early end of stream")
134            }
135            Error::Formatting => formatter.write_str("Deserialization error: formatting"),
136            Error::LeftOverBytes => formatter.write_str("Deserialization error: left-over bytes"),
137            Error::OutOfMemory => formatter.write_str("Serialization error: out of memory"),
138            Error::NotRepresentable => {
139                formatter.write_str("Serialization error: value is not representable.")
140            }
141            Error::ExceededRecursionDepth => formatter.write_str("exceeded recursion depth"),
142        }
143    }
144}
145
146/// Deserializes `bytes` into an instance of `T`.
147///
148/// Returns an error if the bytes cannot be deserialized into `T` or if not all of the input bytes
149/// are consumed in the operation.
150pub fn deserialize<T: FromBytes>(bytes: Vec<u8>) -> Result<T, Error> {
151    let (t, remainder) = T::from_bytes(&bytes)?;
152    if remainder.is_empty() {
153        Ok(t)
154    } else {
155        Err(Error::LeftOverBytes)
156    }
157}
158
159/// Deserializes a slice of bytes into an instance of `T`.
160///
161/// Returns an error if the bytes cannot be deserialized into `T` or if not all of the input bytes
162/// are consumed in the operation.
163pub fn deserialize_from_slice<I: AsRef<[u8]>, O: FromBytes>(bytes: I) -> Result<O, Error> {
164    let (t, remainder) = O::from_bytes(bytes.as_ref())?;
165    if remainder.is_empty() {
166        Ok(t)
167    } else {
168        Err(Error::LeftOverBytes)
169    }
170}
171
172/// Serializes `t` into a `Vec<u8>`.
173pub fn serialize(t: impl ToBytes) -> Result<Vec<u8>, Error> {
174    t.into_bytes()
175}
176
177/// Safely splits the slice at the given point.
178pub(crate) fn safe_split_at(bytes: &[u8], n: usize) -> Result<(&[u8], &[u8]), Error> {
179    if n > bytes.len() {
180        Err(Error::EarlyEndOfStream)
181    } else {
182        Ok(bytes.split_at(n))
183    }
184}
185
186impl ToBytes for () {
187    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
188        Ok(Vec::new())
189    }
190
191    fn serialized_length(&self) -> usize {
192        UNIT_SERIALIZED_LENGTH
193    }
194}
195
196impl FromBytes for () {
197    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
198        Ok(((), bytes))
199    }
200}
201
202impl ToBytes for bool {
203    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
204        u8::from(*self).to_bytes()
205    }
206
207    fn serialized_length(&self) -> usize {
208        BOOL_SERIALIZED_LENGTH
209    }
210
211    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
212        writer.push(*self as u8);
213        Ok(())
214    }
215}
216
217impl FromBytes for bool {
218    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
219        match bytes.split_first() {
220            None => Err(Error::EarlyEndOfStream),
221            Some((byte, rem)) => match byte {
222                1 => Ok((true, rem)),
223                0 => Ok((false, rem)),
224                _ => Err(Error::Formatting),
225            },
226        }
227    }
228}
229
230impl ToBytes for u8 {
231    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
232        Ok(vec![*self])
233    }
234
235    fn serialized_length(&self) -> usize {
236        U8_SERIALIZED_LENGTH
237    }
238
239    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
240        writer.push(*self);
241        Ok(())
242    }
243}
244
245impl FromBytes for u8 {
246    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
247        match bytes.split_first() {
248            None => Err(Error::EarlyEndOfStream),
249            Some((byte, rem)) => Ok((*byte, rem)),
250        }
251    }
252}
253
254impl ToBytes for i32 {
255    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
256        Ok(self.to_le_bytes().to_vec())
257    }
258
259    fn serialized_length(&self) -> usize {
260        I32_SERIALIZED_LENGTH
261    }
262
263    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
264        writer.extend_from_slice(&self.to_le_bytes());
265        Ok(())
266    }
267}
268
269impl FromBytes for i32 {
270    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
271        let mut result = [0u8; I32_SERIALIZED_LENGTH];
272        let (bytes, remainder) = safe_split_at(bytes, I32_SERIALIZED_LENGTH)?;
273        result.copy_from_slice(bytes);
274        Ok((<i32>::from_le_bytes(result), remainder))
275    }
276}
277
278impl ToBytes for i64 {
279    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
280        Ok(self.to_le_bytes().to_vec())
281    }
282
283    fn serialized_length(&self) -> usize {
284        I64_SERIALIZED_LENGTH
285    }
286
287    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
288        writer.extend_from_slice(&self.to_le_bytes());
289        Ok(())
290    }
291}
292
293impl FromBytes for i64 {
294    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
295        let mut result = [0u8; I64_SERIALIZED_LENGTH];
296        let (bytes, remainder) = safe_split_at(bytes, I64_SERIALIZED_LENGTH)?;
297        result.copy_from_slice(bytes);
298        Ok((<i64>::from_le_bytes(result), remainder))
299    }
300}
301
302impl ToBytes for u16 {
303    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
304        Ok(self.to_le_bytes().to_vec())
305    }
306
307    fn serialized_length(&self) -> usize {
308        U16_SERIALIZED_LENGTH
309    }
310
311    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
312        writer.extend_from_slice(&self.to_le_bytes());
313        Ok(())
314    }
315}
316
317impl FromBytes for u16 {
318    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
319        let mut result = [0u8; U16_SERIALIZED_LENGTH];
320        let (bytes, remainder) = safe_split_at(bytes, U16_SERIALIZED_LENGTH)?;
321        result.copy_from_slice(bytes);
322        Ok((<u16>::from_le_bytes(result), remainder))
323    }
324}
325
326impl ToBytes for u32 {
327    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
328        Ok(self.to_le_bytes().to_vec())
329    }
330
331    fn serialized_length(&self) -> usize {
332        U32_SERIALIZED_LENGTH
333    }
334
335    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
336        writer.extend_from_slice(&self.to_le_bytes());
337        Ok(())
338    }
339}
340
341impl FromBytes for u32 {
342    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
343        let mut result = [0u8; U32_SERIALIZED_LENGTH];
344        let (bytes, remainder) = safe_split_at(bytes, U32_SERIALIZED_LENGTH)?;
345        result.copy_from_slice(bytes);
346        Ok((<u32>::from_le_bytes(result), remainder))
347    }
348}
349
350impl ToBytes for u64 {
351    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
352        Ok(self.to_le_bytes().to_vec())
353    }
354
355    fn serialized_length(&self) -> usize {
356        U64_SERIALIZED_LENGTH
357    }
358
359    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
360        writer.extend_from_slice(&self.to_le_bytes());
361        Ok(())
362    }
363}
364
365impl FromBytes for u64 {
366    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
367        let mut result = [0u8; U64_SERIALIZED_LENGTH];
368        let (bytes, remainder) = safe_split_at(bytes, U64_SERIALIZED_LENGTH)?;
369        result.copy_from_slice(bytes);
370        Ok((<u64>::from_le_bytes(result), remainder))
371    }
372}
373
374impl ToBytes for String {
375    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
376        let bytes = self.as_bytes();
377        u8_slice_to_bytes(bytes)
378    }
379
380    fn serialized_length(&self) -> usize {
381        u8_slice_serialized_length(self.as_bytes())
382    }
383
384    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
385        write_u8_slice(self.as_bytes(), writer)?;
386        Ok(())
387    }
388}
389
390impl FromBytes for String {
391    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
392        let (size, remainder) = u32::from_bytes(bytes)?;
393        let (str_bytes, remainder) = safe_split_at(remainder, size as usize)?;
394        let result = String::from_utf8(str_bytes.to_vec()).map_err(|_| Error::Formatting)?;
395        Ok((result, remainder))
396    }
397}
398
399fn ensure_efficient_serialization<T>() {
400    #[cfg(debug_assertions)]
401    debug_assert_ne!(
402        any::type_name::<T>(),
403        any::type_name::<u8>(),
404        "You should use Bytes newtype wrapper for efficiency"
405    );
406}
407
408fn iterator_serialized_length<'a, T: 'a + ToBytes>(ts: impl Iterator<Item = &'a T>) -> usize {
409    U32_SERIALIZED_LENGTH + ts.map(ToBytes::serialized_length).sum::<usize>()
410}
411
412impl<T: ToBytes> ToBytes for Vec<T> {
413    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
414        ensure_efficient_serialization::<T>();
415
416        let mut result = Vec::with_capacity(self.serialized_length());
417        let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
418        result.append(&mut length_32.to_bytes()?);
419
420        for item in self.iter() {
421            result.append(&mut item.to_bytes()?);
422        }
423
424        Ok(result)
425    }
426
427    fn into_bytes(self) -> Result<Vec<u8>, Error> {
428        ensure_efficient_serialization::<T>();
429
430        let mut result = allocate_buffer(&self)?;
431        let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
432        result.append(&mut length_32.to_bytes()?);
433
434        for item in self {
435            result.append(&mut item.into_bytes()?);
436        }
437
438        Ok(result)
439    }
440
441    fn serialized_length(&self) -> usize {
442        iterator_serialized_length(self.iter())
443    }
444
445    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
446        let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
447        writer.extend_from_slice(&length_32.to_le_bytes());
448        for item in self.iter() {
449            item.write_bytes(writer)?;
450        }
451        Ok(())
452    }
453}
454
455fn vec_from_vec<T: FromBytes>(bytes: Vec<u8>) -> Result<(Vec<T>, Vec<u8>), Error> {
456    ensure_efficient_serialization::<T>();
457
458    Vec::<T>::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
459}
460
461/// Returns a conservative estimate for the preallocated number of elements for a new `Vec<T>`.
462///
463/// `hint` indicates the desired upper limit in heap size (in bytes), which is itself bounded by
464/// 4096 bytes. This function will never return less than 1.
465#[inline]
466fn cautious<T>(hint: usize) -> usize {
467    let el_size = core::mem::size_of::<T>();
468    core::cmp::max(core::cmp::min(hint, 4096 / el_size), 1)
469}
470
471impl<T: FromBytes> FromBytes for Vec<T> {
472    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
473        ensure_efficient_serialization::<T>();
474
475        let (count, mut stream) = u32::from_bytes(bytes)?;
476
477        if count == 0 {
478            return Ok((Vec::new(), stream));
479        }
480
481        let mut result = Vec::with_capacity(cautious::<T>(count as usize));
482
483        for _ in 0..count {
484            let (value, remainder) = T::from_bytes(stream)?;
485            result.push(value);
486            stream = remainder;
487        }
488
489        Ok((result, stream))
490    }
491
492    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), Error> {
493        vec_from_vec(bytes)
494    }
495}
496
497impl<T: ToBytes> ToBytes for VecDeque<T> {
498    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
499        let (slice1, slice2) = self.as_slices();
500        let mut result = allocate_buffer(self)?;
501        let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
502        result.append(&mut length_32.to_bytes()?);
503        for item in slice1.iter().chain(slice2.iter()) {
504            result.append(&mut item.to_bytes()?);
505        }
506        Ok(result)
507    }
508
509    fn into_bytes(self) -> Result<Vec<u8>, Error> {
510        let vec: Vec<T> = self.into();
511        vec.to_bytes()
512    }
513
514    fn serialized_length(&self) -> usize {
515        let (slice1, slice2) = self.as_slices();
516        iterator_serialized_length(slice1.iter().chain(slice2.iter()))
517    }
518}
519
520impl<T: FromBytes> FromBytes for VecDeque<T> {
521    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
522        let (vec, bytes) = Vec::from_bytes(bytes)?;
523        Ok((VecDeque::from(vec), bytes))
524    }
525
526    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), Error> {
527        let (vec, bytes) = vec_from_vec(bytes)?;
528        Ok((VecDeque::from(vec), bytes))
529    }
530}
531
532impl<const COUNT: usize> ToBytes for [u8; COUNT] {
533    #[inline(always)]
534    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
535        Ok(self.to_vec())
536    }
537
538    #[inline(always)]
539    fn serialized_length(&self) -> usize {
540        COUNT
541    }
542
543    #[inline(always)]
544    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
545        writer.extend_from_slice(self);
546        Ok(())
547    }
548}
549
550impl<const COUNT: usize> FromBytes for [u8; COUNT] {
551    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
552        let (bytes, rem) = safe_split_at(bytes, COUNT)?;
553        // SAFETY: safe_split_at makes sure `bytes` is exactly `COUNT` bytes.
554        let ptr = bytes.as_ptr() as *const [u8; COUNT];
555        let result = unsafe { *ptr };
556        Ok((result, rem))
557    }
558}
559
560impl<V: ToBytes> ToBytes for BTreeSet<V> {
561    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
562        let mut result = allocate_buffer(self)?;
563
564        let num_keys: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
565        result.append(&mut num_keys.to_bytes()?);
566
567        for value in self.iter() {
568            result.append(&mut value.to_bytes()?);
569        }
570
571        Ok(result)
572    }
573
574    fn serialized_length(&self) -> usize {
575        U32_SERIALIZED_LENGTH + self.iter().map(|v| v.serialized_length()).sum::<usize>()
576    }
577
578    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
579        let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
580        writer.extend_from_slice(&length_32.to_le_bytes());
581        for value in self.iter() {
582            value.write_bytes(writer)?;
583        }
584        Ok(())
585    }
586}
587
588impl<V: FromBytes + Ord> FromBytes for BTreeSet<V> {
589    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
590        let (num_keys, mut stream) = u32::from_bytes(bytes)?;
591        let mut result = BTreeSet::new();
592        for _ in 0..num_keys {
593            let (v, rem) = V::from_bytes(stream)?;
594            result.insert(v);
595            stream = rem;
596        }
597        Ok((result, stream))
598    }
599}
600
601impl<K, V> ToBytes for BTreeMap<K, V>
602where
603    K: ToBytes,
604    V: ToBytes,
605{
606    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
607        let mut result = allocate_buffer(self)?;
608
609        let num_keys: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
610        result.append(&mut num_keys.to_bytes()?);
611
612        for (key, value) in self.iter() {
613            result.append(&mut key.to_bytes()?);
614            result.append(&mut value.to_bytes()?);
615        }
616
617        Ok(result)
618    }
619
620    fn serialized_length(&self) -> usize {
621        U32_SERIALIZED_LENGTH
622            + self
623                .iter()
624                .map(|(key, value)| key.serialized_length() + value.serialized_length())
625                .sum::<usize>()
626    }
627
628    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
629        let length_32: u32 = self.len().try_into().map_err(|_| Error::NotRepresentable)?;
630        writer.extend_from_slice(&length_32.to_le_bytes());
631        for (key, value) in self.iter() {
632            key.write_bytes(writer)?;
633            value.write_bytes(writer)?;
634        }
635        Ok(())
636    }
637}
638
639impl<K, V> FromBytes for BTreeMap<K, V>
640where
641    K: FromBytes + Ord,
642    V: FromBytes,
643{
644    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
645        let (num_keys, mut stream) = u32::from_bytes(bytes)?;
646        let mut result = BTreeMap::new();
647        for _ in 0..num_keys {
648            let (k, rem) = K::from_bytes(stream)?;
649            let (v, rem) = V::from_bytes(rem)?;
650            result.insert(k, v);
651            stream = rem;
652        }
653        Ok((result, stream))
654    }
655}
656
657impl<T: ToBytes> ToBytes for Option<T> {
658    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
659        match self {
660            None => Ok(vec![OPTION_NONE_TAG]),
661            Some(v) => {
662                let mut result = allocate_buffer(self)?;
663                result.push(OPTION_SOME_TAG);
664
665                let mut value = v.to_bytes()?;
666                result.append(&mut value);
667
668                Ok(result)
669            }
670        }
671    }
672
673    fn serialized_length(&self) -> usize {
674        U8_SERIALIZED_LENGTH
675            + match self {
676                Some(v) => v.serialized_length(),
677                None => 0,
678            }
679    }
680
681    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
682        match self {
683            None => writer.push(OPTION_NONE_TAG),
684            Some(v) => {
685                writer.push(OPTION_SOME_TAG);
686                v.write_bytes(writer)?;
687            }
688        };
689        Ok(())
690    }
691}
692
693impl<T: FromBytes> FromBytes for Option<T> {
694    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
695        let (tag, rem) = u8::from_bytes(bytes)?;
696        match tag {
697            OPTION_NONE_TAG => Ok((None, rem)),
698            OPTION_SOME_TAG => {
699                let (t, rem) = T::from_bytes(rem)?;
700                Ok((Some(t), rem))
701            }
702            _ => Err(Error::Formatting),
703        }
704    }
705}
706
707impl<T: ToBytes, E: ToBytes> ToBytes for Result<T, E> {
708    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
709        let mut result = allocate_buffer(self)?;
710        let (variant, mut value) = match self {
711            Err(error) => (RESULT_ERR_TAG, error.to_bytes()?),
712            Ok(result) => (RESULT_OK_TAG, result.to_bytes()?),
713        };
714        result.push(variant);
715        result.append(&mut value);
716        Ok(result)
717    }
718
719    fn serialized_length(&self) -> usize {
720        U8_SERIALIZED_LENGTH
721            + match self {
722                Ok(ok) => ok.serialized_length(),
723                Err(error) => error.serialized_length(),
724            }
725    }
726
727    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
728        match self {
729            Err(error) => {
730                writer.push(RESULT_ERR_TAG);
731                error.write_bytes(writer)?;
732            }
733            Ok(result) => {
734                writer.push(RESULT_OK_TAG);
735                result.write_bytes(writer)?;
736            }
737        };
738        Ok(())
739    }
740}
741
742impl<T: FromBytes, E: FromBytes> FromBytes for Result<T, E> {
743    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
744        let (variant, rem) = u8::from_bytes(bytes)?;
745        match variant {
746            RESULT_ERR_TAG => {
747                let (value, rem) = E::from_bytes(rem)?;
748                Ok((Err(value), rem))
749            }
750            RESULT_OK_TAG => {
751                let (value, rem) = T::from_bytes(rem)?;
752                Ok((Ok(value), rem))
753            }
754            _ => Err(Error::Formatting),
755        }
756    }
757}
758
759impl<T1: ToBytes> ToBytes for (T1,) {
760    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
761        self.0.to_bytes()
762    }
763
764    fn serialized_length(&self) -> usize {
765        self.0.serialized_length()
766    }
767}
768
769impl<T1: FromBytes> FromBytes for (T1,) {
770    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
771        let (t1, remainder) = T1::from_bytes(bytes)?;
772        Ok(((t1,), remainder))
773    }
774}
775
776impl<T1: ToBytes, T2: ToBytes> ToBytes for (T1, T2) {
777    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
778        let mut result = allocate_buffer(self)?;
779        result.append(&mut self.0.to_bytes()?);
780        result.append(&mut self.1.to_bytes()?);
781        Ok(result)
782    }
783
784    fn serialized_length(&self) -> usize {
785        self.0.serialized_length() + self.1.serialized_length()
786    }
787}
788
789impl<T1: FromBytes, T2: FromBytes> FromBytes for (T1, T2) {
790    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
791        let (t1, remainder) = T1::from_bytes(bytes)?;
792        let (t2, remainder) = T2::from_bytes(remainder)?;
793        Ok(((t1, t2), remainder))
794    }
795}
796
797impl<T1: ToBytes, T2: ToBytes, T3: ToBytes> ToBytes for (T1, T2, T3) {
798    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
799        let mut result = allocate_buffer(self)?;
800        result.append(&mut self.0.to_bytes()?);
801        result.append(&mut self.1.to_bytes()?);
802        result.append(&mut self.2.to_bytes()?);
803        Ok(result)
804    }
805
806    fn serialized_length(&self) -> usize {
807        self.0.serialized_length() + self.1.serialized_length() + self.2.serialized_length()
808    }
809}
810
811impl<T1: FromBytes, T2: FromBytes, T3: FromBytes> FromBytes for (T1, T2, T3) {
812    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
813        let (t1, remainder) = T1::from_bytes(bytes)?;
814        let (t2, remainder) = T2::from_bytes(remainder)?;
815        let (t3, remainder) = T3::from_bytes(remainder)?;
816        Ok(((t1, t2, t3), remainder))
817    }
818}
819
820impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes> ToBytes for (T1, T2, T3, T4) {
821    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
822        let mut result = allocate_buffer(self)?;
823        result.append(&mut self.0.to_bytes()?);
824        result.append(&mut self.1.to_bytes()?);
825        result.append(&mut self.2.to_bytes()?);
826        result.append(&mut self.3.to_bytes()?);
827        Ok(result)
828    }
829
830    fn serialized_length(&self) -> usize {
831        self.0.serialized_length()
832            + self.1.serialized_length()
833            + self.2.serialized_length()
834            + self.3.serialized_length()
835    }
836}
837
838impl<T1: FromBytes, T2: FromBytes, T3: FromBytes, T4: FromBytes> FromBytes for (T1, T2, T3, T4) {
839    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
840        let (t1, remainder) = T1::from_bytes(bytes)?;
841        let (t2, remainder) = T2::from_bytes(remainder)?;
842        let (t3, remainder) = T3::from_bytes(remainder)?;
843        let (t4, remainder) = T4::from_bytes(remainder)?;
844        Ok(((t1, t2, t3, t4), remainder))
845    }
846}
847
848impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes, T5: ToBytes> ToBytes
849    for (T1, T2, T3, T4, T5)
850{
851    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
852        let mut result = allocate_buffer(self)?;
853        result.append(&mut self.0.to_bytes()?);
854        result.append(&mut self.1.to_bytes()?);
855        result.append(&mut self.2.to_bytes()?);
856        result.append(&mut self.3.to_bytes()?);
857        result.append(&mut self.4.to_bytes()?);
858        Ok(result)
859    }
860
861    fn serialized_length(&self) -> usize {
862        self.0.serialized_length()
863            + self.1.serialized_length()
864            + self.2.serialized_length()
865            + self.3.serialized_length()
866            + self.4.serialized_length()
867    }
868}
869
870impl<T1: FromBytes, T2: FromBytes, T3: FromBytes, T4: FromBytes, T5: FromBytes> FromBytes
871    for (T1, T2, T3, T4, T5)
872{
873    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
874        let (t1, remainder) = T1::from_bytes(bytes)?;
875        let (t2, remainder) = T2::from_bytes(remainder)?;
876        let (t3, remainder) = T3::from_bytes(remainder)?;
877        let (t4, remainder) = T4::from_bytes(remainder)?;
878        let (t5, remainder) = T5::from_bytes(remainder)?;
879        Ok(((t1, t2, t3, t4, t5), remainder))
880    }
881}
882
883impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes, T5: ToBytes, T6: ToBytes> ToBytes
884    for (T1, T2, T3, T4, T5, T6)
885{
886    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
887        let mut result = allocate_buffer(self)?;
888        result.append(&mut self.0.to_bytes()?);
889        result.append(&mut self.1.to_bytes()?);
890        result.append(&mut self.2.to_bytes()?);
891        result.append(&mut self.3.to_bytes()?);
892        result.append(&mut self.4.to_bytes()?);
893        result.append(&mut self.5.to_bytes()?);
894        Ok(result)
895    }
896
897    fn serialized_length(&self) -> usize {
898        self.0.serialized_length()
899            + self.1.serialized_length()
900            + self.2.serialized_length()
901            + self.3.serialized_length()
902            + self.4.serialized_length()
903            + self.5.serialized_length()
904    }
905}
906
907impl<T1: FromBytes, T2: FromBytes, T3: FromBytes, T4: FromBytes, T5: FromBytes, T6: FromBytes>
908    FromBytes for (T1, T2, T3, T4, T5, T6)
909{
910    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
911        let (t1, remainder) = T1::from_bytes(bytes)?;
912        let (t2, remainder) = T2::from_bytes(remainder)?;
913        let (t3, remainder) = T3::from_bytes(remainder)?;
914        let (t4, remainder) = T4::from_bytes(remainder)?;
915        let (t5, remainder) = T5::from_bytes(remainder)?;
916        let (t6, remainder) = T6::from_bytes(remainder)?;
917        Ok(((t1, t2, t3, t4, t5, t6), remainder))
918    }
919}
920
921impl<T1: ToBytes, T2: ToBytes, T3: ToBytes, T4: ToBytes, T5: ToBytes, T6: ToBytes, T7: ToBytes>
922    ToBytes for (T1, T2, T3, T4, T5, T6, T7)
923{
924    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
925        let mut result = allocate_buffer(self)?;
926        result.append(&mut self.0.to_bytes()?);
927        result.append(&mut self.1.to_bytes()?);
928        result.append(&mut self.2.to_bytes()?);
929        result.append(&mut self.3.to_bytes()?);
930        result.append(&mut self.4.to_bytes()?);
931        result.append(&mut self.5.to_bytes()?);
932        result.append(&mut self.6.to_bytes()?);
933        Ok(result)
934    }
935
936    fn serialized_length(&self) -> usize {
937        self.0.serialized_length()
938            + self.1.serialized_length()
939            + self.2.serialized_length()
940            + self.3.serialized_length()
941            + self.4.serialized_length()
942            + self.5.serialized_length()
943            + self.6.serialized_length()
944    }
945}
946
947impl<
948        T1: FromBytes,
949        T2: FromBytes,
950        T3: FromBytes,
951        T4: FromBytes,
952        T5: FromBytes,
953        T6: FromBytes,
954        T7: FromBytes,
955    > FromBytes for (T1, T2, T3, T4, T5, T6, T7)
956{
957    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
958        let (t1, remainder) = T1::from_bytes(bytes)?;
959        let (t2, remainder) = T2::from_bytes(remainder)?;
960        let (t3, remainder) = T3::from_bytes(remainder)?;
961        let (t4, remainder) = T4::from_bytes(remainder)?;
962        let (t5, remainder) = T5::from_bytes(remainder)?;
963        let (t6, remainder) = T6::from_bytes(remainder)?;
964        let (t7, remainder) = T7::from_bytes(remainder)?;
965        Ok(((t1, t2, t3, t4, t5, t6, t7), remainder))
966    }
967}
968
969impl<
970        T1: ToBytes,
971        T2: ToBytes,
972        T3: ToBytes,
973        T4: ToBytes,
974        T5: ToBytes,
975        T6: ToBytes,
976        T7: ToBytes,
977        T8: ToBytes,
978    > ToBytes for (T1, T2, T3, T4, T5, T6, T7, T8)
979{
980    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
981        let mut result = allocate_buffer(self)?;
982        result.append(&mut self.0.to_bytes()?);
983        result.append(&mut self.1.to_bytes()?);
984        result.append(&mut self.2.to_bytes()?);
985        result.append(&mut self.3.to_bytes()?);
986        result.append(&mut self.4.to_bytes()?);
987        result.append(&mut self.5.to_bytes()?);
988        result.append(&mut self.6.to_bytes()?);
989        result.append(&mut self.7.to_bytes()?);
990        Ok(result)
991    }
992
993    fn serialized_length(&self) -> usize {
994        self.0.serialized_length()
995            + self.1.serialized_length()
996            + self.2.serialized_length()
997            + self.3.serialized_length()
998            + self.4.serialized_length()
999            + self.5.serialized_length()
1000            + self.6.serialized_length()
1001            + self.7.serialized_length()
1002    }
1003}
1004
1005impl<
1006        T1: FromBytes,
1007        T2: FromBytes,
1008        T3: FromBytes,
1009        T4: FromBytes,
1010        T5: FromBytes,
1011        T6: FromBytes,
1012        T7: FromBytes,
1013        T8: FromBytes,
1014    > FromBytes for (T1, T2, T3, T4, T5, T6, T7, T8)
1015{
1016    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1017        let (t1, remainder) = T1::from_bytes(bytes)?;
1018        let (t2, remainder) = T2::from_bytes(remainder)?;
1019        let (t3, remainder) = T3::from_bytes(remainder)?;
1020        let (t4, remainder) = T4::from_bytes(remainder)?;
1021        let (t5, remainder) = T5::from_bytes(remainder)?;
1022        let (t6, remainder) = T6::from_bytes(remainder)?;
1023        let (t7, remainder) = T7::from_bytes(remainder)?;
1024        let (t8, remainder) = T8::from_bytes(remainder)?;
1025        Ok(((t1, t2, t3, t4, t5, t6, t7, t8), remainder))
1026    }
1027}
1028
1029impl<
1030        T1: ToBytes,
1031        T2: ToBytes,
1032        T3: ToBytes,
1033        T4: ToBytes,
1034        T5: ToBytes,
1035        T6: ToBytes,
1036        T7: ToBytes,
1037        T8: ToBytes,
1038        T9: ToBytes,
1039    > ToBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9)
1040{
1041    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1042        let mut result = allocate_buffer(self)?;
1043        result.append(&mut self.0.to_bytes()?);
1044        result.append(&mut self.1.to_bytes()?);
1045        result.append(&mut self.2.to_bytes()?);
1046        result.append(&mut self.3.to_bytes()?);
1047        result.append(&mut self.4.to_bytes()?);
1048        result.append(&mut self.5.to_bytes()?);
1049        result.append(&mut self.6.to_bytes()?);
1050        result.append(&mut self.7.to_bytes()?);
1051        result.append(&mut self.8.to_bytes()?);
1052        Ok(result)
1053    }
1054
1055    fn serialized_length(&self) -> usize {
1056        self.0.serialized_length()
1057            + self.1.serialized_length()
1058            + self.2.serialized_length()
1059            + self.3.serialized_length()
1060            + self.4.serialized_length()
1061            + self.5.serialized_length()
1062            + self.6.serialized_length()
1063            + self.7.serialized_length()
1064            + self.8.serialized_length()
1065    }
1066}
1067
1068impl<
1069        T1: FromBytes,
1070        T2: FromBytes,
1071        T3: FromBytes,
1072        T4: FromBytes,
1073        T5: FromBytes,
1074        T6: FromBytes,
1075        T7: FromBytes,
1076        T8: FromBytes,
1077        T9: FromBytes,
1078    > FromBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9)
1079{
1080    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1081        let (t1, remainder) = T1::from_bytes(bytes)?;
1082        let (t2, remainder) = T2::from_bytes(remainder)?;
1083        let (t3, remainder) = T3::from_bytes(remainder)?;
1084        let (t4, remainder) = T4::from_bytes(remainder)?;
1085        let (t5, remainder) = T5::from_bytes(remainder)?;
1086        let (t6, remainder) = T6::from_bytes(remainder)?;
1087        let (t7, remainder) = T7::from_bytes(remainder)?;
1088        let (t8, remainder) = T8::from_bytes(remainder)?;
1089        let (t9, remainder) = T9::from_bytes(remainder)?;
1090        Ok(((t1, t2, t3, t4, t5, t6, t7, t8, t9), remainder))
1091    }
1092}
1093
1094impl<
1095        T1: ToBytes,
1096        T2: ToBytes,
1097        T3: ToBytes,
1098        T4: ToBytes,
1099        T5: ToBytes,
1100        T6: ToBytes,
1101        T7: ToBytes,
1102        T8: ToBytes,
1103        T9: ToBytes,
1104        T10: ToBytes,
1105    > ToBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)
1106{
1107    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1108        let mut result = allocate_buffer(self)?;
1109        result.append(&mut self.0.to_bytes()?);
1110        result.append(&mut self.1.to_bytes()?);
1111        result.append(&mut self.2.to_bytes()?);
1112        result.append(&mut self.3.to_bytes()?);
1113        result.append(&mut self.4.to_bytes()?);
1114        result.append(&mut self.5.to_bytes()?);
1115        result.append(&mut self.6.to_bytes()?);
1116        result.append(&mut self.7.to_bytes()?);
1117        result.append(&mut self.8.to_bytes()?);
1118        result.append(&mut self.9.to_bytes()?);
1119        Ok(result)
1120    }
1121
1122    fn serialized_length(&self) -> usize {
1123        self.0.serialized_length()
1124            + self.1.serialized_length()
1125            + self.2.serialized_length()
1126            + self.3.serialized_length()
1127            + self.4.serialized_length()
1128            + self.5.serialized_length()
1129            + self.6.serialized_length()
1130            + self.7.serialized_length()
1131            + self.8.serialized_length()
1132            + self.9.serialized_length()
1133    }
1134}
1135
1136impl<
1137        T1: FromBytes,
1138        T2: FromBytes,
1139        T3: FromBytes,
1140        T4: FromBytes,
1141        T5: FromBytes,
1142        T6: FromBytes,
1143        T7: FromBytes,
1144        T8: FromBytes,
1145        T9: FromBytes,
1146        T10: FromBytes,
1147    > FromBytes for (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)
1148{
1149    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1150        let (t1, remainder) = T1::from_bytes(bytes)?;
1151        let (t2, remainder) = T2::from_bytes(remainder)?;
1152        let (t3, remainder) = T3::from_bytes(remainder)?;
1153        let (t4, remainder) = T4::from_bytes(remainder)?;
1154        let (t5, remainder) = T5::from_bytes(remainder)?;
1155        let (t6, remainder) = T6::from_bytes(remainder)?;
1156        let (t7, remainder) = T7::from_bytes(remainder)?;
1157        let (t8, remainder) = T8::from_bytes(remainder)?;
1158        let (t9, remainder) = T9::from_bytes(remainder)?;
1159        let (t10, remainder) = T10::from_bytes(remainder)?;
1160        Ok(((t1, t2, t3, t4, t5, t6, t7, t8, t9, t10), remainder))
1161    }
1162}
1163
1164impl ToBytes for str {
1165    #[inline]
1166    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1167        u8_slice_to_bytes(self.as_bytes())
1168    }
1169
1170    #[inline]
1171    fn serialized_length(&self) -> usize {
1172        u8_slice_serialized_length(self.as_bytes())
1173    }
1174
1175    #[inline]
1176    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
1177        write_u8_slice(self.as_bytes(), writer)?;
1178        Ok(())
1179    }
1180}
1181
1182impl ToBytes for &str {
1183    #[inline(always)]
1184    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1185        (*self).to_bytes()
1186    }
1187
1188    #[inline(always)]
1189    fn serialized_length(&self) -> usize {
1190        (*self).serialized_length()
1191    }
1192
1193    #[inline]
1194    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), Error> {
1195        write_u8_slice(self.as_bytes(), writer)?;
1196        Ok(())
1197    }
1198}
1199
1200impl<T> ToBytes for &T
1201where
1202    T: ToBytes,
1203{
1204    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1205        (*self).to_bytes()
1206    }
1207
1208    fn serialized_length(&self) -> usize {
1209        (*self).serialized_length()
1210    }
1211}
1212
1213impl<T> ToBytes for Ratio<T>
1214where
1215    T: Clone + Integer + ToBytes,
1216{
1217    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1218        if self.denom().is_zero() {
1219            return Err(Error::Formatting);
1220        }
1221        (self.numer().clone(), self.denom().clone()).into_bytes()
1222    }
1223
1224    fn serialized_length(&self) -> usize {
1225        (self.numer().clone(), self.denom().clone()).serialized_length()
1226    }
1227}
1228
1229impl<T> FromBytes for Ratio<T>
1230where
1231    T: Clone + FromBytes + Integer,
1232{
1233    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
1234        let ((numer, denom), rem): ((T, T), &[u8]) = FromBytes::from_bytes(bytes)?;
1235        if denom.is_zero() {
1236            return Err(Error::Formatting);
1237        }
1238        Ok((Ratio::new(numer, denom), rem))
1239    }
1240}
1241
1242/// Serializes a slice of bytes with a length prefix.
1243///
1244/// This function is serializing a slice of bytes with an addition of a 4 byte length prefix.
1245///
1246/// For safety you should prefer to use [`vec_u8_to_bytes`]. For efficiency reasons you should also
1247/// avoid using serializing Vec<u8>.
1248fn u8_slice_to_bytes(bytes: &[u8]) -> Result<Vec<u8>, Error> {
1249    let serialized_length = u8_slice_serialized_length(bytes);
1250    let mut vec = Vec::with_capacity(serialized_length);
1251    let length_prefix: u32 = bytes
1252        .len()
1253        .try_into()
1254        .map_err(|_| Error::NotRepresentable)?;
1255    let length_prefix_bytes = length_prefix.to_le_bytes();
1256    vec.extend_from_slice(&length_prefix_bytes);
1257    vec.extend_from_slice(bytes);
1258    Ok(vec)
1259}
1260
1261fn write_u8_slice(bytes: &[u8], writer: &mut Vec<u8>) -> Result<(), Error> {
1262    let length_32: u32 = bytes
1263        .len()
1264        .try_into()
1265        .map_err(|_| Error::NotRepresentable)?;
1266    writer.extend_from_slice(&length_32.to_le_bytes());
1267    writer.extend_from_slice(bytes);
1268    Ok(())
1269}
1270
1271/// Serializes a vector of bytes with a length prefix.
1272///
1273/// For efficiency you should avoid serializing Vec<u8>.
1274#[allow(clippy::ptr_arg)]
1275#[inline]
1276pub(crate) fn vec_u8_to_bytes(vec: &Vec<u8>) -> Result<Vec<u8>, Error> {
1277    u8_slice_to_bytes(vec.as_slice())
1278}
1279
1280/// Returns serialized length of serialized slice of bytes.
1281///
1282/// This function adds a length prefix in the beginning.
1283#[inline(always)]
1284fn u8_slice_serialized_length(bytes: &[u8]) -> usize {
1285    U32_SERIALIZED_LENGTH + bytes.len()
1286}
1287
1288#[allow(clippy::ptr_arg)]
1289#[inline]
1290pub(crate) fn vec_u8_serialized_length(vec: &Vec<u8>) -> usize {
1291    u8_slice_serialized_length(vec.as_slice())
1292}
1293
1294// This test helper is not intended to be used by third party crates.
1295#[doc(hidden)]
1296/// Returns `true` if a we can serialize and then deserialize a value
1297pub fn test_serialization_roundtrip<T>(t: &T)
1298where
1299    T: alloc::fmt::Debug + ToBytes + FromBytes + PartialEq,
1300{
1301    let serialized = ToBytes::to_bytes(t).expect("Unable to serialize data");
1302    assert_eq!(
1303        serialized.len(),
1304        t.serialized_length(),
1305        "\nLength of serialized data: {},\nserialized_length() yielded: {},\nserialized data: {:?}, t is {:?}",
1306        serialized.len(),
1307        t.serialized_length(),
1308        serialized,
1309        t
1310    );
1311    let mut written_bytes = vec![];
1312    t.write_bytes(&mut written_bytes)
1313        .expect("Unable to serialize data via write_bytes");
1314    assert_eq!(serialized, written_bytes);
1315
1316    let deserialized_from_slice =
1317        deserialize_from_slice(&serialized).expect("Unable to deserialize data");
1318    // assert!(*t == deserialized);
1319    assert_eq!(*t, deserialized_from_slice);
1320
1321    let deserialized = deserialize::<T>(serialized).expect("Unable to deserialize data");
1322    assert_eq!(*t, deserialized);
1323}
1324#[cfg(test)]
1325mod tests {
1326    use crate::U128;
1327
1328    use super::*;
1329
1330    #[test]
1331    fn should_not_serialize_zero_denominator() {
1332        let malicious = Ratio::new_raw(1, 0);
1333        assert_eq!(malicious.to_bytes().unwrap_err(), Error::Formatting);
1334    }
1335
1336    #[test]
1337    fn should_not_deserialize_zero_denominator() {
1338        let malicious_bytes = (1u64, 0u64).to_bytes().unwrap();
1339        let result: Result<Ratio<u64>, Error> = super::deserialize(malicious_bytes);
1340        assert_eq!(result.unwrap_err(), Error::Formatting);
1341    }
1342
1343    #[test]
1344    fn should_have_generic_tobytes_impl_for_borrowed_types() {
1345        struct NonCopyable;
1346
1347        impl ToBytes for NonCopyable {
1348            fn to_bytes(&self) -> Result<Vec<u8>, Error> {
1349                Ok(vec![1, 2, 3])
1350            }
1351
1352            fn serialized_length(&self) -> usize {
1353                3
1354            }
1355        }
1356
1357        let noncopyable: &NonCopyable = &NonCopyable;
1358
1359        assert_eq!(noncopyable.to_bytes().unwrap(), vec![1, 2, 3]);
1360        assert_eq!(noncopyable.serialized_length(), 3);
1361        assert_eq!(noncopyable.into_bytes().unwrap(), vec![1, 2, 3]);
1362    }
1363
1364    #[cfg(debug_assertions)]
1365    #[test]
1366    #[should_panic(expected = "You should use Bytes newtype wrapper for efficiency")]
1367    fn should_fail_to_serialize_slice_of_u8() {
1368        let bytes = b"0123456789".to_vec();
1369        bytes.to_bytes().unwrap();
1370    }
1371
1372    #[test]
1373    fn should_calculate_capacity() {
1374        #[allow(dead_code)]
1375        struct CustomStruct {
1376            u8_field: u8,
1377            u16_field: u16,
1378            u32_field: u32,
1379            u64_field: u64,
1380            // Here we're using U128 type that represents u128 with a two u64s which is what the
1381            // compiler is doing for x86_64. On 64-bit ARM architecture u128 is aligned
1382            // to 16 bytes, but on x86_64 it's aligned to 8 bytes. This changes the
1383            // memory layout of the struct and affects the results of function `cautious`.
1384            // The expected behaviour of u128 alignment is 8 bytes instead of 16,
1385            // and there is a bug in the rust compiler for this: https://github.com/rust-lang/rust/issues/54341
1386            u128_field: U128,
1387            str_field: String,
1388        }
1389        assert_eq!(
1390            cautious::<usize>(u32::MAX as usize),
1391            512,
1392            "hint is 2^32-1 and we can only preallocate 512 elements"
1393        );
1394        assert_eq!(
1395            cautious::<u8>(usize::MAX),
1396            4096,
1397            "hint is usize::MAX and we can only preallocate 4096 elements"
1398        );
1399        assert_eq!(
1400            cautious::<u16>(usize::MAX),
1401            2048,
1402            "hint is usize::MAX and we can only preallocate 2048 elements"
1403        );
1404        assert_eq!(
1405            cautious::<CustomStruct>(usize::MAX),
1406            73,
1407            "hint is usize::MAX and we can only preallocate 73 elements"
1408        );
1409    }
1410
1411    #[test]
1412    fn deserializing_empty_vec_has_no_capacity() {
1413        let bytes = ToBytes::to_bytes(&(0u32, b"123")).unwrap();
1414        let (vec, rem): (Vec<u32>, _) = FromBytes::from_bytes(&bytes).unwrap();
1415        assert!(vec.is_empty());
1416        assert_eq!(vec.capacity(), 0);
1417        assert_eq!(rem, b"123");
1418    }
1419}
1420
1421#[cfg(test)]
1422mod proptests {
1423    use std::collections::VecDeque;
1424
1425    use proptest::{collection::vec, prelude::*};
1426
1427    use crate::{
1428        bytesrepr::{self, bytes::gens::bytes_arb, ToBytes},
1429        gens::*,
1430    };
1431
1432    proptest! {
1433        #[test]
1434        fn test_bool(u in any::<bool>()) {
1435            bytesrepr::test_serialization_roundtrip(&u);
1436        }
1437
1438        #[test]
1439        fn test_u8(u in any::<u8>()) {
1440            bytesrepr::test_serialization_roundtrip(&u);
1441        }
1442
1443        #[test]
1444        fn test_u16(u in any::<u16>()) {
1445            bytesrepr::test_serialization_roundtrip(&u);
1446        }
1447
1448        #[test]
1449        fn test_u32(u in any::<u32>()) {
1450            bytesrepr::test_serialization_roundtrip(&u);
1451        }
1452
1453        #[test]
1454        fn test_i32(u in any::<i32>()) {
1455            bytesrepr::test_serialization_roundtrip(&u);
1456        }
1457
1458        #[test]
1459        fn test_u64(u in any::<u64>()) {
1460            bytesrepr::test_serialization_roundtrip(&u);
1461        }
1462
1463        #[test]
1464        fn test_i64(u in any::<i64>()) {
1465            bytesrepr::test_serialization_roundtrip(&u);
1466        }
1467
1468        #[test]
1469        fn test_u8_slice_32(s in u8_slice_32()) {
1470            bytesrepr::test_serialization_roundtrip(&s);
1471        }
1472
1473        #[test]
1474        fn test_vec_u8(u in bytes_arb(1..100)) {
1475            bytesrepr::test_serialization_roundtrip(&u);
1476        }
1477
1478        #[test]
1479        fn test_vec_i32(u in vec(any::<i32>(), 1..100)) {
1480            bytesrepr::test_serialization_roundtrip(&u);
1481        }
1482
1483        #[test]
1484        fn test_vecdeque_i32((front, back) in (vec(any::<i32>(), 1..100), vec(any::<i32>(), 1..100))) {
1485            let mut vec_deque = VecDeque::new();
1486            for f in front {
1487                vec_deque.push_front(f);
1488            }
1489            for f in back {
1490                vec_deque.push_back(f);
1491            }
1492            bytesrepr::test_serialization_roundtrip(&vec_deque);
1493        }
1494
1495        #[test]
1496        fn test_vec_vec_u8(u in vec(bytes_arb(1..100), 10)) {
1497            bytesrepr::test_serialization_roundtrip(&u);
1498        }
1499
1500        #[test]
1501        fn test_uref_map(m in named_keys_arb(20)) {
1502            bytesrepr::test_serialization_roundtrip(&m);
1503        }
1504
1505        #[test]
1506        fn test_array_u8_32(arr in any::<[u8; 32]>()) {
1507            bytesrepr::test_serialization_roundtrip(&arr);
1508        }
1509
1510        #[test]
1511        fn test_string(s in "\\PC*") {
1512            bytesrepr::test_serialization_roundtrip(&s);
1513        }
1514
1515        #[test]
1516        fn test_str(s in "\\PC*") {
1517            let not_a_string_object = s.as_str();
1518            not_a_string_object.to_bytes().expect("should serialize a str");
1519        }
1520
1521        #[test]
1522        fn test_option(o in proptest::option::of(key_arb())) {
1523            bytesrepr::test_serialization_roundtrip(&o);
1524        }
1525
1526        #[test]
1527        fn test_unit(unit in Just(())) {
1528            bytesrepr::test_serialization_roundtrip(&unit);
1529        }
1530
1531        #[test]
1532        fn test_u128_serialization(u in u128_arb()) {
1533            bytesrepr::test_serialization_roundtrip(&u);
1534        }
1535
1536        #[test]
1537        fn test_u256_serialization(u in u256_arb()) {
1538            bytesrepr::test_serialization_roundtrip(&u);
1539        }
1540
1541        #[test]
1542        fn test_u512_serialization(u in u512_arb()) {
1543            bytesrepr::test_serialization_roundtrip(&u);
1544        }
1545
1546        #[test]
1547        fn test_key_serialization(key in key_arb()) {
1548            bytesrepr::test_serialization_roundtrip(&key);
1549        }
1550
1551        #[test]
1552        fn test_cl_value_serialization(cl_value in cl_value_arb()) {
1553            bytesrepr::test_serialization_roundtrip(&cl_value);
1554        }
1555
1556        #[test]
1557        fn test_access_rights(access_right in access_rights_arb()) {
1558            bytesrepr::test_serialization_roundtrip(&access_right);
1559        }
1560
1561        #[test]
1562        fn test_uref(uref in uref_arb()) {
1563            bytesrepr::test_serialization_roundtrip(&uref);
1564        }
1565
1566        #[test]
1567        fn test_account_hash(pk in account_hash_arb()) {
1568            bytesrepr::test_serialization_roundtrip(&pk);
1569        }
1570
1571        #[test]
1572        fn test_result(result in result_arb()) {
1573            bytesrepr::test_serialization_roundtrip(&result);
1574        }
1575
1576        #[test]
1577        fn test_phase_serialization(phase in phase_arb()) {
1578            bytesrepr::test_serialization_roundtrip(&phase);
1579        }
1580
1581        #[test]
1582        fn test_protocol_version(protocol_version in protocol_version_arb()) {
1583            bytesrepr::test_serialization_roundtrip(&protocol_version);
1584        }
1585
1586        #[test]
1587        fn test_sem_ver(sem_ver in sem_ver_arb()) {
1588            bytesrepr::test_serialization_roundtrip(&sem_ver);
1589        }
1590
1591        #[test]
1592        fn test_tuple1(t in (any::<u8>(),)) {
1593            bytesrepr::test_serialization_roundtrip(&t);
1594        }
1595
1596        #[test]
1597        fn test_tuple2(t in (any::<u8>(),any::<u32>())) {
1598            bytesrepr::test_serialization_roundtrip(&t);
1599        }
1600
1601        #[test]
1602        fn test_tuple3(t in (any::<u8>(),any::<u32>(),any::<i32>())) {
1603            bytesrepr::test_serialization_roundtrip(&t);
1604        }
1605
1606        #[test]
1607        fn test_tuple4(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>())) {
1608            bytesrepr::test_serialization_roundtrip(&t);
1609        }
1610        #[test]
1611        fn test_tuple5(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>())) {
1612            bytesrepr::test_serialization_roundtrip(&t);
1613        }
1614        #[test]
1615        fn test_tuple6(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1616            bytesrepr::test_serialization_roundtrip(&t);
1617        }
1618        #[test]
1619        fn test_tuple7(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1620            bytesrepr::test_serialization_roundtrip(&t);
1621        }
1622        #[test]
1623        fn test_tuple8(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1624            bytesrepr::test_serialization_roundtrip(&t);
1625        }
1626        #[test]
1627        fn test_tuple9(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1628            bytesrepr::test_serialization_roundtrip(&t);
1629        }
1630        #[test]
1631        fn test_tuple10(t in (any::<u8>(),any::<u32>(),any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>(), any::<i32>())) {
1632            bytesrepr::test_serialization_roundtrip(&t);
1633        }
1634        #[test]
1635        fn test_ratio_u64(t in (any::<u64>(), 1..u64::max_value())) {
1636            bytesrepr::test_serialization_roundtrip(&t);
1637        }
1638    }
1639}