diff --git a/src/runtime.rs b/src/runtime.rs index f765f5f..8308249 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -270,15 +270,7 @@ impl RunState { match trap_vect { // getc 0x20 => { - 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; - } + *self.reg(0) = read_input() as u16; } // out 0x21 => { @@ -305,19 +297,10 @@ impl RunState { } // in 0x23 => { - 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(); - } + let ch = read_input(); + *self.reg(0) = ch as u16; + print!("{}", ch); + stdout().flush().unwrap(); } // putsp 0x24 => { @@ -348,3 +331,16 @@ impl RunState { } } } + +// Read one byte from stdin or unbuffered terminal +fn read_input() -> u8 { + if stdin().is_terminal() { + let cons = Term::stdout(); + let ch = cons.read_char().unwrap(); + ch as u8 + } else { + let mut buf = [0; 1]; + stdin().read_exact(&mut buf).unwrap(); + buf[0] + } +}