Debian Codegraph @

src/bin/leb128-repl.rs

raw symbols SCIP
1 use leb128;
2
3 use std::io::{self, BufRead, Write};
4 use std::str;
5
6 fn display(bytes: &[u8]) -> String {
7 let mut s = vec![];
8
9 // Base 10.
10 write!(&mut s, "{:?}\n", bytes).unwrap();
11
12 // Hex.
13 write!(&mut s, "[").unwrap();
14 for (i, b) in bytes.iter().enumerate() {
15 if i != 0 {
16 write!(&mut s, ", ").unwrap();
17 }
18 write!(&mut s, "{:0x}", b).unwrap();
19 }
20 writeln!(&mut s, "]").unwrap();
21
22 // Binary.
23 write!(&mut s, "[").unwrap();
24 for (i, b) in bytes.iter().enumerate() {
25 if i != 0 {
26 write!(&mut s, ", ").unwrap();
27 }
28 write!(&mut s, "{:08b}", b).unwrap();
29 }
30 writeln!(&mut s, "]").unwrap();
31
32 String::from_utf8(s).unwrap()
33 }
34
35 fn main() {
36 println!(
37 "
38 LEB128 Read-Eval-Print-Loop!
39
40 Converts numbers to signed and unsigned LEB128 and displays the results in
41 base-10, hex, and binary.
42 "
43 );
44
45 let mut stdin = io::BufReader::new(io::stdin());
46 let mut stdout = io::stdout();
47
48 let mut buf = vec![];
49
50 loop {
51 stdout.write_all(b"> ").expect("failed to write to stdout");
52 stdout.flush().expect("failed to flush stdout");
53
54 buf.clear();
55 let n = stdin
56 .read_until(b'\n', &mut buf)
57 .expect("failed to read line from stdin");
58 if n == 0 {
59 break;
60 }
61
62 let uleb = str::from_utf8(&buf)
63 .ok()
64 .and_then(|s| s.trim().parse().ok())
65 .and_then(|n: u64| {
66 let mut s = vec![];
67 leb128::write::unsigned(&mut s, n).ok()?;
68 Some(display(&s))
69 })
70 .unwrap_or_else(|| "error\n".into());
71 stdout
72 .write_all(b"# unsigned LEB128\n")
73 .and_then(|_| stdout.write_all(uleb.as_bytes()))
74 .and_then(|_| stdout.write_all(b"\n"))
75 .expect("failed to write to stdout");
76
77 let leb = str::from_utf8(&buf)
78 .ok()
79 .and_then(|s| s.trim().parse().ok())
80 .and_then(|n: i64| {
81 let mut s = vec![];
82 leb128::write::signed(&mut s, n).ok()?;
83 Some(display(&s))
84 })
85 .unwrap_or_else(|| "error\n".into());
86 stdout
87 .write_all(b"# signed LEB128\n")
88 .and_then(|_| stdout.write_all(leb.as_bytes()))
89 .and_then(|_| stdout.write_all(b"\n"))
90 .expect("failed to write to stdout");
91
92 stdout.flush().expect("failed to flush stdout");
93 }
94 }