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
use crate::{MAX_DATA_LEN, U16_HEX_BYTES};
use std::io;
pub struct Writer<T> {
pub inner: T,
binary: bool,
}
impl<T: io::Write> Writer<T> {
pub fn new(write: T) -> Self {
Writer {
inner: write,
binary: true,
}
}
pub fn enable_binary_mode(&mut self) {
self.binary = true;
}
pub fn enable_text_mode(&mut self) {
self.binary = false;
}
pub fn text_mode(mut self) -> Self {
self.binary = false;
self
}
pub fn binary_mode(mut self) -> Self {
self.binary = true;
self
}
}
impl<T: io::Write> io::Write for Writer<T> {
fn write(&mut self, mut buf: &[u8]) -> io::Result<usize> {
if buf.is_empty() {
return Err(io::Error::new(
io::ErrorKind::Other,
"empty packet lines are not permitted as '0004' is invalid",
));
}
let mut written = 0;
while !buf.is_empty() {
let (data, rest) = buf.split_at(buf.len().min(MAX_DATA_LEN));
written += if self.binary {
crate::encode::data_to_write(data, &mut self.inner)
} else {
crate::encode::text_to_write(data, &mut self.inner)
}
.map_err(|err| {
use crate::encode::Error::*;
match err {
Io(err) => err,
DataIsEmpty | DataLengthLimitExceeded(_) => {
unreachable!("We are handling empty and large data here, so this can't ever happen")
}
}
})?;
written -= U16_HEX_BYTES + if self.binary { 0 } else { 1 };
buf = rest;
}
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}