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