1use crate::bytecode::Value;
8
9pub trait OutputSink: Send + Sync + std::fmt::Debug + 'static {
14 fn write(&self, values: &[Value]);
15}
16
17#[derive(Debug, Clone, Copy, Default)]
19pub struct NullSink;
20
21impl OutputSink for NullSink {
22 fn write(&self, _values: &[Value]) {}
23}
24
25#[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
37fn 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}