gix_packetline/encode/
blocking_io.rs

1use 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
6/// Write a response-end message to `out`.
7pub fn response_end_to_write(mut out: impl io::Write) -> io::Result<usize> {
8    out.write_all(RESPONSE_END_LINE).map(|_| 4)
9}
10
11/// Write a delim message to `out`.
12pub fn delim_to_write(mut out: impl io::Write) -> io::Result<usize> {
13    out.write_all(DELIMITER_LINE).map(|_| 4)
14}
15
16/// Write a flush message to `out`.
17pub fn flush_to_write(mut out: impl io::Write) -> io::Result<usize> {
18    out.write_all(FLUSH_LINE).map(|_| 4)
19}
20
21/// Write an error `message` to `out`.
22pub fn error_to_write(message: &[u8], out: impl io::Write) -> io::Result<usize> {
23    prefixed_data_to_write(ERR_PREFIX, message, out)
24}
25
26/// Write `data` of `kind` to `out` using side-band encoding.
27pub 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
31/// Write a `data` message to `out`.
32pub fn data_to_write(data: &[u8], out: impl io::Write) -> io::Result<usize> {
33    prefixed_data_to_write(&[], data, out)
34}
35
36/// Write a `text` message to `out`, which is assured to end in a newline.
37pub 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}