-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
349 lines (265 loc) · 11.3 KB
/
lib.rs
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
pub mod event;
pub mod message;
pub mod state;
// Soon...
// macro_rules! event_loop {
// () => {};
// }
#[cfg(test)]
mod test {
use std::fmt::{Display, Formatter};
use std::hash::Hash;
use std::sync::Arc;
use tokio::sync::{mpsc, RwLock};
use tokio::task::JoinHandle;
use super::*;
// use state::State;
use event::EventLoop;
use crate::message::{MessageEmitter, MessageError, MessageHandle};
#[derive(Debug, Hash)]
enum TestMessage {
Increment,
Decrement,
GetCurrent,
GetError,
}
#[derive(Debug)]
enum TestResponse {
Current(usize),
}
#[derive(Debug)]
struct TestClose;
impl Display for TestClose {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "TestClose")
}
}
#[derive(Debug, PartialEq)] // PartialEq is required for the test, not a normal requirement
enum TestError {
TestError,
FailedToIncrement,
FailedToDecrement,
FailedToGetCurrent,
AlreadyClosed,
}
impl Display for TestError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
TestError::TestError =>
write!(f, "Error used to test errors"),
TestError::FailedToIncrement =>
write!(f, "Failed to increment number"),
TestError::FailedToDecrement =>
write!(f, "Failed to decrement number"),
TestError::FailedToGetCurrent =>
write!(f, "Failed to get current number"),
TestError::AlreadyClosed =>
write!(f, "Already closed"),
}
}
}
impl std::error::Error for TestError {}
type TestMessageType = message::MessageType<TestMessage, TestResponse, TestClose, TestError>;
#[derive(Clone)]
struct TestEventLoop {
// state: Arc<TestState>,
event_handle: Arc<RwLock<JoinHandle<Result<TestClose, TestError>>>>,
message_handle: MessageHandle<TestMessage, TestResponse, TestClose, TestError>,
}
impl TestEventLoop {
async fn new() -> Self {
let (message_tx, mut message_rx) = mpsc::channel::<TestMessageType>(256);
// let thread_state = Arc::new(TestState {});
// let state = Arc::clone(&thread_state);
let event_loop = tokio::spawn(async move {
//let state = thread_state;
let mut message_rx = message_rx;
//let mut reference_count: usize = 0;
let mut num = 0;
// This makes it all a bit more centralized rather than having a bunch of closures
loop {
tokio::select! {
m = message_rx.recv() => {
if let Some(m) = m {
match m {
TestMessageType::Event(mut message) => {
match message.message() {
// Notifications
TestMessage::Decrement => {
num-= 1
}
TestMessage::Increment => {
num+= 1
}
// Messages
TestMessage::GetCurrent=> {
match message.callback_ok(TestResponse::Current(num)) {
Ok(_) => {}
Err(_) => {
#[cfg(debug_assertions)]
dbg!("Failed to send TestResponse::Current");
}
}
}
TestMessage::GetError => {
match message.callback_err(TestError::TestError) {
Ok(_) => {}
Err(_) => {
#[cfg(debug_assertions)]
dbg!("Failed to send TestError::TestError");
}
}
}
}
},
TestMessageType::Close(reason) => {
#[cfg(debug_assertions)]
dbg!("Closing TestEventLoop: {}", reason.to_string());
break Ok(reason)
}
TestMessageType::EventResponse(_) => {
#[cfg(debug_assertions)]
dbg!("Received EventResponse, ignoring");
}
}
}
}
}
}
});
Self {
event_handle: Arc::new(RwLock::new(event_loop)),
message_handle: MessageHandle::new(message_tx, #[cfg(feature = "cache")]None),
}
}
pub async fn increment(&self) -> Result<(), TestError> {
match self.message_handle.send_notification(TestMessage::Increment, "increment").await {
Ok(_) => Ok(()),
Err(_) => Err(TestError::FailedToIncrement)
}
}
pub async fn decrement(&self) -> Result<(), TestError> {
match self.message_handle.send_notification(TestMessage::Decrement, "decrement").await {
Ok(_) => Ok(()),
Err(_) => Err(TestError::FailedToDecrement)
}
}
pub async fn current(&self) -> Result<usize, TestError> {
// if we know the response here could we convert on the fly?
match self.message_handle.send_message(TestMessage::GetCurrent, "current").await {
Ok(res) => {
match res {
TestResponse::Current(i) => Ok(i),
//_ => unreachable!()
}
}
Err(_e) => Err(TestError::FailedToGetCurrent)
}
}
#[cfg(feature = "cache")]
pub async fn current_w_cache(&self) -> Result<usize, TestError> {
// if we know the response here could we convert on the fly?
match self.message_handle.send_message_or_cache(TestMessage::GetCurrent, "current_w_cache").await {
Ok(res) => {
match *res {
TestResponse::Current(i) => Ok(i),
//_ => unreachable!()
}
}
Err(_e) => Err(TestError::FailedToGetCurrent)
}
}
// TODO: Make a wrapper proc macro for this
pub async fn error_test(&self) -> Result<(), TestError> {
match self.message_handle.send_message(TestMessage::GetError, "error_test").await {
Ok(_) => unreachable!(),
Err(_e) => Err(TestError::TestError)
}
}
}
impl MessageEmitter for TestEventLoop {
type Message = TestMessage;
type Response = TestResponse;
unsafe fn message_handle(&self) -> &MessageHandle<Self::Message, TestResponse, TestClose, TestError> {
&self.message_handle
}
}
#[async_trait::async_trait]
impl EventLoop for TestEventLoop {
type Close = TestClose;
type Err = TestError;
fn join_handle(&self) -> &Arc<RwLock<JoinHandle<Result<Self::Close, Self::Err>>>> {
&self.event_handle
}
fn is_closed(&self) -> bool {
self.message_handle.is_closed()
}
async fn close(&self, reason: Self::Close) -> Result<(), Self::Err> {
self.message_handle.close(reason).await.map_err(|_| TestError::AlreadyClosed)
}
}
/// Returns how many successful increments were made
fn spawn_test_task(test_ref: TestEventLoop, inc: u32) -> JoinHandle<Result<u32, TestError>>
{
tokio::task::spawn(async move {
let test_event_loop_ref = test_ref;
let mut incs = 0;
for _ in 0..inc {
match test_event_loop_ref.increment().await {
Ok(_) => incs += 1,
Err(e) => {
println!("Failed to increment: {:?}", e);
}
}
}
Ok(incs)
})
}
#[tokio::test]
async fn test_event_system() {
// As the constructor returns a reference to the event loop, it is not directly the event loop
let main_task = TestEventLoop::new().await;
let task_1 = spawn_test_task(main_task.clone(), 1000);
let task_2 = spawn_test_task(main_task.clone(), 1000);
let (res_1, res_2) = tokio::join!(task_1,task_2);
print!("Task 1: {:?}, Task 2: {:?}", res_1, res_2);
let current = main_task.current().await.unwrap();
assert_eq!(current, 2000);
}
#[tokio::test]
async fn test_send_error() {
// As the constructor returns a reference to the event loop, it is not directly the event loop
let main_task = TestEventLoop::new().await;
let task_1 = spawn_test_task(main_task.clone(), 1000);
let (res_1) = tokio::join!(task_1);
let current = main_task.current().await.unwrap();
assert_eq!(current, 2000);
}
#[tokio::test]
async fn test_error_system() {
let test = TestEventLoop::new().await;
let err = test.error_test().await;
assert_eq!(err, Err(TestError::TestError));
}
#[tokio::test]
async fn test_close() {
let test = TestEventLoop::new().await;
let task_1 = test.clone();
assert_eq!(test.close(TestClose).await, Ok(()));
assert_eq!(task_1.close(TestClose).await, Err(TestError::AlreadyClosed));
}
#[cfg(feature = "cache")] #[tokio::test]
async fn test_caching() {
let e_loop = TestEventLoop::new().await;
assert_eq!(e_loop.current_w_cache().await, Ok(0));
assert_eq!(e_loop.current().await, Ok(0));
e_loop.increment().await.unwrap();
assert_eq!(e_loop.current().await, Ok(1));
assert_eq!(e_loop.current_w_cache().await, Ok(0));
assert_eq!(e_loop.current_w_cache().await, Ok(0));
}
#[test]
fn testing() {
dbg!(std::mem::size_of::<&'sta>());
}
}