Skip to main content

sprite_core/
message.rs

1/// A message sent between actors.
2#[derive(Debug, Clone, PartialEq)]
3pub struct Message {
4    pub from: u64,
5    pub payload: Payload,
6}
7
8/// The payload of a message.
9#[derive(Debug, Clone, PartialEq)]
10pub enum Payload {
11    Text(String),
12    Int(i64),
13    Float(f64),
14    Bool(bool),
15    Bytes(Vec<u8>),
16    Nil,
17}
18
19impl Message {
20    pub fn text(s: impl Into<String>) -> Self {
21        Self { from: 0, payload: Payload::Text(s.into()) }
22    }
23    pub fn int(i: i64) -> Self {
24        Self { from: 0, payload: Payload::Int(i) }
25    }
26    pub fn float(f: f64) -> Self {
27        Self { from: 0, payload: Payload::Float(f) }
28    }
29    pub fn bool(b: bool) -> Self {
30        Self { from: 0, payload: Payload::Bool(b) }
31    }
32    pub fn bytes(b: impl Into<Vec<u8>>) -> Self {
33        Self { from: 0, payload: Payload::Bytes(b.into()) }
34    }
35    pub fn nil() -> Self {
36        Self { from: 0, payload: Payload::Nil }
37    }
38    pub fn payload(&self) -> &Payload {
39        &self.payload
40    }
41    pub fn as_str(&self) -> Option<&str> {
42        match &self.payload { Payload::Text(s) => Some(s), _ => None }
43    }
44    pub fn as_i64(&self) -> Option<i64> {
45        match &self.payload { Payload::Int(i) => Some(*i), _ => None }
46    }
47    pub fn as_f64(&self) -> Option<f64> {
48        match &self.payload { Payload::Float(f) => Some(*f), _ => None }
49    }
50    pub fn as_bool(&self) -> Option<bool> {
51        match &self.payload { Payload::Bool(b) => Some(*b), _ => None }
52    }
53}
54
55impl PartialEq<&str> for Message {
56    fn eq(&self, other: &&str) -> bool {
57        matches!(&self.payload, Payload::Text(s) if s == *other)
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    #[test]
65    fn constructors() {
66        assert_eq!(Message::text("hi").as_str(), Some("hi"));
67        assert_eq!(Message::int(42).as_i64(), Some(42));
68        assert_eq!(Message::float(3.14).as_f64(), Some(3.14));
69        assert_eq!(Message::bool(true).as_bool(), Some(true));
70        assert!(Message::nil().payload() == &Payload::Nil);
71    }
72    #[test]
73    fn str_equality() {
74        assert!(Message::text("ping") == "ping");
75        assert!(Message::text("ping") != "pong");
76    }
77}