-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
107 lines (92 loc) · 2.06 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
mod sim_context;
mod sim_link;
pub use self::sim_context::SimContext;
pub(crate) use self::sim_link::{link, SimDownLink, SimUpLink};
use anyhow::Result;
use netsim_core::BusSender;
pub(crate) use netsim_core::Msg;
pub use netsim_core::{
Bandwidth, Edge, EdgePolicy, HasBytesSize, Latency, NodePolicy, PacketLoss, SimConfiguration,
SimId,
};
pub struct SimSocket<T>
where
T: HasBytesSize,
{
reader: SimSocketReadHalf<T>,
writer: SimSocketWriteHalf<T>,
}
pub struct SimSocketReadHalf<T> {
id: SimId,
down: SimDownLink<T>,
}
pub struct SimSocketWriteHalf<T>
where
T: HasBytesSize,
{
id: SimId,
up: BusSender<SimUpLink<T>>,
}
impl<T> SimSocket<T>
where
T: HasBytesSize,
{
pub(crate) fn new(
id: SimId,
to_bus: BusSender<SimUpLink<T>>,
receiver: SimDownLink<T>,
) -> Self {
let reader = SimSocketReadHalf { id, down: receiver };
let writer = SimSocketWriteHalf { id, up: to_bus };
Self { reader, writer }
}
pub fn id(&self) -> SimId {
self.reader.id()
}
pub fn into_split(self) -> (SimSocketReadHalf<T>, SimSocketWriteHalf<T>) {
let Self { reader, writer } = self;
(reader, writer)
}
}
impl<T> SimSocket<T>
where
T: HasBytesSize,
{
pub fn send_to(&self, to: SimId, msg: T) -> Result<()> {
self.writer.send_to(to, msg)
}
pub async fn recv(&mut self) -> Option<(SimId, T)> {
self.reader.recv().await
}
}
impl<T> SimSocketWriteHalf<T>
where
T: HasBytesSize,
{
pub fn id(&self) -> SimId {
self.id
}
}
impl<T> SimSocketWriteHalf<T>
where
T: HasBytesSize,
{
pub fn send_to(&self, to: SimId, msg: T) -> Result<()> {
let msg = Msg::new(self.id, to, msg);
self.up.send_msg(msg)
}
}
impl<T> SimSocketReadHalf<T> {
pub fn id(&self) -> SimId {
self.id
}
}
impl<T> SimSocketReadHalf<T>
where
T: HasBytesSize,
{
pub async fn recv(&mut self) -> Option<(SimId, T)> {
let msg = self.down.recv().await?;
Some((msg.from(), msg.into_content()))
}
}