Skip to main content

byteflow/
output.rs

1//! Host-side output for the `print` native.
2//!
3//! Bytecode must not own stdout. Embedders inject an [`OutputSink`]; the
4//! default is [`NullSink`] so a library load is silent. CLI demos pass
5//! [`StdoutSink`].
6
7use crate::bytecode::Value;
8
9/// Receives `print` native arguments. Must not panic.
10///
11/// The call may block for its own write. [`StdoutSink`] takes the process
12/// stdout lock once, writes one line, and drops a failed write.
13pub trait OutputSink: Send + Sync + std::fmt::Debug + 'static {
14    fn write(&self, values: &[Value]);
15}
16
17/// Discard output (default for embedders and tests).
18#[derive(Debug, Clone, Copy, Default)]
19pub struct NullSink;
20
21impl OutputSink for NullSink {
22    fn write(&self, _values: &[Value]) {}
23}
24
25/// Space-separated `Display` forms plus a newline on stdout.
26#[derive(Debug, Clone, Copy, Default)]
27pub struct StdoutSink;
28
29impl OutputSink for StdoutSink {
30    fn write(&self, values: &[Value]) {
31        let line = format_print_line(values);
32        let mut stdout = std::io::stdout().lock();
33        let _ = std::io::Write::write_all(&mut stdout, line.as_bytes());
34    }
35}
36
37/// One `print` record: values separated by a single space, then a newline.
38fn format_print_line(values: &[Value]) -> String {
39    use std::fmt::Write as _;
40
41    let mut line = String::new();
42    for (index, value) in values.iter().enumerate() {
43        if index > 0 {
44            line.push(' ');
45        }
46        let _ = write!(line, "{value}");
47    }
48    line.push('\n');
49    line
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn print_line_is_one_record() {
58        let list = match Value::try_list(vec![Value::Int(1)]) {
59            Some(value) => value,
60            None => panic!("list"),
61        };
62        let map = match Value::try_map(vec![(crate::bytecode::MapKey::Int(7), Value::Bool(true))]) {
63            Some(value) => value,
64            None => panic!("map"),
65        };
66        assert_eq!(format_print_line(&[]), "\n");
67        assert_eq!(
68            format_print_line(&[Value::Int(1), list, map]),
69            "1 [1] {7: true}\n"
70        );
71    }
72
73    #[test]
74    fn stdout_sink_writes_one_line_without_panicking() {
75        StdoutSink.write(&[Value::Int(1), Value::Bool(false)]);
76    }
77}