dusk_bytes/
serialize.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7use super::errors::{BadLength, Error};
8
9/// The core trait used to implement [`from_bytes`] and [`to_bytes`]
10pub trait Serializable<const N: usize> {
11    /// The size of
12    const SIZE: usize = N;
13    /// The type returned in the event of a conversion error.
14    type Error;
15
16    /// Deserialize a [`&[u8; N]`] into [`Self`], it might be fail.
17    fn from_bytes(buf: &[u8; N]) -> Result<Self, Self::Error>
18    where
19        Self: Sized;
20
21    /// Serialize [`Self`] into a [`[u8; N]`].
22    fn to_bytes(&self) -> [u8; N];
23}
24
25/// An optional trait used to implement [`from_slice`] on top of types that
26/// uses [`Serializable`] trait.
27/// The default implementation makes use of [`Serializable`] trait to provide
28/// the necessary deserialization functionality without additional code from the
29/// consumer.
30pub trait DeserializableSlice<const N: usize>: Serializable<N> {
31    /// Deserialize a slice of [`u8`] into [`Self`]
32    fn from_slice(buf: &[u8]) -> Result<Self, Self::Error>
33    where
34        Self: Sized,
35        Self::Error: BadLength,
36    {
37        if buf.len() < N {
38            Err(Self::Error::bad_length(buf.len(), N))
39        } else {
40            let mut bytes = [0u8; N];
41            bytes[..N].copy_from_slice(&buf[..N]);
42            Self::from_bytes(&bytes)
43        }
44    }
45
46    /// Deserialize the type reading the bytes from a reader.
47    /// The bytes read are removed from the reader.
48    fn from_reader<R>(buf: &mut R) -> Result<Self, Self::Error>
49    where
50        R: Read,
51        Self: Sized,
52        Self::Error: BadLength,
53    {
54        let mut bytes = [0u8; N];
55        buf.read(&mut bytes)
56            .map_err(|_| Self::Error::bad_length(buf.capacity(), N))?;
57
58        Self::from_bytes(&bytes)
59    }
60}
61
62// Auto trait [`DeserializableSlice`] for any type that implements
63// [`Serializable`]
64impl<T, const N: usize> DeserializableSlice<N> for T where T: Serializable<N> {}
65
66// The `Read` trait allows for reading bytes from a source.
67///
68/// Implementors of the `Read` trait are called 'readers'.
69///
70/// Readers are defined by one required method, [`read()`]. Each call to
71/// [`read()`] will attempt to pull bytes from this source into a provided
72/// buffer.
73pub trait Read {
74    /// Returns the number of elements the Reader can hold.
75    fn capacity(&self) -> usize;
76
77    /// Pull some bytes from this source into the specified buffer, returning
78    /// how many bytes were read.
79    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>;
80}
81
82impl Read for &[u8] {
83    #[inline]
84    fn capacity(&self) -> usize {
85        self.len()
86    }
87
88    #[inline]
89    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
90        if buf.len() > self.len() {
91            return Err(Error::bad_length(self.len(), buf.len()));
92        }
93        let amt = buf.len();
94        let (a, b) = self.split_at(amt);
95
96        // First check if the amount of bytes we want to read is small:
97        // `copy_from_slice` will generally expand to a call to `memcpy`, and
98        // for a single byte the overhead is significant.
99        if amt == 1 {
100            buf[0] = a[0];
101        } else {
102            buf[..amt].copy_from_slice(a);
103        }
104
105        *self = b;
106        Ok(amt)
107    }
108}
109
110// A trait for objects which are byte-oriented sinks.
111///
112/// Implementors of the `Write` trait are sometimes called 'writers'.
113///
114/// Writers are defined by one required method, [`write()`].
115pub trait Write {
116    /// Write a buffer into this writer, returning how many bytes were written.
117    ///
118    /// This function will attempt to write the entire contents of `buf`, but
119    /// the entire write may not succeed, or the write may also generate an
120    /// error.
121    fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
122}
123
124impl Write for &mut [u8] {
125    #[inline]
126    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
127        if buf.len() > self.len() {
128            return Err(Error::bad_length(self.len(), buf.len()));
129        }
130        let amt = buf.len();
131
132        let (a, b) = core::mem::take(self).split_at_mut(amt);
133        a.copy_from_slice(&buf[..amt]);
134        *self = b;
135        Ok(amt)
136    }
137}