#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
pub trait Input {
type Error;
fn read(&mut self, into: &mut [u8]) -> Result<(), Self::Error>;
fn read_byte(&mut self) -> Result<u8, Self::Error> {
let mut buf = [0u8];
self.read(&mut buf[..])?;
Ok(buf[0])
}
}
#[cfg(not(feature = "std"))]
#[derive(PartialEq, Eq, Clone)]
pub enum SliceInputError {
NotEnoughData,
}
#[cfg(not(feature = "std"))]
impl<'a> Input for &'a [u8] {
type Error = SliceInputError;
fn read(&mut self, into: &mut [u8]) -> Result<(), SliceInputError> {
if into.len() > self.len() {
return Err(SliceInputError::NotEnoughData);
}
let len = into.len();
into.copy_from_slice(&self[..len]);
*self = &self[len..];
Ok(())
}
}
#[cfg(feature = "std")]
impl<R: std::io::Read> Input for R {
type Error = std::io::Error;
fn read(&mut self, into: &mut [u8]) -> Result<(), std::io::Error> {
(self as &mut dyn std::io::Read).read_exact(into)?;
Ok(())
}
}
pub trait Output: Sized {
fn write(&mut self, bytes: &[u8]);
fn push_byte(&mut self, byte: u8) {
self.write(&[byte]);
}
}
#[cfg(not(feature = "std"))]
impl Output for alloc::vec::Vec<u8> {
fn write(&mut self, bytes: &[u8]) {
self.extend_from_slice(bytes)
}
}
#[cfg(feature = "std")]
impl<W: std::io::Write> Output for W {
fn write(&mut self, bytes: &[u8]) {
(self as &mut dyn std::io::Write).write_all(bytes).expect("Codec outputs are infallible");
}
}