-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost_repl.rs
More file actions
90 lines (78 loc) · 2.27 KB
/
Copy pathhost_repl.rs
File metadata and controls
90 lines (78 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use std::io::{self, Read, Write};
use no_std_repl::{LineBuffer, Outcome, Parts};
fn handle_line(line: &str, out: &mut impl Write) -> io::Result<bool> {
let parts = Parts::<8>::parse(line);
if parts.is_truncated() {
writeln!(out, "too many arguments")?;
return Ok(true);
}
match parts.as_slice() {
[] => {}
["help"] => {
writeln!(out, "commands: help, ping [n], echo <words...>, quit")?;
}
["ping"] => {
writeln!(out, "pong")?;
}
["ping", n] => {
writeln!(out, "pong {n}")?;
}
["echo", rest @ ..] => {
writeln!(out, "{}", rest.join(" "))?;
}
["quit"] | ["exit"] => {
writeln!(out, "bye")?;
return Ok(false);
}
other => {
writeln!(out, "unknown command: {other:?}")?;
}
}
Ok(true)
}
fn main() -> io::Result<()> {
let mut stdin = io::stdin().lock();
let mut stdout = io::stdout().lock();
let mut line = LineBuffer::<128>::new();
let mut buf = [0_u8; 1];
writeln!(stdout, "host REPL demo")?;
writeln!(stdout, "type `help` for commands")?;
write!(stdout, "> ")?;
stdout.flush()?;
loop {
if stdin.read(&mut buf)? == 0 {
break;
}
let byte = buf[0];
if !matches!(byte, b'\r' | b'\n') {
stdout.write_all(&[byte])?;
stdout.flush()?;
}
match line.push(byte) {
Outcome::Continue => {}
Outcome::LineComplete => {
writeln!(stdout)?;
match line.as_str() {
Some(s) => {
if !handle_line(s, &mut stdout)? {
break;
}
}
None => {
writeln!(stdout, "invalid UTF-8 input")?;
}
}
line.clear();
write!(stdout, "> ")?;
stdout.flush()?;
}
Outcome::BufferFull => {
writeln!(stdout, "\nline too long")?;
line.clear();
write!(stdout, "> ")?;
stdout.flush()?;
}
}
}
Ok(())
}