wasmi/module/
read.rs

1use core::{fmt, fmt::Display};
2
3#[cfg(feature = "std")]
4use std::io;
5
6/// Errors returned by [`Read::read`].
7#[derive(Debug, PartialEq, Eq)]
8pub enum ReadError {
9    /// The source has reached the end of the stream.
10    EndOfStream,
11    /// An unknown error occurred.
12    UnknownError,
13}
14
15impl Display for ReadError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        match self {
18            ReadError::EndOfStream => write!(f, "encountered unexpected end of stream"),
19            ReadError::UnknownError => write!(f, "encountered unknown error"),
20        }
21    }
22}
23
24/// Types implementing this trait act as byte streams.
25///
26/// # Note
27///
28/// Provides a subset of the interface provided by Rust's [`std::io::Read`][std_io_read] trait.
29///
30/// [`Module::new`]: [`crate::Module::new`]
31/// [std_io_read]: https://doc.rust-lang.org/std/io/trait.Read.html
32pub trait Read {
33    /// Pull some bytes from this source into the specified buffer, returning how many bytes were read.
34    ///
35    /// # Note
36    ///
37    /// Provides the same guarantees to the caller as [`std::io::Read::read`][io_read_read].
38    ///
39    /// [io_read_read]: https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read
40    ///
41    /// # Errors
42    ///
43    /// - If `self` stream is already at its end.
44    /// - For any unknown error returned by the generic [`Read`] implementer.
45    fn read(&mut self, buf: &mut [u8]) -> Result<usize, ReadError>;
46}
47
48#[cfg(feature = "std")]
49impl<T> Read for T
50where
51    T: io::Read,
52{
53    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, ReadError> {
54        <T as io::Read>::read(self, buffer).map_err(|error| match error.kind() {
55            io::ErrorKind::UnexpectedEof => ReadError::EndOfStream,
56            _ => ReadError::UnknownError,
57        })
58    }
59}
60
61#[cfg(not(feature = "std"))]
62impl<'a> Read for &'a [u8] {
63    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, ReadError> {
64        let len_copy = self.len().min(buffer.len());
65        let (read, rest) = self.split_at(len_copy);
66        buffer[..len_copy].copy_from_slice(read);
67        *self = rest;
68        Ok(len_copy)
69    }
70}