serde_scale/
read.rs

1// Copyright (C) 2020 Stephane Raux. Distributed under the zlib license.
2
3use core::{
4    fmt::{self, Debug, Display},
5    ops::Deref,
6};
7
8/// Interface to read bytes
9pub trait Read<'a> {
10    type Error: Debug + Display;
11
12    /// Reads exactly `n` bytes and passes them to the given function
13    ///
14    /// An error must be returned if there are fewer than `n` bytes left.
15    fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
16    where
17        F: FnOnce(Bytes<'a, '_>) -> R;
18
19    /// Reads exactly `buf.len()` bytes and writes them to the supplied buffer
20    ///
21    /// An error must be returned if there are fewer than `buf.len()` bytes left.
22    fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
23        self.read_map(buf.len(), |bytes| {
24            buf.copy_from_slice(&bytes);
25        })
26    }
27}
28
29impl<'a, T: Read<'a> + ?Sized> Read<'a> for &'_ mut T {
30    type Error = T::Error;
31
32    fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
33    where
34        F: FnOnce(Bytes<'a, '_>) -> R,
35    {
36        (**self).read_map(n, f)
37    }
38
39    fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
40        (**self).read_exact(buf)
41    }
42}
43
44impl<'a> Read<'a> for &'a [u8] {
45    type Error = EndOfInput;
46
47    fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
48    where
49        F: FnOnce(Bytes<'a, '_>) -> R,
50    {
51        if n > self.len() {
52            return Err(EndOfInput);
53        }
54        let (consumed, remaining) = self.split_at(n);
55        *self = remaining;
56        Ok(f(Bytes::Persistent(consumed)))
57    }
58}
59
60/// Bytes borrowed from the deserializer or valid only for the duration of the call to `read_map`
61pub enum Bytes<'a, 'b> {
62    /// Bytes borrowed from the deserializer allowing zero-copy deserialization
63    Persistent(&'a [u8]),
64    /// Bytes only valid for the duration of the call to `read_map`
65    Temporary(&'b [u8]),
66}
67
68impl Deref for Bytes<'_, '_> {
69    type Target = [u8];
70
71    fn deref(&self) -> &[u8] {
72        match self {
73            Bytes::Persistent(b) => b,
74            Bytes::Temporary(b) => b,
75        }
76    }
77}
78
79/// Error indicating that the end of the input was reached and not enough bytes were read
80#[derive(Debug)]
81pub struct EndOfInput;
82
83impl Display for EndOfInput {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str("EndOfInput")
86    }
87}
88
89#[cfg(feature = "std")]
90impl std::error::Error for EndOfInput {}