wirepact 0.1.0

A teaching protocol crate: protocols are contracts, not HTTP.
Documentation
use crate::error::{Result, WirePactError};
use crate::message::Message;
use bytes::BytesMut;

/// Newline-delimited text codec for human-friendly clients (`nc`, telnet).
#[derive(Debug, Clone, Default)]
pub struct LineCodec {
    buffer: BytesMut,
}

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

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

    pub fn buffered_len(&self) -> usize {
        self.buffer.len()
    }

    pub fn decode_messages(&mut self) -> Result<Vec<Message>> {
        let mut messages = Vec::new();

        while let Some(newline) = self.buffer.iter().position(|&b| b == b'\n') {
            let line_bytes = self.buffer.split_to(newline + 1);
            let line = std::str::from_utf8(&line_bytes[..line_bytes.len() - 1])
                .map_err(|_| WirePactError::InvalidLine("invalid UTF-8".into()))?
                .trim_end_matches('\r');

            if line.is_empty() {
                continue;
            }

            messages.push(parse_line(line)?);
        }

        Ok(messages)
    }

    pub fn encode(&self, message: &Message) -> Vec<u8> {
        format!("{message}\n").into_bytes()
    }
}

fn parse_line(line: &str) -> Result<Message> {
    let mut parts = line.splitn(2, ' ');
    let command = parts.next().unwrap_or_default();
    let rest = parts.next().unwrap_or_default();

    match command {
        "HELLO" => {
            if rest.is_empty() {
                return Err(WirePactError::InvalidLine("HELLO requires a name".into()));
            }
            Ok(Message::Hello {
                name: rest.to_string(),
            })
        }
        "WELCOME" => {
            if rest.is_empty() {
                return Err(WirePactError::InvalidLine("WELCOME requires a name".into()));
            }
            Ok(Message::Welcome {
                name: rest.to_string(),
            })
        }
        "PING" => Ok(Message::Ping),
        "PONG" => Ok(Message::Pong),
        "ECHO" => {
            if rest.is_empty() {
                return Err(WirePactError::InvalidLine("ECHO requires a payload".into()));
            }
            Ok(Message::Echo {
                payload: rest.as_bytes().to_vec(),
            })
        }
        "GOODBYE" => Ok(Message::Goodbye),
        "BYE" => Ok(Message::Bye),
        "ERR" => {
            let mut err_parts = rest.splitn(2, ' ');
            let code = err_parts
                .next()
                .ok_or_else(|| WirePactError::InvalidLine("ERR requires a code".into()))?
                .parse::<u8>()
                .map_err(|_| WirePactError::InvalidLine("ERR code must be u8".into()))?;
            let message = err_parts
                .next()
                .ok_or_else(|| WirePactError::InvalidLine("ERR requires a message".into()))?
                .to_string();
            Ok(Message::Error { code, message })
        }
        other => Err(WirePactError::InvalidLine(format!(
            "unknown command: {other}"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn round_trip_line_messages() {
        let mut codec = LineCodec::new();
        codec.feed(b"HELLO sam\nPING\nECHO hi there\nGOODBYE\n");

        let messages = codec.decode_messages().unwrap();
        assert_eq!(messages.len(), 4);
        assert_eq!(messages[0], Message::hello("sam"));
        assert_eq!(messages[1], Message::Ping);
        assert_eq!(messages[2], Message::echo(b"hi there"));
        assert_eq!(messages[3], Message::Goodbye);
    }

    #[test]
    fn encode_line_message() {
        let codec = LineCodec::new();
        assert_eq!(codec.encode(&Message::Ping), b"PING\n");
    }
}