scsys_actors/messages/
message.rs1use scsys::prelude::{AtomicId, Timestamp};
6
7#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
8#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
9pub struct Message<T = String> {
10 id: AtomicId,
11 data: Option<T>,
12 ts: Timestamp<u64>,
13}
14
15impl<T> Message<T> {
16 pub fn new(value: T) -> Self {
17 Self {
18 id: AtomicId::new(),
19 data: Some(value),
20 ts: Timestamp::now(),
21 }
22 }
23
24 pub fn clear(&mut self) {
25 self.on_update();
26 self.data = None;
27 }
28
29 pub fn data(&self) -> Option<&T> {
30 self.data.as_ref()
31 }
32
33 pub fn data_mut(&mut self) -> Option<&mut T> {
34 self.data.as_mut()
35 }
36
37 pub fn id(&self) -> usize {
38 *self.id
39 }
40
41 pub fn set_data(&mut self, data: Option<T>) {
42 self.on_update();
43 self.data = data;
44 }
45
46 pub fn timestamp(&self) -> Timestamp {
47 self.ts
48 }
49
50 pub fn with_data(mut self, data: T) -> Self {
51 self.on_update();
52 self.data = Some(data);
53 self
54 }
55
56 fn on_update(&mut self) {
57 self.ts = Timestamp::now();
58 }
59}
60
61impl<T> Default for Message<T> {
62 fn default() -> Self {
63 Self {
64 id: AtomicId::new(),
65 data: None,
66 ts: Timestamp::now(),
67 }
68 }
69}
70impl<T> core::fmt::Display for Message<T>
71where
72 T: core::fmt::Display,
73{
74 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
75 if let Some(data) = self.data() {
76 return write!(f, "{}", data);
77 }
78 write!(f, "{}", self.timestamp())
79 }
80}
81
82impl<T> From<Option<T>> for Message<T> {
83 fn from(data: Option<T>) -> Self {
84 if let Some(msg) = data {
85 return Self::new(msg);
86 }
87 Self::default()
88 }
89}
90
91impl<T> From<T> for Message<T> {
92 fn from(data: T) -> Self {
93 Self::new(data)
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn test_default_message() {
103 let a = Message::<&str>::default();
104 assert_eq!(&a.data, &a.data)
105 }
106}