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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use byteorder::{BigEndian, ByteOrder};
use cannyls::lump::LumpId;
use raftlog::log::LogIndex;
use raftlog::node::NodeId as RaftNodeId;
use raftlog::{Error, ErrorKind, Result};
use std::fmt;
use std::net::SocketAddr;
use std::ops::Range;
use std::str::FromStr;
use std::u32;
use trackable::error::ErrorKindExt;
const LUMP_TYPE_BALLOT: u8 = 0;
const LUMP_TYPE_LOG_ENTRY: u8 = 1;
const LUMP_TYPE_LOG_PREFIX_INDEX: u8 = 2;
const LUMP_TYPE_LOG_PREFIX: u8 = 3;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct LocalNodeId(#[serde(with = "hex_node_id")] [u8; 7]);
impl LocalNodeId {
pub fn new(id: [u8; 7]) -> Self {
LocalNodeId(id)
}
pub fn as_slice(&self) -> &[u8] {
&self.0[..]
}
pub fn to_ballot_lump_id(self) -> LumpId {
let mut id = [0; 16];
(&mut id[0..7]).copy_from_slice(&self.0[..]);
id[7] = LUMP_TYPE_BALLOT;
LumpId::new(BigEndian::read_u128(&id[..]))
}
pub fn to_log_entry_lump_id(self, index: LogIndex) -> LumpId {
let mut id = [0; 16];
(&mut id[0..7]).copy_from_slice(&self.0[..]);
id[7] = LUMP_TYPE_LOG_ENTRY;
BigEndian::write_u64(&mut id[8..], index.as_u64());
LumpId::new(BigEndian::read_u128(&id[..]))
}
pub fn to_log_prefix_index_lump_id(self) -> LumpId {
let mut id = [0; 16];
(&mut id[0..7]).copy_from_slice(&self.0[..]);
id[7] = LUMP_TYPE_LOG_PREFIX_INDEX;
LumpId::new(BigEndian::read_u128(&id[..]))
}
pub fn to_log_prefix_lump_id(self, index: u64) -> LumpId {
let mut id = [0; 16];
(&mut id[0..7]).copy_from_slice(&self.0[..]);
id[7] = LUMP_TYPE_LOG_PREFIX;
BigEndian::write_u64(&mut id[8..], index);
LumpId::new(BigEndian::read_u128(&id[..]))
}
pub fn to_available_lump_id_range(self) -> Range<LumpId> {
let mut id = [0; 16];
(&mut id[0..7]).copy_from_slice(&self.0[..]);
let start = LumpId::new(BigEndian::read_u128(&id[..]));
let local_id_and_type = BigEndian::read_u64(&id[0..8]);
BigEndian::write_u64(&mut id[0..8], local_id_and_type + (0x01 << 8));
let end = LumpId::new(BigEndian::read_u128(&id[..]));
Range { start, end }
}
}
impl fmt::Debug for LocalNodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LocalNodeId({:?})", hex_node_id::to_hex_string(self.0))
}
}
impl fmt::Display for LocalNodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex_node_id::to_hex_string(self.0))
}
}
impl FromStr for LocalNodeId {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
track!(hex_node_id::from_hex_str(s).map(LocalNodeId))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeId {
pub local_id: LocalNodeId,
pub instance: u32,
pub addr: SocketAddr,
}
impl NodeId {
pub fn to_raft_node_id(&self) -> RaftNodeId {
RaftNodeId::new(self.to_string())
}
pub fn from_raft_node_id(id: &RaftNodeId) -> Result<Self> {
id.as_str().parse()
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{:x}@{}", self.local_id, self.instance, self.addr)
}
}
impl FromStr for NodeId {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let mut tokens = s.splitn(2, '.');
let local_id = track_assert_some!(tokens.next(), ErrorKind::InvalidInput, "{:?}", s);
let mut tokens =
track_assert_some!(tokens.next(), ErrorKind::InvalidInput, "{:?}", s).splitn(2, '@');
let instance = track_assert_some!(tokens.next(), ErrorKind::InvalidInput, "{:?}", s);
let addr = track_assert_some!(tokens.next(), ErrorKind::InvalidInput, "{:?}", s);
let local_id = track!(local_id.parse())?;
let instance = track!(
u32::from_str_radix(instance, 16).map_err(|e| ErrorKind::InvalidInput.cause(e))
)?;
let addr = track!(addr.parse().map_err(|e| ErrorKind::InvalidInput.cause(e)))?;
Ok(NodeId {
local_id,
instance,
addr,
})
}
}
mod hex_node_id {
use byteorder::{BigEndian, ByteOrder};
use raftlog::{Error, ErrorKind};
use serde::de;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::u64;
use trackable::error::ErrorKindExt;
const NODE_ID_SIZE: usize = 7;
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn serialize<S>(value: &[u8; NODE_ID_SIZE], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let hex = to_hex_string(*value);
hex.serialize(serializer)
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; NODE_ID_SIZE], D::Error>
where
D: Deserializer<'de>,
{
let hex = String::deserialize(deserializer)?;
from_hex_str(&hex).map_err(de::Error::custom)
}
pub fn to_hex_string(id: [u8; NODE_ID_SIZE]) -> String {
let n = BigEndian::read_uint(&id[..], 7);
format!("{:x}", n)
}
pub fn from_hex_str(hex: &str) -> Result<[u8; NODE_ID_SIZE], Error> {
let n = track!(u64::from_str_radix(hex, 16).map_err(|e| ErrorKind::InvalidInput.cause(e)))?;
let mut id = [0; NODE_ID_SIZE];
BigEndian::write_uint(&mut id[..], n, 7);
Ok(id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn node_conv() {
let n = NodeId {
local_id: "123abc".parse().unwrap(),
instance: 4,
addr: "127.0.0.1:80".parse().unwrap(),
};
assert_eq!(n.to_string(), "123abc.4@127.0.0.1:80");
assert_eq!("123abc.4@127.0.0.1:80".parse::<NodeId>().unwrap(), n);
}
}