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