gix_packetline/encode/
blocking_io.rs1use std::io;
2
3use super::u16_to_hex;
4use crate::{encode::Error, Channel, DELIMITER_LINE, ERR_PREFIX, FLUSH_LINE, MAX_DATA_LEN, RESPONSE_END_LINE};
5
6pub fn response_end_to_write(mut out: impl io::Write) -> io::Result<usize> {
8 out.write_all(RESPONSE_END_LINE).map(|_| 4)
9}
10
11pub fn delim_to_write(mut out: impl io::Write) -> io::Result<usize> {
13 out.write_all(DELIMITER_LINE).map(|_| 4)
14}
15
16pub fn flush_to_write(mut out: impl io::Write) -> io::Result<usize> {
18 out.write_all(FLUSH_LINE).map(|_| 4)
19}
20
21pub fn error_to_write(message: &[u8], out: impl io::Write) -> io::Result<usize> {
23 prefixed_data_to_write(ERR_PREFIX, message, out)
24}
25
26pub fn band_to_write(kind: Channel, data: &[u8], out: impl io::Write) -> io::Result<usize> {
28 prefixed_data_to_write(&[kind as u8], data, out)
29}
30
31pub fn data_to_write(data: &[u8], out: impl io::Write) -> io::Result<usize> {
33 prefixed_data_to_write(&[], data, out)
34}
35
36pub fn text_to_write(text: &[u8], out: impl io::Write) -> io::Result<usize> {
38 prefixed_and_suffixed_data_to_write(&[], text, b"\n", out)
39}
40
41fn prefixed_data_to_write(prefix: &[u8], data: &[u8], out: impl io::Write) -> io::Result<usize> {
42 prefixed_and_suffixed_data_to_write(prefix, data, &[], out)
43}
44
45fn prefixed_and_suffixed_data_to_write(
46 prefix: &[u8],
47 data: &[u8],
48 suffix: &[u8],
49 mut out: impl io::Write,
50) -> io::Result<usize> {
51 let data_len = prefix.len() + data.len() + suffix.len();
52 if data_len > MAX_DATA_LEN {
53 return Err(io::Error::new(
54 io::ErrorKind::Other,
55 Error::DataLengthLimitExceeded {
56 length_in_bytes: data_len,
57 },
58 ));
59 }
60 if data.is_empty() {
61 return Err(io::Error::new(io::ErrorKind::Other, Error::DataIsEmpty));
62 }
63
64 let data_len = data_len + 4;
65 let buf = u16_to_hex(data_len as u16);
66
67 out.write_all(&buf)?;
68 if !prefix.is_empty() {
69 out.write_all(prefix)?;
70 }
71 out.write_all(data)?;
72 if !suffix.is_empty() {
73 out.write_all(suffix)?;
74 }
75 Ok(data_len)
76}