parity_wasm/
io.rs

1//! Simple abstractions for the IO operations.
2//!
3//! Basically it just a replacement for the std::io that is usable from
4//! the `no_std` environment.
5
6#[cfg(feature = "std")]
7use std::io;
8
9/// IO specific error.
10#[derive(Debug)]
11pub enum Error {
12	/// Some unexpected data left in the buffer after reading all data.
13	TrailingData,
14
15	/// Unexpected End-Of-File
16	UnexpectedEof,
17
18	/// Invalid data is encountered.
19	InvalidData,
20
21	#[cfg(feature = "std")]
22	Io(std::io::Error),
23}
24
25/// IO specific Result.
26pub type Result<T> = core::result::Result<T, Error>;
27
28pub trait Write {
29	/// Write a buffer of data into this write.
30	///
31	/// All data is written at once.
32	fn write(&mut self, buf: &[u8]) -> Result<()>;
33}
34
35pub trait Read {
36	/// Read a data from this read to a buffer.
37	///
38	/// If there is not enough data in this read then `UnexpectedEof` will be returned.
39	fn read(&mut self, buf: &mut [u8]) -> Result<()>;
40}
41
42/// Reader that saves the last position.
43pub struct Cursor<T> {
44	inner: T,
45	pos: usize,
46}
47
48impl<T> Cursor<T> {
49	pub fn new(inner: T) -> Cursor<T> {
50		Cursor { inner, pos: 0 }
51	}
52
53	pub fn position(&self) -> usize {
54		self.pos
55	}
56}
57
58impl<T: AsRef<[u8]>> Read for Cursor<T> {
59	fn read(&mut self, buf: &mut [u8]) -> Result<()> {
60		let slice = self.inner.as_ref();
61		let remainder = slice.len() - self.pos;
62		let requested = buf.len();
63		if requested > remainder {
64			return Err(Error::UnexpectedEof)
65		}
66		buf.copy_from_slice(&slice[self.pos..(self.pos + requested)]);
67		self.pos += requested;
68		Ok(())
69	}
70}
71
72#[cfg(not(feature = "std"))]
73impl Write for alloc::vec::Vec<u8> {
74	fn write(&mut self, buf: &[u8]) -> Result<()> {
75		self.extend(buf);
76		Ok(())
77	}
78}
79
80#[cfg(feature = "std")]
81impl<T: io::Read> Read for T {
82	fn read(&mut self, buf: &mut [u8]) -> Result<()> {
83		self.read_exact(buf).map_err(Error::Io)
84	}
85}
86
87#[cfg(feature = "std")]
88impl<T: io::Write> Write for T {
89	fn write(&mut self, buf: &[u8]) -> Result<()> {
90		self.write_all(buf).map_err(Error::Io)
91	}
92}
93
94#[cfg(test)]
95mod tests {
96	use super::*;
97
98	#[test]
99	fn cursor() {
100		let mut cursor = Cursor::new(vec![0xFFu8, 0x7Fu8]);
101		assert_eq!(cursor.position(), 0);
102
103		let mut buf = [0u8];
104		assert!(cursor.read(&mut buf[..]).is_ok());
105		assert_eq!(cursor.position(), 1);
106		assert_eq!(buf[0], 0xFFu8);
107		assert!(cursor.read(&mut buf[..]).is_ok());
108		assert_eq!(buf[0], 0x7Fu8);
109		assert_eq!(cursor.position(), 2);
110	}
111
112	#[test]
113	fn overflow_in_cursor() {
114		let mut cursor = Cursor::new(vec![0u8]);
115		let mut buf = [0, 1, 2];
116		assert!(cursor.read(&mut buf[..]).is_err());
117	}
118}