git_packetline/write/
blocking_io.rs

1use std::io;
2
3use crate::{MAX_DATA_LEN, U16_HEX_BYTES};
4
5/// An implementor of [`Write`][io::Write] which passes all input to an inner `Write` in packet line data encoding,
6/// one line per `write(…)` call or as many lines as it takes if the data doesn't fit into the maximum allowed line length.
7pub struct Writer<T> {
8    /// the `Write` implementation to which to propagate packet lines
9    inner: T,
10    binary: bool,
11}
12
13impl<T: io::Write> Writer<T> {
14    /// Create a new instance from the given `write`
15    pub fn new(write: T) -> Self {
16        Writer {
17            inner: write,
18            binary: true,
19        }
20    }
21}
22
23/// Non-IO methods
24impl<T> Writer<T> {
25    /// If called, each call to [`write()`][io::Write::write()] will write bytes as is.
26    pub fn enable_binary_mode(&mut self) {
27        self.binary = true;
28    }
29    /// If called, each call to [`write()`][io::Write::write()] will write the input as text, appending a trailing newline
30    /// if needed before writing.
31    pub fn enable_text_mode(&mut self) {
32        self.binary = false;
33    }
34    /// Return the inner writer, consuming self.
35    pub fn into_inner(self) -> T {
36        self.inner
37    }
38    /// Return a mutable reference to the inner writer, useful if packet lines should be serialized directly.
39    pub fn inner_mut(&mut self) -> &mut T {
40        &mut self.inner
41    }
42}
43
44impl<T: io::Write> io::Write for Writer<T> {
45    fn write(&mut self, mut buf: &[u8]) -> io::Result<usize> {
46        if buf.is_empty() {
47            return Err(io::Error::new(
48                io::ErrorKind::Other,
49                "empty packet lines are not permitted as '0004' is invalid",
50            ));
51        }
52
53        let mut written = 0;
54        while !buf.is_empty() {
55            let (data, rest) = buf.split_at(buf.len().min(MAX_DATA_LEN));
56            written += if self.binary {
57                crate::encode::data_to_write(data, &mut self.inner)
58            } else {
59                crate::encode::text_to_write(data, &mut self.inner)
60            }?;
61            // subtract header (and trailing NL) because write-all can't handle writing more than it passes in
62            written -= U16_HEX_BYTES + usize::from(!self.binary);
63            buf = rest;
64        }
65        Ok(written)
66    }
67
68    fn flush(&mut self) -> io::Result<()> {
69        self.inner.flush()
70    }
71}