blob: c7e4512dbeae8d6595ea081e8d681b9ca148942d (
plain)
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
|
use crate::wire::{
game::{Action, Update},
Lobby,
};
use async_std::sync::RwLock;
use std::collections::VecDeque;
pub enum ClientUpdate {
/// Change to the lobby state
Lobby(Lobby),
/// A game simulation update
GameUpdate(Update),
}
impl<'l> From<&'l Lobby> for ClientUpdate {
fn from(l: &'l Lobby) -> Self {
ClientUpdate::Lobby(l.clone())
}
}
impl<'l> From<&'l Update> for ClientUpdate {
fn from(u: &'l Update) -> Self {
ClientUpdate::GameUpdate(u.clone())
}
}
/// A message out buffer that can be attached to any server entity
pub struct Outbox {
queue: RwLock<VecDeque<ClientUpdate>>,
}
impl Outbox {
pub fn new() -> Self {
Self {
queue: Default::default(),
}
}
/// Queue a new item to send out
pub async fn queue(&self, update: impl Into<ClientUpdate>) {
let mut q = self.queue.write().await;
q.push_back(update.into());
}
/// Run a closure for all queued items
pub async fn run_for<F: Fn(&ClientUpdate)>(&self, handle: F) {
let q = self.queue.read().await;
q.iter().for_each(|item| handle(item));
}
/// Clear the outbox for the next update interval
pub async fn clear(&self) {
self.queue.write().await.clear();
}
}
pub struct Inbox {
queue: RwLock<VecDeque<Action>>,
}
impl Inbox {
pub fn new() -> Self {
Self {
queue: Default::default(),
}
}
/// Queue a new item to send out
pub async fn queue(&self, update: impl Into<Action>) {
let mut q = self.queue.write().await;
q.push_back(update.into());
}
pub async fn pop(&self) -> Option<Action> {
self.queue.write().await.pop_front()
}
}
|