use std::io;
#[derive(Debug)]
pub enum OutputError {
Io(io::Error),
}
impl std::fmt::Display for OutputError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OutputError::Io(error) => write!(formatter, "output error: {error}"),
}
}
}
impl std::error::Error for OutputError {}
impl From<io::Error> for OutputError {
fn from(error: io::Error) -> Self {
OutputError::Io(error)
}
}
pub trait Output: Send + Sync {
fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError>;
fn flush(&mut self) -> Result<(), OutputError> {
Ok(())
}
}
#[derive(Clone, Debug, Default)]
pub struct BytesOutput {
bytes: Vec<u8>,
}
impl BytesOutput {
pub fn new() -> Self {
Self::default()
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
impl Output for BytesOutput {
fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError> {
self.bytes.extend_from_slice(bytes);
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SinkOutput;
impl SinkOutput {
pub fn new() -> Self {
Self
}
}
impl Output for SinkOutput {
fn write(&mut self, _bytes: &[u8]) -> Result<(), OutputError> {
Ok(())
}
}