1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use std::io::Write;
use std::ops::Deref;
use std::sync::{Arc, RwLock};
use serde::{Deserialize, Serialize};
use serde::de::{DeserializeOwned, Error};
use serde_json::Value;
pub type SocketHandle<'a> = &'a mut dyn Write;
pub type BoxedSocketListener = Box<dyn SocketListener + Send + Sync>;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SocketPacket {
pub ty: String,
pub requester: Option<String>,
pub data: Option<Value>
}
pub trait SocketListener {
fn message(&self, socket: SocketHandle, packet: SocketPacket);
}
pub trait SocketData {
const NAME: &'static str;
}
pub fn parse_packet_to_data<T: SocketData + DeserializeOwned>(packet: &SocketPacket) -> Result<T, serde_json::Error> {
if packet.ty == T::NAME {
if let Some(data) = &packet.data {
Ok(serde_json::from_value(data.clone())?)
} else {
Err(serde_json::Error::custom("Missing data"))
}
} else {
Err(serde_json::Error::custom("Invalid packet"))
}
}
pub fn check_packet_for_data<T: SocketData>(packet: &SocketPacket) -> bool {
packet.ty == T::NAME
}
pub fn write_in_chunks(handle: SocketHandle, data: String) -> Result<(), SocketError> {
for chunk in data.into_bytes().chunks(250) {
handle.write(chunk)?;
}
Ok(())
}
pub fn send_packet<T: SocketData + Serialize>(handle: SocketHandle, previous_packet: &SocketPacket, data: &T) -> Result<(), SocketError> {
let packet = SocketPacket {
ty: T::NAME.to_string(),
requester: previous_packet.requester.clone(),
data: Some(serde_json::to_value(data)?)
};
write_in_chunks(handle, format!("{}\u{0004}", serde_json::to_string(&packet)?))?;
Ok(())
}
pub fn send_packet_with_requester<T: SocketData + Serialize>(handle: SocketHandle, requester: &str, data: &T) -> Result<(), SocketError> {
let packet = SocketPacket {
ty: T::NAME.to_string(),
requester: Some(requester.to_string()),
data: Some(serde_json::to_value(data)?)
};
write_in_chunks(handle, format!("{}\u{0004}", serde_json::to_string(&packet)?))?;
Ok(())
}
pub fn send_no_data_packet_with_requester<T: SocketData>(handle: SocketHandle, requester: &str) -> Result<(), SocketError> {
let packet = SocketPacket {
ty: T::NAME.to_string(),
requester: Some(requester.to_string()),
data: None
};
write_in_chunks(handle, format!("{}\u{0004}", serde_json::to_string(&packet)?))?;
Ok(())
}
#[derive(Debug)]
pub enum SocketError {
SerdeError(serde_json::Error),
WriteError(std::io::Error),
}
impl From<serde_json::Error> for SocketError {
fn from(err: serde_json::Error) -> Self {
SocketError::SerdeError(err)
}
}
impl From<std::io::Error> for SocketError {
fn from(err: std::io::Error) -> Self {
SocketError::WriteError(err)
}
}
pub struct SocketManager {
listeners: RwLock<Vec<BoxedSocketListener>>,
}
impl SocketManager {
pub fn new() -> Arc<SocketManager> {
Arc::new(SocketManager {
listeners: RwLock::new(vec![])
})
}
pub fn add_listener(&self, listener: BoxedSocketListener) {
self.listeners.write().unwrap().push(listener);
}
pub fn message(&self, handle: SocketHandle, packet: SocketPacket) {
for listener in self.listeners.read().unwrap().deref() {
listener.message(handle, packet.clone());
}
}
}