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
use std::io::{Result, Write};
pub trait Output: Write {
fn write_str(&mut self, s: &str) -> Result<usize>;
}
pub struct Writer<W: Write> {
writer: W,
}
impl<W: Write> Output for Writer<W> {
fn write_str(&mut self, s: &str) -> Result<usize> {
self.writer.write(s.as_bytes())
}
}
impl<W: Write> Write for Writer<W> {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.writer.write(buf)
}
fn flush(&mut self) -> Result<()> {
self.writer.flush()
}
}
pub struct StringOutput {
value: String,
}
impl StringOutput {
pub fn new() -> Self {
Self {
value: String::new(),
}
}
}
impl Into<String> for StringOutput {
fn into(self) -> String {
self.value
}
}
impl Output for StringOutput {
fn write_str(&mut self, s: &str) -> Result<usize> {
self.write(s.as_bytes())
}
}
impl Write for StringOutput {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let s = match std::str::from_utf8(buf) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
self.value.push_str(s);
Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}