apt-transport 0.1.0

APT transport abstraction, allowing for custom APT transport implementations in Rust
Documentation
use crate::{Error, message::Message};

/// Transport-independent byte stream that yields APT messages.
///
/// This struct takes lines of bytes from an underlying byte stream and
/// yields complete APT messages when they are ready.
#[derive(Debug, Default)]
pub struct MessageStream {
    buffer: Vec<u8>,
}

impl MessageStream {
    /// Takes a line and optionally returns a complete APT message.
    ///
    /// Pass an empty slice to signal EOF. In this case:
    /// - Returns `None` if the internal buffer is empty (clean EOF)
    /// - Returns `Some(Err(Error::UnexpectedEof))` if the buffer has partial data
    pub fn push_line(&mut self, line: &[u8]) -> Option<Result<Message, Error>> {
        // Handle EOF case
        if line.is_empty() {
            return if self.buffer.is_empty() {
                None
            } else {
                Some(Err(Error::UnexpectedEof))
            };
        }

        self.buffer.extend_from_slice(line);
        if line == b"\n" {
            let message = Message::from_bytes(&self.buffer);
            self.buffer.clear();
            Some(message)
        } else {
            None
        }
    }
}