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
use super::*;
use std::num::NonZeroU8;
use tox_binary_io::*;
use nom::number::streaming::be_u8;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct ConnectionId(Option<NonZeroU8>);
impl ConnectionId {
pub fn zero() -> Self {
ConnectionId(None)
}
pub fn from_index(index: u8) -> Self {
assert!(index < MAX_LINKS_N, "The index {} must be lower than {}", index, MAX_LINKS_N);
ConnectionId(Some(NonZeroU8::new(index + 16).unwrap()))
}
pub fn index(self) -> Option<u8> {
self.0.map(|connection_id| connection_id.get() - 16)
}
}
impl FromBytes for ConnectionId {
named!(from_bytes<ConnectionId>, map!(verify!(be_u8, |id| *id == 0 || *id >= 0x10), |id| ConnectionId(NonZeroU8::new(id))));
}
impl ToBytes for ConnectionId {
fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
gen_be_u8!(buf, self.0.map_or(0, |connection_id| connection_id.get()))
}
}
#[cfg(test)]
mod test {
use super::*;
encode_decode_test!(
tox_crypto::crypto_init().unwrap(),
connection_id_encode_decode,
ConnectionId::from_index(42)
);
encode_decode_test!(
tox_crypto::crypto_init().unwrap(),
connection_id_0_encode_decode,
ConnectionId::zero()
);
#[test]
fn zero() {
let connection_id = ConnectionId::zero();
assert_eq!(connection_id.0, None);
}
#[test]
fn from_index() {
let connection_id = ConnectionId::from_index(0);
assert_eq!(connection_id.0.unwrap().get(), 16);
}
#[test]
#[should_panic]
fn from_index_invalid() {
let _connection_id = ConnectionId::from_index(255);
}
#[test]
fn index() {
let index = 42;
let connection_id = ConnectionId::from_index(index);
assert_eq!(connection_id.index().unwrap(), index);
}
#[test]
fn index_zero() {
let connection_id = ConnectionId::zero();
assert!(connection_id.index().is_none());
}
}