Skip to main content

wasmi/module/
read.rs

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