#[derive(Debug, Clone, PartialEq)]
pub struct Message {
pub from: u64,
pub payload: Payload,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Payload {
Text(String),
Int(i64),
Float(f64),
Bool(bool),
Bytes(Vec<u8>),
Nil,
}
impl Message {
pub fn text(s: impl Into<String>) -> Self {
Self { from: 0, payload: Payload::Text(s.into()) }
}
pub fn int(i: i64) -> Self {
Self { from: 0, payload: Payload::Int(i) }
}
pub fn float(f: f64) -> Self {
Self { from: 0, payload: Payload::Float(f) }
}
pub fn bool(b: bool) -> Self {
Self { from: 0, payload: Payload::Bool(b) }
}
pub fn bytes(b: impl Into<Vec<u8>>) -> Self {
Self { from: 0, payload: Payload::Bytes(b.into()) }
}
pub fn nil() -> Self {
Self { from: 0, payload: Payload::Nil }
}
pub fn payload(&self) -> &Payload {
&self.payload
}
pub fn as_str(&self) -> Option<&str> {
match &self.payload { Payload::Text(s) => Some(s), _ => None }
}
pub fn as_i64(&self) -> Option<i64> {
match &self.payload { Payload::Int(i) => Some(*i), _ => None }
}
pub fn as_f64(&self) -> Option<f64> {
match &self.payload { Payload::Float(f) => Some(*f), _ => None }
}
pub fn as_bool(&self) -> Option<bool> {
match &self.payload { Payload::Bool(b) => Some(*b), _ => None }
}
}
impl PartialEq<&str> for Message {
fn eq(&self, other: &&str) -> bool {
matches!(&self.payload, Payload::Text(s) if s == *other)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constructors() {
assert_eq!(Message::text("hi").as_str(), Some("hi"));
assert_eq!(Message::int(42).as_i64(), Some(42));
assert_eq!(Message::float(3.14).as_f64(), Some(3.14));
assert_eq!(Message::bool(true).as_bool(), Some(true));
assert!(Message::nil().payload() == &Payload::Nil);
}
#[test]
fn str_equality() {
assert!(Message::text("ping") == "ping");
assert!(Message::text("ping") != "pong");
}
}