lox_lang/vm/
io.rs

1use std::{
2    cmp, fmt,
3    io::{Error, ErrorKind, Read, Result, Write},
4    mem,
5};
6
7use super::VM;
8
9impl VM {
10    /// Print directly to stdout, or buffer output internally.
11    ///
12    /// Pass `true` to this method to buffer print output internally. This output can then be
13    /// accessed through this struct's [`Read`] implementation.
14    ///
15    /// Pass `false` (the default mode) to sink all program output directly to [`Stdout`].
16    ///
17    /// ### Example
18    ///
19    /// ```
20    /// use std::io::Read;
21    ///
22    /// let mut vm = lox_lang::VM::default();
23    /// vm.buffer_output(true);
24    ///
25    /// vm.interpret("print nil == true;");
26    ///
27    /// let mut buffer = String::new();
28    /// vm.read_to_string(&mut buffer).unwrap();
29    /// assert_eq!(buffer, "false\n");
30    ///
31    /// vm.interpret("for (var a = 3; a < 12; a = a + 3) print a;");
32    ///
33    /// buffer.clear();
34    /// vm.read_to_string(&mut buffer).unwrap();
35    /// assert_eq!(buffer, "3\n6\n9\n");
36    /// ```
37    ///
38    /// [`Stdout`]: https://doc.rust-lang.org/std/io/struct.Stdout.html
39    /// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
40    pub fn buffer_output(&mut self, should_buffer: bool) {
41        if should_buffer && self.stdout.is_none() {
42            self.stdout = Some(Vec::new());
43        } else if !should_buffer && self.stdout.is_some() {
44            self.stdout = None;
45        }
46    }
47
48    pub(super) fn print(&mut self, args: fmt::Arguments) {
49        if let Some(ref mut out) = self.stdout {
50            out.write_fmt(args).unwrap();
51        } else {
52            print!("{}", args);
53        }
54    }
55
56    fn try_read_buf(&mut self) -> Result<&mut Vec<u8>> {
57        if let Some(ref mut my_buf) = &mut self.stdout {
58            Ok(my_buf)
59        } else {
60            Err(Error::new(
61                ErrorKind::Other,
62                "Currently logging directly to stdout.",
63            ))
64        }
65    }
66}
67
68impl Read for VM {
69    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
70        let my_buf = self.try_read_buf()?;
71
72        if my_buf.is_empty() {
73            return Ok(0);
74        }
75
76        let common_len = cmp::min(my_buf.len(), buf.len());
77
78        let new_vec = my_buf.split_off(common_len);
79        let old_vec = mem::replace(my_buf, new_vec);
80
81        buf[0..common_len].copy_from_slice(&old_vec);
82
83        Ok(common_len)
84    }
85
86    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
87        let my_buf = self.try_read_buf()?;
88
89        if my_buf.is_empty() {
90            return Ok(0);
91        }
92
93        let len = my_buf.len();
94        buf.append(my_buf);
95
96        Ok(len)
97    }
98}