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
use std::time::duration::Duration;
use std::u16;
pub struct ConnectionConfig<T> {
pub protocol_id: u32,
pub timeout_period: Duration,
pub packet_deserializer: fn(&Vec<u8>) -> Option<T>,
pub packet_serializer: fn(&T) -> Vec<u8>
}
impl <T> ConnectionConfig <T> {
pub fn new(protocol_id: u32, timeout_period: Duration, packet_deserializer: fn(&Vec<u8>) -> Option<T>, packet_serializer: fn(&T) -> Vec<u8>) -> ConnectionConfig<T> {
ConnectionConfig {
protocol_id: protocol_id,
timeout_period: timeout_period,
packet_deserializer: packet_deserializer,
packet_serializer: packet_serializer
}
}
}
#[derive(Clone)]
pub struct SequenceManager {
pub last_sent_sequence_id: u16,
pub last_received_sequence_id: u16
}
impl SequenceManager {
pub fn new() -> SequenceManager {
SequenceManager {
last_sent_sequence_id: 0,
last_received_sequence_id: 0
}
}
pub fn next_sequence_id(&mut self) -> u16 {
self.last_sent_sequence_id += 1;
self.last_sent_sequence_id
}
pub fn packet_is_newer(&self, sequence_id: u16) -> bool {
let max = u16::MAX;
return (sequence_id > self.last_received_sequence_id) && (sequence_id - self.last_received_sequence_id <= max/2) ||
(self.last_received_sequence_id > sequence_id) && (self.last_received_sequence_id - sequence_id > max/2);
}
pub fn set_newest_packet(&mut self, sequence_id: u16) {
self.last_received_sequence_id = sequence_id;
}
}