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
use parking_lot::RwLock;
use tokio::{
net::{
tcp::{OwnedReadHalf, OwnedWriteHalf},
TcpStream,
},
task::JoinHandle,
};
use std::{collections::HashMap, net::SocketAddr, ops::Not};
#[derive(Default)]
pub(crate) struct Connections(RwLock<HashMap<SocketAddr, Connection>>);
impl Connections {
pub(crate) fn add(&self, conn: Connection) {
self.0.write().insert(conn.addr, conn);
}
pub(crate) fn is_connected(&self, addr: SocketAddr) -> bool {
self.0.read().contains_key(&addr)
}
pub(crate) fn remove(&self, addr: SocketAddr) -> Option<Connection> {
self.0.write().remove(&addr)
}
pub(crate) fn num_connected(&self) -> usize {
self.0.read().len()
}
pub(crate) fn addrs(&self) -> Vec<SocketAddr> {
self.0.read().keys().copied().collect()
}
}
#[derive(Clone, Copy, Debug)]
pub enum ConnectionSide {
Initiator,
Responder,
}
impl Not for ConnectionSide {
type Output = Self;
fn not(self) -> Self::Output {
match self {
Self::Initiator => Self::Responder,
Self::Responder => Self::Initiator,
}
}
}
pub struct Connection {
pub addr: SocketAddr,
pub reader: Option<OwnedReadHalf>,
pub writer: Option<OwnedWriteHalf>,
pub tasks: Vec<JoinHandle<()>>,
pub side: ConnectionSide,
}
impl Connection {
pub(crate) fn new(addr: SocketAddr, stream: TcpStream, side: ConnectionSide) -> Self {
let (reader, writer) = stream.into_split();
Self {
addr,
reader: Some(reader),
writer: Some(writer),
side,
tasks: Default::default(),
}
}
pub fn reader(&mut self) -> &mut OwnedReadHalf {
self.reader
.as_mut()
.expect("Connection's reader is not available!")
}
pub fn writer(&mut self) -> &mut OwnedWriteHalf {
self.writer
.as_mut()
.expect("Connection's writer is not available!")
}
}