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
use core::{
pin::Pin,
task::{
Context,
Poll,
},
};
use futures::{
prelude::*,
ready,
};
use serde::{
Deserialize,
Serialize,
};
mod background;
pub mod chain;
pub use background::*;
#[derive(Deserialize, Serialize, Eq, PartialEq, Debug, Clone, Copy)]
pub enum Msg<T> {
Broadcast { to: i8, from: i8, data: T },
Direct { to: i8, from: i8, data: T },
}
impl<T> Msg<T> {
pub fn broadcast(data: T) -> Self {
Self::Broadcast {
from: 0,
to: 0,
data,
}
}
pub fn direct(to: i8, data: T) -> Self {
Self::Direct { to, from: 0, data }
}
pub fn set_from(&mut self, new_from: i8) {
match self {
Self::Direct { ref mut from, .. } | Self::Broadcast { ref mut from, .. } => {
*from = new_from;
}
}
}
pub fn unpack(self) -> (i8, T) {
match self {
Self::Direct { from, data, .. } | Self::Broadcast { from, data, .. } => (from, data),
}
}
}
pub trait NetSend<T>: Sink<Msg<T>> {}
impl<T, U> NetSend<T> for U where U: Sink<Msg<T>> {}
pub trait NetRecv<T>: TryStream<Ok = Msg<T>> {}
impl<T, U> NetRecv<T> for U where U: TryStream<Ok = Msg<T>> {}
pub trait Net<T>: NetSend<T> + NetRecv<T> {
fn addr(&self) -> i8;
}
pub trait NetSendExt<T>: NetSend<T> {
fn send_to(&mut self, to: i8, msg: T) -> futures::sink::Send<Self, Msg<T>>
where
Self: Unpin,
{
self.send(Msg::direct(to, msg))
}
fn broadcast(&mut self, msg: T) -> futures::sink::Send<Self, Msg<T>>
where
Self: Unpin,
{
self.send(Msg::broadcast(msg))
}
fn poll_flush_unpin(
&mut self,
cx: &mut Context,
) -> Poll<Result<(), <Self as Sink<Msg<T>>>::Error>>
where
Self: Unpin,
{
Pin::new(self).poll_flush(cx)
}
fn poll_ready_unpin(
&mut self,
cx: &mut Context,
) -> Poll<Result<(), <Self as Sink<Msg<T>>>::Error>>
where
Self: Unpin,
{
Pin::new(self).poll_ready(cx)
}
}
pub trait NetRecvExt<T>: NetRecv<T> {}
impl<T, U> NetSendExt<T> for U where U: NetSend<T> {}
impl<T, U> NetRecvExt<T> for U where U: NetRecv<T> {}