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
|
use super::*;
use async_trait::async_trait;
use delegate::delegate;
use num_enum::TryFromPrimitive;
use std::{borrow::Cow, io, sync::Arc};
use tokio::sync::mpsc;
pub const PROTO_ID: u32 = 0x4f457403;
pub const UDP_PKT_SIZE: usize = 512;
pub const NUM_CHANS: usize = 3;
pub const REL_BUFFER: usize = 0x8000;
pub const INIT_SEQNUM: u16 = 65500;
pub const TIMEOUT: u64 = 30;
pub const PING_TIMEOUT: u64 = 5;
#[async_trait]
pub trait UdpSender: Send + Sync + 'static {
async fn send(&self, data: &[u8]) -> io::Result<()>;
}
#[async_trait]
pub trait UdpReceiver: Send + Sync + 'static {
async fn recv(&self) -> io::Result<Vec<u8>>;
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[repr(u16)]
pub enum PeerID {
Nil = 0,
Srv,
CltMin,
}
#[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
#[repr(u8)]
pub enum PktType {
Ctl = 0,
Orig,
Split,
Rel,
}
#[derive(Debug, Copy, Clone, PartialEq, TryFromPrimitive)]
#[repr(u8)]
pub enum CtlType {
Ack = 0,
SetPeerID,
Ping,
Disco,
}
#[derive(Debug)]
pub struct Pkt<'a> {
pub unrel: bool,
pub chan: u8,
pub data: Cow<'a, [u8]>,
}
pub type InPkt = Result<Pkt<'static>, Error>;
#[derive(Debug)]
pub struct RudpReceiver<S: UdpSender> {
pub(crate) share: Arc<RudpShare<S>>,
pub(crate) pkt_rx: mpsc::UnboundedReceiver<InPkt>,
}
#[derive(Debug)]
pub struct RudpSender<S: UdpSender> {
pub(crate) share: Arc<RudpShare<S>>,
}
// derive(Clone) adds unwanted Clone trait bound to S parameter
impl<S: UdpSender> Clone for RudpSender<S> {
fn clone(&self) -> Self {
Self {
share: Arc::clone(&self.share),
}
}
}
macro_rules! impl_share {
($T:ident) => {
impl<S: UdpSender> $T<S> {
pub async fn peer_id(&self) -> u16 {
self.share.id
}
pub async fn is_server(&self) -> bool {
self.share.id == PeerID::Srv as u16
}
pub async fn close(self) {
self.share.bomb.lock().await.defuse();
self.share.close_tx.send(true).ok();
let mut tasks = self.share.tasks.lock().await;
while let Some(res) = tasks.join_next().await {
res.ok(); // TODO: handle error (?)
}
}
}
};
}
impl_share!(RudpReceiver);
impl_share!(RudpSender);
impl<S: UdpSender> RudpReceiver<S> {
delegate! {
to self.pkt_rx {
pub async fn recv(&mut self) -> Option<InPkt>;
}
}
}
|