-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmessage.rs
More file actions
104 lines (87 loc) · 2.3 KB
/
message.rs
File metadata and controls
104 lines (87 loc) · 2.3 KB
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
use super::*;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Message {
pub fingerprint: Fingerprint,
pub timestamp: Option<u64>,
}
impl Message {
pub(crate) fn digest(&self) -> Hash {
Hash::bytes(&self.encode_to_vec())
}
}
#[cfg(test)]
impl Decode for Message {
fn decode(decoder: &mut Decoder) -> Result<Self, DecodeError> {
let mut map = decoder.map::<u8>()?;
let application = map.key::<String>(0)?.unwrap();
ensure!(
application == "filepack",
cbor::decode_error::UnexpectedValue
);
let ty = map.key::<String>(1)?.unwrap();
ensure!(ty == "message", cbor::decode_error::UnexpectedValue);
let fingerprint = map.key::<Fingerprint>(2)?.unwrap();
let timestamp = map.key::<u64>(3)?;
map.finish()?;
Ok(Self {
fingerprint,
timestamp,
})
}
}
impl Encode for Message {
fn encode(&self, encoder: &mut Encoder) {
let length = 3 + count_some!(self.timestamp);
let mut map = encoder.map::<u8>(length);
map.item(0, "filepack");
map.item(1, "message");
map.item(2, self.fingerprint);
map.optional_item(3, self.timestamp);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encoding_with_timestamp() {
assert_encoding(Message {
fingerprint: Fingerprint::from_bytes([0; Fingerprint::LEN]),
timestamp: Some(1000),
});
}
#[test]
fn encoding_without_timestamp() {
assert_encoding(Message {
fingerprint: Fingerprint::from_bytes([0; Fingerprint::LEN]),
timestamp: None,
});
}
#[test]
fn wrong_application() {
let mut encoder = Encoder::new();
let mut map = encoder.map::<u8>(3);
map.item(0, "foo");
map.item(1, "message");
map.item(2, Fingerprint::from_bytes([0; Fingerprint::LEN]));
drop(map);
let bytes = encoder.finish();
assert_eq!(
Message::decode(&mut Decoder::new(bytes)),
Err(DecodeError::UnexpectedValue),
);
}
#[test]
fn wrong_type() {
let mut encoder = Encoder::new();
let mut map = encoder.map::<u8>(3);
map.item(0, "filepack");
map.item(1, "foo");
map.item(2, Fingerprint::from_bytes([0; Fingerprint::LEN]));
drop(map);
let bytes = encoder.finish();
assert_eq!(
Message::decode(&mut Decoder::new(bytes)),
Err(DecodeError::UnexpectedValue),
);
}
}