Skip to main content

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 [`Serializable::from_bytes`] and
10/// [`Serializable::to_bytes`].
11pub trait Serializable<const N: usize> {
12    /// The size of
13    const SIZE: usize = N;
14    /// The type returned in the event of a conversion error.
15    type Error;
16
17    /// Deserialize a [`&[u8; N]`] into [`Self`], it might be fail.
18    fn from_bytes(buf: &[u8; N]) -> Result<Self, Self::Error>
19    where
20        Self: Sized;
21
22    /// Serialize [`Self`] into a [`[u8; N]`].
23    fn to_bytes(&self) -> [u8; N];
24}
25
26/// An optional trait used to implement [`DeserializableSlice::from_slice`] on
27/// top of types that use the [`Serializable`] trait.
28/// The default implementation makes use of [`Serializable`] trait to provide
29/// the necessary deserialization functionality without additional code from the
30/// consumer.
31pub trait DeserializableSlice<const N: usize>: Serializable<N> {
32    /// Deserialize a slice of [`u8`] into [`Self`]
33    fn from_slice(buf: &[u8]) -> Result<Self, Self::Error>
34    where
35        Self: Sized,
36        Self::Error: BadLength,
37    {
38        match buf.first_chunk::<N>() {
39            Some(bytes) => Self::from_bytes(bytes),
40            None => Err(Self::Error::bad_length(buf.len(), N)),
41        }
42    }
43
44    /// Deserialize the type by reading exactly `N` bytes from a reader.
45    /// Successful short reads are retried. If the reader makes no progress or
46    /// returns an error before filling the buffer, a bad-length error is
47    /// returned. The bytes read are removed from the reader, including bytes
48    /// read before an error or end of input.
49    fn from_reader<R>(buf: &mut R) -> Result<Self, Self::Error>
50    where
51        R: Read,
52        Self: Sized,
53        Self::Error: BadLength,
54    {
55        let mut bytes = [0u8; N];
56        let mut filled = 0;
57
58        while filled < N {
59            let remaining = N - filled;
60            match buf.read(&mut bytes[filled..]) {
61                Ok(0) => return Err(Self::Error::bad_length(filled, N)),
62                Ok(read) if read <= remaining => filled += read,
63                Ok(_) => return Err(Self::Error::bad_length(filled, N)),
64                Err(_) => {
65                    let found = filled.saturating_add(buf.capacity());
66                    return Err(Self::Error::bad_length(found, N));
67                }
68            }
69        }
70
71        Self::from_bytes(&bytes)
72    }
73}
74
75// Auto trait [`DeserializableSlice`] for any type that implements
76// [`Serializable`]
77impl<T, const N: usize> DeserializableSlice<N> for T where T: Serializable<N> {}
78
79// The `Read` trait allows for reading bytes from a source.
80///
81/// Implementors of the `Read` trait are called 'readers'.
82///
83/// Readers are defined by one required method, [`Read::read`]. Each call to
84/// [`Read::read`] will attempt to pull bytes from this source into a provided
85/// buffer.
86pub trait Read {
87    /// Returns the number of unread bytes remaining in the source.
88    fn capacity(&self) -> usize;
89
90    /// Pull some bytes from this source into the specified buffer, returning
91    /// how many bytes were read.
92    ///
93    /// A successful read of `n` means exactly `n` bytes were written into
94    /// `buf`. It may fill only part of `buf`, but must not report more than
95    /// `buf.len()`. `Ok(0)` means the reader can produce no more bytes.
96    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>;
97}
98
99impl Read for &[u8] {
100    #[inline]
101    fn capacity(&self) -> usize {
102        self.len()
103    }
104
105    #[inline]
106    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
107        if buf.len() > self.len() {
108            return Err(Error::bad_length(self.len(), buf.len()));
109        }
110        let amt = buf.len();
111        let (a, b) = self.split_at(amt);
112
113        // First check if the amount of bytes we want to read is small:
114        // `copy_from_slice` will generally expand to a call to `memcpy`, and
115        // for a single byte the overhead is significant.
116        if amt == 1 {
117            buf[0] = a[0];
118        } else {
119            buf[..amt].copy_from_slice(a);
120        }
121
122        *self = b;
123        Ok(amt)
124    }
125}
126
127// A trait for objects which are byte-oriented sinks.
128///
129/// Implementors of the `Write` trait are sometimes called 'writers'.
130///
131/// Writers are defined by one required method, [`Write::write`].
132pub trait Write {
133    /// Write a buffer into this writer, returning how many bytes were written.
134    ///
135    /// This function will attempt to write the entire contents of `buf`, but
136    /// the entire write may not succeed, or the write may also generate an
137    /// error.
138    fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
139}
140
141impl Write for &mut [u8] {
142    #[inline]
143    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
144        if buf.len() > self.len() {
145            return Err(Error::bad_length(self.len(), buf.len()));
146        }
147        let amt = buf.len();
148
149        let (a, b) = core::mem::take(self).split_at_mut(amt);
150        a.copy_from_slice(&buf[..amt]);
151        *self = b;
152        Ok(amt)
153    }
154}