microcad_lang/eval/
output.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/// Trait which Context is using to access or redirect the µcad code's console output.
5pub trait Output {
6    /// Print into output buffer.
7    fn print(&mut self, what: String) -> std::io::Result<()>;
8    /// Access captured output.
9    fn output(&self) -> Option<String>;
10}
11
12/// Output what `__builtin::print` is printing to stdout.
13pub struct Stdout;
14
15impl Output for Stdout {
16    /// Print into output buffer.
17    fn print(&mut self, what: String) -> std::io::Result<()> {
18        println!("{what}");
19        Ok(())
20    }
21    fn output(&self) -> Option<String> {
22        None
23    }
24}
25
26/// Output buffer to catch what `__builtin::print` is printing.
27pub struct Capture {
28    buf: std::io::BufWriter<Vec<u8>>,
29}
30
31impl Capture {
32    /// Create new capture buffer.
33    pub fn new() -> Self {
34        Self {
35            buf: std::io::BufWriter::new(Vec::new()),
36        }
37    }
38}
39
40impl Default for Capture {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl Output for Capture {
47    fn print(&mut self, what: String) -> std::io::Result<()> {
48        use std::io::Write;
49        writeln!(self.buf, "{what}")
50    }
51    fn output(&self) -> Option<String> {
52        String::from_utf8(self.buf.buffer().into()).ok()
53    }
54}