git_packetline/read/
blocking_io.rs

1use std::io;
2
3use bstr::ByteSlice;
4
5use crate::{
6    decode,
7    read::{ExhaustiveOutcome, WithSidebands},
8    PacketLineRef, StreamingPeekableIter, MAX_LINE_LEN, U16_HEX_BYTES,
9};
10
11/// Non-IO methods
12impl<T> StreamingPeekableIter<T>
13where
14    T: io::Read,
15{
16    fn read_line_inner<'a>(reader: &mut T, buf: &'a mut [u8]) -> io::Result<Result<PacketLineRef<'a>, decode::Error>> {
17        let (hex_bytes, data_bytes) = buf.split_at_mut(4);
18        reader.read_exact(hex_bytes)?;
19        let num_data_bytes = match decode::hex_prefix(hex_bytes) {
20            Ok(decode::PacketLineOrWantedSize::Line(line)) => return Ok(Ok(line)),
21            Ok(decode::PacketLineOrWantedSize::Wanted(additional_bytes)) => additional_bytes as usize,
22            Err(err) => return Ok(Err(err)),
23        };
24
25        let (data_bytes, _) = data_bytes.split_at_mut(num_data_bytes);
26        reader.read_exact(data_bytes)?;
27        match decode::to_data_line(data_bytes) {
28            Ok(line) => Ok(Ok(line)),
29            Err(err) => Ok(Err(err)),
30        }
31    }
32
33    /// This function is needed to help the borrow checker allow us to return references all the time
34    /// It contains a bunch of logic shared between peek and read_line invocations.
35    fn read_line_inner_exhaustive<'a>(
36        reader: &mut T,
37        buf: &'a mut Vec<u8>,
38        delimiters: &[PacketLineRef<'static>],
39        fail_on_err_lines: bool,
40        buf_resize: bool,
41    ) -> ExhaustiveOutcome<'a> {
42        (
43            false,
44            None,
45            Some(match Self::read_line_inner(reader, buf) {
46                Ok(Ok(line)) => {
47                    if delimiters.contains(&line) {
48                        let stopped_at = delimiters.iter().find(|l| **l == line).cloned();
49                        buf.clear();
50                        return (true, stopped_at, None);
51                    } else if fail_on_err_lines {
52                        if let Some(err) = line.check_error() {
53                            let err = err.0.as_bstr().to_owned();
54                            buf.clear();
55                            return (
56                                true,
57                                None,
58                                Some(Err(io::Error::new(
59                                    io::ErrorKind::Other,
60                                    crate::read::Error { message: err },
61                                ))),
62                            );
63                        }
64                    }
65                    let len = line
66                        .as_slice()
67                        .map(|s| s.len() + U16_HEX_BYTES)
68                        .unwrap_or(U16_HEX_BYTES);
69                    if buf_resize {
70                        buf.resize(len, 0);
71                    }
72                    Ok(Ok(crate::decode(buf).expect("only valid data here")))
73                }
74                Ok(Err(err)) => {
75                    buf.clear();
76                    Ok(Err(err))
77                }
78                Err(err) => {
79                    buf.clear();
80                    Err(err)
81                }
82            }),
83        )
84    }
85
86    /// Read a packet line into the internal buffer and return it.
87    ///
88    /// Returns `None` if the end of iteration is reached because of one of the following:
89    ///
90    ///  * natural EOF
91    ///  * ERR packet line encountered if [`fail_on_err_lines()`][StreamingPeekableIter::fail_on_err_lines()] is true.
92    ///  * A `delimiter` packet line encountered
93    pub fn read_line(&mut self) -> Option<io::Result<Result<PacketLineRef<'_>, decode::Error>>> {
94        if self.is_done {
95            return None;
96        }
97        if !self.peek_buf.is_empty() {
98            std::mem::swap(&mut self.peek_buf, &mut self.buf);
99            self.peek_buf.clear();
100            Some(Ok(Ok(crate::decode(&self.buf).expect("only valid data in peek buf"))))
101        } else {
102            if self.buf.len() != MAX_LINE_LEN {
103                self.buf.resize(MAX_LINE_LEN, 0);
104            }
105            let (is_done, stopped_at, res) = Self::read_line_inner_exhaustive(
106                &mut self.read,
107                &mut self.buf,
108                self.delimiters,
109                self.fail_on_err_lines,
110                false,
111            );
112            self.is_done = is_done;
113            self.stopped_at = stopped_at;
114            res
115        }
116    }
117
118    /// Peek the next packet line without consuming it.
119    ///
120    /// Multiple calls to peek will return the same packet line, if there is one.
121    pub fn peek_line(&mut self) -> Option<io::Result<Result<PacketLineRef<'_>, decode::Error>>> {
122        if self.is_done {
123            return None;
124        }
125        if self.peek_buf.is_empty() {
126            self.peek_buf.resize(MAX_LINE_LEN, 0);
127            let (is_done, stopped_at, res) = Self::read_line_inner_exhaustive(
128                &mut self.read,
129                &mut self.peek_buf,
130                self.delimiters,
131                self.fail_on_err_lines,
132                true,
133            );
134            self.is_done = is_done;
135            self.stopped_at = stopped_at;
136            res
137        } else {
138            Some(Ok(Ok(crate::decode(&self.peek_buf).expect("only valid data here"))))
139        }
140    }
141
142    /// Return this instance as implementor of [`Read`][io::Read] assuming side bands to be used in all received packet lines.
143    /// Each invocation of [`read_line()`][io::BufRead::read_line()] returns a packet line.
144    ///
145    /// Progress or error information will be passed to the given `handle_progress(is_error, text)` function, with `is_error: bool`
146    /// being true in case the `text` is to be interpreted as error.
147    ///
148    /// _Please note_ that side bands need to be negotiated with the server.
149    pub fn as_read_with_sidebands<F: FnMut(bool, &[u8])>(&mut self, handle_progress: F) -> WithSidebands<'_, T, F> {
150        WithSidebands::with_progress_handler(self, handle_progress)
151    }
152
153    /// Same as [`as_read_with_sidebands(…)`][StreamingPeekableIter::as_read_with_sidebands()], but for channels without side band support.
154    ///
155    /// The type parameter `F` needs to be configured for this method to be callable using the 'turbofish' operator.
156    /// Use [`as_read()`][StreamingPeekableIter::as_read()].
157    pub fn as_read_without_sidebands<F: FnMut(bool, &[u8])>(&mut self) -> WithSidebands<'_, T, F> {
158        WithSidebands::without_progress_handler(self)
159    }
160
161    /// Same as [`as_read_with_sidebands(…)`][StreamingPeekableIter::as_read_with_sidebands()], but for channels without side band support.
162    ///
163    /// Due to the preconfigured function type this method can be called without 'turbofish'.
164    pub fn as_read(&mut self) -> WithSidebands<'_, T, fn(bool, &[u8])> {
165        WithSidebands::new(self)
166    }
167}