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
115
116
117
118
use super::util::encode_u32;
use core::convert::From;
use core::ops::Deref;
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, Ord, PartialOrd)]
pub struct MsgToken {
len: u8,
bytes: [u8; 8],
}
impl MsgToken {
pub const EMPTY: MsgToken = MsgToken {
len: 0u8,
bytes: [0; 8],
};
pub fn new(x: &[u8]) -> MsgToken {
MsgToken::from(x)
}
pub fn len(&self) -> usize {
self.len as usize
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len as usize]
}
}
impl std::fmt::Display for MsgToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for b in self.as_bytes() {
write!(f, "{:02X}", b)?;
}
Ok(())
}
}
impl Default for MsgToken {
fn default() -> Self {
MsgToken::EMPTY
}
}
impl Deref for MsgToken {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_bytes()
}
}
impl core::cmp::PartialEq<[u8]> for MsgToken {
fn eq(&self, other: &[u8]) -> bool {
self.as_bytes() == other
}
}
impl core::convert::From<u32> for MsgToken {
fn from(x: u32) -> Self {
let mut bytes = [0u8; 8];
let len = encode_u32(x, &mut bytes).len();
MsgToken {
len: len as u8,
bytes,
}
}
}
impl core::convert::From<i32> for MsgToken {
fn from(x: i32) -> Self {
core::convert::Into::into(x as u32)
}
}
impl core::convert::From<u16> for MsgToken {
fn from(x: u16) -> Self {
core::convert::Into::into(x as u32)
}
}
impl core::convert::From<&[u8]> for MsgToken {
fn from(x: &[u8]) -> Self {
let mut bytes = [0u8; 8];
let len = x.len();
bytes[..len].copy_from_slice(x);
MsgToken {
len: len as u8,
bytes,
}
}
}