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