From 2ccffaea130d5fd5a7eaca242cce928e6c0fcba0 Mon Sep 17 00:00:00 2001 From: darcy Date: Sat, 21 Sep 2024 16:35:30 +1000 Subject: [PATCH] Support non-terminal stdin reading for `GETC` and `IN` --- src/runtime.rs | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/runtime.rs b/src/runtime.rs index 9c94c78..2f34190 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -1,5 +1,10 @@ use core::panic; -use std::{cmp::Ordering, i16, io::Write, u16, u32, u8, usize}; +use std::{ + cmp::Ordering, + i16, + io::{stdin, stdout, IsTerminal, Read, Write}, + u16, u32, u8, usize, +}; use crate::Air; use colored::Colorize; @@ -265,9 +270,15 @@ impl RunState { match trap_vect { // getc 0x20 => { - let cons = Term::stdout(); - let c = cons.read_char().unwrap(); - *self.reg(0) = c as u16; + if stdin().is_terminal() { + let cons = Term::stdout(); + let c = cons.read_char().unwrap(); + *self.reg(0) = c as u16; + } else { + let mut buf = [0; 1]; + stdin().read_exact(&mut buf).unwrap(); + *self.reg(0) = buf[0] as u16; + } } // out 0x21 => { @@ -292,11 +303,19 @@ impl RunState { } // in 0x23 => { - let mut cons = Term::stdout(); - let c = cons.read_char().unwrap(); - *self.reg(0) = c as u16; - write!(cons, "{c}").unwrap(); - cons.flush().unwrap(); + if stdin().is_terminal() { + let mut cons = Term::stdout(); + let c = cons.read_char().unwrap(); + *self.reg(0) = c as u16; + write!(cons, "{c}").unwrap(); + cons.flush().unwrap(); + } else { + let mut buf = [0; 1]; + stdin().read_exact(&mut buf).unwrap(); + *self.reg(0) = buf[0] as u16; + print!("{}", buf[0] as char); + stdout().flush().unwrap(); + } } // putsp 0x24 => {