Skip to main content

engine/io/
output.rs

1//! Output streams.
2
3use std::io;
4
5/// Errors produced by an [`Output`] stream.
6#[derive(Debug)]
7pub enum OutputError {
8    /// The underlying stream failed in a host-specific way.
9    Io(io::Error),
10}
11
12impl std::fmt::Display for OutputError {
13    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        match self {
15            OutputError::Io(error) => write!(formatter, "output error: {error}"),
16        }
17    }
18}
19
20impl std::error::Error for OutputError {}
21
22impl From<io::Error> for OutputError {
23    fn from(error: io::Error) -> Self {
24        OutputError::Io(error)
25    }
26}
27
28/// A writable byte stream.
29pub trait Output: Send + Sync {
30    /// Writes all of `bytes`.
31    fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError>;
32
33    /// Flushes any buffered state.
34    fn flush(&mut self) -> Result<(), OutputError> {
35        Ok(())
36    }
37}
38
39/// An output that accumulates bytes in memory (used by tests and the
40/// non-interactive shell).
41#[derive(Clone, Debug, Default)]
42pub struct BytesOutput {
43    bytes: Vec<u8>,
44}
45
46impl BytesOutput {
47    /// Creates an empty output.
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    /// The bytes written so far.
53    pub fn bytes(&self) -> &[u8] {
54        &self.bytes
55    }
56
57    /// Consumes the output, returning the accumulated bytes.
58    pub fn into_bytes(self) -> Vec<u8> {
59        self.bytes
60    }
61}
62
63impl Output for BytesOutput {
64    fn write(&mut self, bytes: &[u8]) -> Result<(), OutputError> {
65        self.bytes.extend_from_slice(bytes);
66        Ok(())
67    }
68}
69
70/// An output that discards everything (the virtual `/dev/null`).
71#[derive(Clone, Copy, Debug, Default)]
72pub struct SinkOutput;
73
74impl SinkOutput {
75    /// Creates a sink output.
76    pub fn new() -> Self {
77        Self
78    }
79}
80
81impl Output for SinkOutput {
82    fn write(&mut self, _bytes: &[u8]) -> Result<(), OutputError> {
83        Ok(())
84    }
85}