wirepact 0.1.0

A teaching protocol crate: protocols are contracts, not HTTP.
Documentation
use std::fmt;

/// Semantic messages shared by both line and frame encodings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Message {
    Hello { name: String },
    Welcome { name: String },
    Ping,
    Pong,
    Echo { payload: Vec<u8> },
    EchoReply { payload: Vec<u8> },
    Goodbye,
    Bye,
    Error { code: u8, message: String },
}

impl Message {
    pub fn hello(name: impl Into<String>) -> Self {
        Self::Hello { name: name.into() }
    }

    pub fn welcome(name: impl Into<String>) -> Self {
        Self::Welcome { name: name.into() }
    }

    pub fn echo(payload: impl Into<Vec<u8>>) -> Self {
        Self::Echo {
            payload: payload.into(),
        }
    }

    pub fn echo_reply(payload: impl Into<Vec<u8>>) -> Self {
        Self::EchoReply {
            payload: payload.into(),
        }
    }

    pub fn error(code: u8, message: impl Into<String>) -> Self {
        Self::Error {
            code,
            message: message.into(),
        }
    }

    /// Typical server response to a client hello.
    pub fn respond(&self) -> Option<Self> {
        match self {
            Self::Hello { name } => Some(Self::welcome(name.clone())),
            Self::Ping => Some(Self::Pong),
            Self::Echo { payload } => Some(Self::echo_reply(payload.clone())),
            Self::Goodbye => Some(Self::Bye),
            _ => None,
        }
    }
}

impl fmt::Display for Message {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hello { name } => write!(f, "HELLO {name}"),
            Self::Welcome { name } => write!(f, "WELCOME {name}"),
            Self::Ping => write!(f, "PING"),
            Self::Pong => write!(f, "PONG"),
            Self::Echo { payload } => {
                let text = String::from_utf8_lossy(payload);
                write!(f, "ECHO {text}")
            }
            Self::EchoReply { payload } => {
                let text = String::from_utf8_lossy(payload);
                write!(f, "ECHOREPLY {text}")
            }
            Self::Goodbye => write!(f, "GOODBYE"),
            Self::Bye => write!(f, "BYE"),
            Self::Error { code, message } => write!(f, "ERR {code} {message}"),
        }
    }
}