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
use super::super::types::ChecksumType;
use super::super::Packet;
impl Packet {
/// Checks if the calculated checksum of the packet
/// matches to the already stored one.
pub fn is_checksum_correct(&self) -> bool {
self.calculate_packet_sum() == self.checksum
}
/// Calculates and returns checksum of whole packet.
///
/// Checksum consist of next fields:
/// source_device_identifier
/// destination_device_identifier
/// flags
/// data_length
/// data
fn calculate_packet_sum(&self) -> ChecksumType {
let mut result: ChecksumType = 0;
// Calculate source_device_identifier
for byte in self.source_device_identifier.to_be_bytes() {
(result, _) = result.overflowing_add(byte);
}
// Calculate destination_device_identifier
for byte in self.destination_device_identifier.to_be_bytes() {
(result, _) = result.overflowing_add(byte);
}
// Calculate id
for byte in self.id.to_be_bytes() {
(result, _) = result.overflowing_add(byte);
}
// Calculate lifetime
for byte in self.lifetime.to_be_bytes() {
(result, _) = result.overflowing_add(byte);
}
// Calculate flags
for byte in self.flags.to_be_bytes() {
(result, _) = result.overflowing_add(byte);
}
// Calculate data_length
for byte in self.data_length.to_be_bytes() {
(result, _) = result.overflowing_add(byte);
}
// Calculate data
for byte in self.data.iter() {
(result, _) = result.overflowing_add(*byte);
}
result
}
/// Calculates checksum for this packet, and sets
/// calculated value into .checksum field. returns
/// new summarized packet.
pub fn summarized(mut self) -> Packet {
self.checksum = self.calculate_packet_sum();
self
}
}