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 Stdout {
16    /// Create new stdout output.
17    pub fn new() -> Box<Self> {
18        Box::new(Self)
19    }
20}
21
22impl Output for Stdout {
23    /// Print into output buffer.
24    fn print(&mut self, what: String) -> std::io::Result<()> {
25        println!("{what}");
26        Ok(())
27    }
28    fn output(&self) -> Option<String> {
29        None
30    }
31}
32
33/// Output buffer to catch what `__builtin::print` is printing.
34pub struct Capture {
35    buf: std::io::BufWriter<Vec<u8>>,
36}
37
38impl Capture {
39    /// Create new capture buffer.
40    pub fn new() -> Box<Self> {
41        Box::new(Self {
42            buf: std::io::BufWriter::new(Vec::new()),
43        })
44    }
45}
46
47impl Output for Capture {
48    fn print(&mut self, what: String) -> std::io::Result<()> {
49        use std::io::Write;
50        writeln!(self.buf, "{what}")
51    }
52    fn output(&self) -> Option<String> {
53        String::from_utf8(self.buf.buffer().into()).ok()
54    }
55}