1#![warn(missing_docs)]
21
22#![cfg_attr(not(feature = "std"), no_std)]
23
24extern crate alloc;
25
26pub trait Input {
28 type Error;
30
31 fn read(&mut self, into: &mut [u8]) -> Result<(), Self::Error>;
36
37 fn read_byte(&mut self) -> Result<u8, Self::Error> {
39 let mut buf = [0u8];
40 self.read(&mut buf[..])?;
41 Ok(buf[0])
42 }
43}
44
45#[cfg(not(feature = "std"))]
47#[derive(PartialEq, Eq, Clone)]
48pub enum SliceInputError {
49 NotEnoughData,
51}
52
53#[cfg(not(feature = "std"))]
54impl<'a> Input for &'a [u8] {
55 type Error = SliceInputError;
56
57 fn read(&mut self, into: &mut [u8]) -> Result<(), SliceInputError> {
58 if into.len() > self.len() {
59 return Err(SliceInputError::NotEnoughData);
60 }
61 let len = into.len();
62 into.copy_from_slice(&self[..len]);
63 *self = &self[len..];
64 Ok(())
65 }
66}
67
68#[cfg(feature = "std")]
69impl<R: std::io::Read> Input for R {
70 type Error = std::io::Error;
71
72 fn read(&mut self, into: &mut [u8]) -> Result<(), std::io::Error> {
73 (self as &mut dyn std::io::Read).read_exact(into)?;
74 Ok(())
75 }
76}
77
78pub trait Output: Sized {
80 fn write(&mut self, bytes: &[u8]);
82
83 fn push_byte(&mut self, byte: u8) {
85 self.write(&[byte]);
86 }
87}
88
89#[cfg(not(feature = "std"))]
90impl Output for alloc::vec::Vec<u8> {
91 fn write(&mut self, bytes: &[u8]) {
92 self.extend_from_slice(bytes)
93 }
94}
95
96#[cfg(feature = "std")]
97impl<W: std::io::Write> Output for W {
98 fn write(&mut self, bytes: &[u8]) {
99 (self as &mut dyn std::io::Write).write_all(bytes).expect("Codec outputs are infallible");
100 }
101}