Skip to content

Commit

Permalink
Merge pull request #44 from dxrcy/input-refactor
Browse files Browse the repository at this point in the history
Extract input behaviour to function
  • Loading branch information
rozukke authored Sep 26, 2024
2 parents 5c00422 + 3587958 commit cc1a5c6
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -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 => {
Expand Down Expand Up @@ -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]
}
}

0 comments on commit cc1a5c6

Please sign in to comment.