1#![allow(missing_docs)]
10
11use crate::bytecode::Value;
12
13pub trait OutputSink: Send + Sync + std::fmt::Debug + 'static {
18 fn write(&self, values: &[Value]);
19}
20
21#[derive(Debug, Clone, Copy, Default)]
23pub struct NullSink;
24
25impl OutputSink for NullSink {
26 fn write(&self, _values: &[Value]) {}
27}
28
29#[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
41fn 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}