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
use core::{fmt, fmt::Display};

#[cfg(feature = "std")]
use std::io;

/// Errors returned by [`Read::read`].
#[derive(Debug, PartialEq, Eq)]
pub enum ReadError {
    /// The source has reached the end of the stream.
    EndOfStream,
    /// An unknown error occurred.
    UnknownError,
}

#[cfg(feature = "std")]
impl std::error::Error for ReadError {}

impl Display for ReadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReadError::EndOfStream => write!(f, "encountered unexpected end of stream"),
            ReadError::UnknownError => write!(f, "encountered unknown error"),
        }
    }
}

/// Types implementing this trait act as byte streams.
///
/// # Note
///
/// Provides a subset of the interface provided by Rust's [`std::io::Read`][std_io_read] trait.
///
/// [`Module::new`]: [`crate::Module::new`]
/// [std_io_read]: https://doc.rust-lang.org/std/io/trait.Read.html
pub trait Read {
    /// Pull some bytes from this source into the specified buffer, returning how many bytes were read.
    ///
    /// # Note
    ///
    /// Provides the same guarantees to the caller as [`std::io::Read::read`][io_read_read].
    ///
    /// [io_read_read]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read
    ///
    /// # Errors
    ///
    /// - If `self` stream is already at its end.
    /// - For any unknown error returned by the generic [`Read`] implementer.
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, ReadError>;
}

#[cfg(feature = "std")]
impl<T> Read for T
where
    T: io::Read,
{
    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, ReadError> {
        <T as io::Read>::read(self, buffer).map_err(|error| match error.kind() {
            io::ErrorKind::UnexpectedEof => ReadError::EndOfStream,
            _ => ReadError::UnknownError,
        })
    }
}

#[cfg(not(feature = "std"))]
impl<'a> Read for &'a [u8] {
    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, ReadError> {
        let len_copy = self.len().min(buffer.len());
        let (read, rest) = self.split_at(len_copy);
        buffer[..len_copy].copy_from_slice(read);
        *self = rest;
        Ok(len_copy)
    }
}