aboutsummaryrefslogtreecommitdiff
path: root/src/common.rs
blob: 9d99cb9e7b689780b6e411256d48ed025b0ca1b6 (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
use async_trait::async_trait;
use num_enum::TryFromPrimitive;
use std::{borrow::Cow, fmt::Debug, io};

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 {
    async fn send(&self, data: &[u8]) -> io::Result<()>;
}

#[async_trait]
pub trait UdpReceiver: Send {
    async fn recv(&mut 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]>,
}

impl<'a> Pkt<'a> {
    pub fn size(&self) -> usize {
        self.header_size() + self.body_size()
    }

    pub fn body_size(&self) -> usize {
        self.data.len()
    }

    pub fn header_size(&self) -> usize {
        4 + 2 + 1 + if self.unrel { 0 } else { 1 + 2 } + 1
    }
}