summaryrefslogtreecommitdiffstats
path: root/src/protocol.rs
blob: 11f54a13be88878d4f9c74f862ae473f3e79c4f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! Newline-delimited protocol helpers shared by the client and server.
//!
//! TLS reads can return more than one line at a time. Keeping the leftover
//! bytes is essential: dropping them silently loses the next message.

use std::io::{self, Read};

#[derive(Debug, Default)]
pub struct LineBuffer {
    buffer: Vec<u8>,
}

impl LineBuffer {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn push(&mut self, bytes: &[u8]) {
        self.buffer.extend_from_slice(bytes);
    }

    /// Return the next complete line, including a line that ended at EOF.
    pub fn next_line(&mut self) -> Option<String> {
        let end = self.buffer.iter().position(|byte| *byte == b'\n')?;
        let mut line: Vec<u8> = self.buffer.drain(..=end).collect();
        line.pop(); // '\n'
        if line.last() == Some(&b'\r') {
            line.pop();
        }
        Some(String::from_utf8_lossy(&line).into_owned())
    }

    /// Return the unterminated remainder at EOF, if any.
    pub fn take_rest(&mut self) -> Option<String> {
        if self.buffer.is_empty() {
            return None;
        }
        let mut rest = std::mem::take(&mut self.buffer);
        if rest.last() == Some(&b'\r') {
            rest.pop();
        }
        Some(String::from_utf8_lossy(&rest).into_owned())
    }

    /// Read one line from a blocking reader, preserving any extra lines for
    /// the next call. Returns `None` at EOF with nothing buffered.
    pub fn read_line<R: Read>(&mut self, reader: &mut R) -> io::Result<Option<String>> {
        loop {
            if let Some(line) = self.next_line() {
                return Ok(Some(line));
            }

            let mut chunk = [0u8; 4096];
            match reader.read(&mut chunk) {
                Ok(0) => return Ok(self.take_rest()),
                Ok(n) => self.push(&chunk[..n]),
                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                Err(error) => return Err(error),
            }
        }
    }
}

/// A stable, user-facing message for a failed request.
pub fn io_failure_message(error: &io::Error) -> &'static str {
    match error.kind() {
        io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock => "ERROR Request timed out",
        _ => "ERROR Connection lost",
    }
}