Skip to main content

divecomputer_core/
checksum.rs

1//! Checksums and CRCs used by dive computer protocols.
2//!
3//! Each algorithm is defined once, named after its entry in the
4//! [checksum catalogue](https://michidk.github.io/divecomputer-rs/spec/common/checksums.html).
5//! CRCs are [`crc::Crc`] instances, so callers get both one-shot
6//! ([`Crc::checksum`]) and incremental ([`Crc::digest`]) computation. The simple sums are
7//! small digest types with the same `update`/`value` shape.
8//!
9//! ```
10//! use divecomputer_core::checksum::{CRC_16_XMODEM, Sum8, Xor8};
11//!
12//! // Cressi Goa dive request: CRC over length, command and arguments.
13//! assert_eq!(CRC_16_XMODEM.checksum(&[0x02, 0x22, 0x01, 0x00]), 0x36FF);
14//!
15//! // Suunto version query: XOR over the command bytes.
16//! assert_eq!(Xor8::of(&[0x05, 0x00, 0x16, 0x14]).value(), 0x07);
17//!
18//! // Sum of data plus its negated sum8 is zero.
19//! let data = [0x10, 0x20, 0x30];
20//! assert_eq!(Sum8::of(&data).negated(), 0xA0);
21//! ```
22
23pub use crc::Crc;
24
25/// CRC-8/SMBUS: polynomial `07`, init `00`, no reflection, no final XOR.
26pub const CRC_8_SMBUS: Crc<u8> = Crc::<u8>::new(&crc::CRC_8_SMBUS);
27
28/// Parameters of [`CRC_8_MSB_0X12`].
29///
30/// Not in the RevEng catalogue: the polynomial `12` has no `x^0` term.
31const CRC_8_MSB_0X12_ALGORITHM: crc::Algorithm<u8> = crc::Algorithm {
32    width: 8,
33    poly: 0x12,
34    init: 0x00,
35    refin: false,
36    refout: false,
37    xorout: 0x00,
38    check: 0xEA,
39    residue: 0x00,
40};
41
42/// CRC-8 with polynomial `12`, init `00`, no reflection, no final XOR.
43///
44/// Used by the Pelagic i330R / Apeks DSX BLE packets.
45pub const CRC_8_MSB_0X12: Crc<u8> = Crc::<u8>::new(&CRC_8_MSB_0X12_ALGORITHM);
46
47/// CRC-16/IBM-3740, also known as CRC-16/CCITT-FALSE: polynomial `1021`, init `FFFF`.
48pub const CRC_16_IBM_3740: Crc<u16> = Crc::<u16>::new(&crc::CRC_16_IBM_3740);
49
50/// CRC-16/XMODEM: polynomial `1021`, init `0000`.
51pub const CRC_16_XMODEM: Crc<u16> = Crc::<u16>::new(&crc::CRC_16_XMODEM);
52
53/// CRC-16/IBM-SDLC, also known as CRC-16/X-25: polynomial `1021`, reflected, init and
54/// final XOR `FFFF`.
55pub const CRC_16_IBM_SDLC: Crc<u16> = Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
56
57/// CRC-16/ARC: polynomial `8005`, reflected, init `0000`.
58pub const CRC_16_ARC: Crc<u16> = Crc::<u16>::new(&crc::CRC_16_ARC);
59
60/// CRC-16/MODBUS: polynomial `8005`, reflected, init `FFFF`.
61pub const CRC_16_MODBUS: Crc<u16> = Crc::<u16>::new(&crc::CRC_16_MODBUS);
62
63/// CRC-32/ISO-HDLC, the common "CRC-32": polynomial `04C11DB7`, reflected.
64pub const CRC_32_ISO_HDLC: Crc<u32> = Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
65
66/// CRC-32/BZIP2: polynomial `04C11DB7`, not reflected.
67pub const CRC_32_BZIP2: Crc<u32> = Crc::<u32>::new(&crc::CRC_32_BZIP2);
68
69/// Sum of bytes modulo 256.
70///
71/// Covers the catalogue entries `sum8`, `sum8-neg` ([`negated`](Self::negated)) and
72/// `sum8-inv` ([`inverted`](Self::inverted)). Some families seed the sum; use
73/// [`with_init`](Self::with_init) for those.
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
75pub struct Sum8(u8);
76
77impl Sum8 {
78    /// Creates a sum starting at zero.
79    #[must_use]
80    pub const fn new() -> Self {
81        Self(0)
82    }
83
84    /// Creates a sum starting at `init`.
85    #[must_use]
86    pub const fn with_init(init: u8) -> Self {
87        Self(init)
88    }
89
90    /// Computes the sum of `data`, starting at zero.
91    #[must_use]
92    pub fn of(data: &[u8]) -> Self {
93        let mut sum = Self::new();
94        sum.update(data);
95        sum
96    }
97
98    /// Adds `data` to the sum.
99    pub fn update(&mut self, data: &[u8]) {
100        self.0 = data.iter().fold(self.0, |acc, &b| acc.wrapping_add(b));
101    }
102
103    /// The sum modulo 256.
104    #[must_use]
105    pub const fn value(self) -> u8 {
106        self.0
107    }
108
109    /// The two's complement of the sum, so that data plus this byte sums to zero.
110    #[must_use]
111    pub const fn negated(self) -> u8 {
112        self.0.wrapping_neg()
113    }
114
115    /// The ones' complement of the sum.
116    #[must_use]
117    pub const fn inverted(self) -> u8 {
118        !self.0
119    }
120}
121
122/// Sum of bytes (each `0..=255`) modulo 65536: the catalogue entry `sum16`.
123#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
124pub struct Sum16(u16);
125
126impl Sum16 {
127    /// Creates a sum starting at zero.
128    #[must_use]
129    pub const fn new() -> Self {
130        Self(0)
131    }
132
133    /// Creates a sum starting at `init`.
134    #[must_use]
135    pub const fn with_init(init: u16) -> Self {
136        Self(init)
137    }
138
139    /// Computes the sum of `data`, starting at zero.
140    #[must_use]
141    pub fn of(data: &[u8]) -> Self {
142        let mut sum = Self::new();
143        sum.update(data);
144        sum
145    }
146
147    /// Adds `data` to the sum.
148    pub fn update(&mut self, data: &[u8]) {
149        self.0 = data
150            .iter()
151            .fold(self.0, |acc, &b| acc.wrapping_add(u16::from(b)));
152    }
153
154    /// The sum modulo 65536.
155    #[must_use]
156    pub const fn value(self) -> u16 {
157        self.0
158    }
159}
160
161/// Sum of the high and low nibble of every byte, modulo 256: the catalogue entry
162/// `nibble-sum`.
163#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
164pub struct NibbleSum(u8);
165
166impl NibbleSum {
167    /// Creates a sum starting at zero.
168    #[must_use]
169    pub const fn new() -> Self {
170        Self(0)
171    }
172
173    /// Computes the nibble sum of `data`, starting at zero.
174    #[must_use]
175    pub fn of(data: &[u8]) -> Self {
176        let mut sum = Self::new();
177        sum.update(data);
178        sum
179    }
180
181    /// Adds the nibbles of `data` to the sum.
182    pub fn update(&mut self, data: &[u8]) {
183        self.0 = data.iter().fold(self.0, |acc, &b| {
184            acc.wrapping_add(b >> 4).wrapping_add(b & 0x0F)
185        });
186    }
187
188    /// The sum modulo 256.
189    #[must_use]
190    pub const fn value(self) -> u8 {
191        self.0
192    }
193}
194
195/// XOR of all bytes: the catalogue entry `xor8`.
196#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
197pub struct Xor8(u8);
198
199impl Xor8 {
200    /// Creates an XOR starting at zero.
201    #[must_use]
202    pub const fn new() -> Self {
203        Self(0)
204    }
205
206    /// Computes the XOR of `data`, starting at zero.
207    #[must_use]
208    pub fn of(data: &[u8]) -> Self {
209        let mut xor = Self::new();
210        xor.update(data);
211        xor
212    }
213
214    /// XORs `data` into the value.
215    pub fn update(&mut self, data: &[u8]) {
216        self.0 = data.iter().fold(self.0, |acc, &b| acc ^ b);
217    }
218
219    /// The XOR of all bytes.
220    #[must_use]
221    pub const fn value(self) -> u8 {
222        self.0
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    /// The standard check input used by the catalogue.
231    const CHECK_INPUT: &[u8] = b"123456789";
232
233    #[test]
234    fn crc_check_values_match_catalogue() {
235        assert_eq!(CRC_8_SMBUS.checksum(CHECK_INPUT), 0xF4);
236        assert_eq!(CRC_8_MSB_0X12.checksum(CHECK_INPUT), 0xEA);
237        assert_eq!(CRC_16_IBM_3740.checksum(CHECK_INPUT), 0x29B1);
238        assert_eq!(CRC_16_XMODEM.checksum(CHECK_INPUT), 0x31C3);
239        assert_eq!(CRC_16_IBM_SDLC.checksum(CHECK_INPUT), 0x906E);
240        assert_eq!(CRC_16_ARC.checksum(CHECK_INPUT), 0xBB3D);
241        assert_eq!(CRC_16_MODBUS.checksum(CHECK_INPUT), 0x4B37);
242        assert_eq!(CRC_32_ISO_HDLC.checksum(CHECK_INPUT), 0xCBF4_3926);
243        assert_eq!(CRC_32_BZIP2.checksum(CHECK_INPUT), 0xFC89_1918);
244    }
245
246    /// The byte-wise formulation given in the catalogue for `crc-8-msb-0x12`.
247    fn crc_8_msb_0x12_bytewise(data: &[u8]) -> u8 {
248        data.iter().fold(0u8, |crc, &b| {
249            let a = crc ^ b;
250            let t = a ^ (a >> 4) ^ (a >> 7);
251            (t << 4) ^ (t << 1)
252        })
253    }
254
255    #[test]
256    fn crc_8_msb_0x12_matches_bytewise_formulation() {
257        let mut data = [0u8; 64];
258        for (i, byte) in (0u8..).zip(data.iter_mut()) {
259            *byte = i.wrapping_mul(37).wrapping_add(11);
260        }
261        for len in 0..=data.len() {
262            let slice = data.get(..len).unwrap_or_default();
263            assert_eq!(
264                CRC_8_MSB_0X12.checksum(slice),
265                crc_8_msb_0x12_bytewise(slice)
266            );
267        }
268    }
269
270    #[test]
271    fn sum_check_values_match_catalogue() {
272        let sum8 = Sum8::of(CHECK_INPUT);
273        assert_eq!(sum8.value(), 0xDD);
274        assert_eq!(sum8.negated(), 0x23);
275        assert_eq!(sum8.inverted(), 0x22);
276        assert_eq!(Sum16::of(CHECK_INPUT).value(), 0x01DD);
277        assert_eq!(NibbleSum::of(CHECK_INPUT).value(), 0x48);
278        assert_eq!(Xor8::of(CHECK_INPUT).value(), 0x31);
279    }
280
281    #[test]
282    fn worked_examples_match_spec() {
283        // Mares ASCII read command: sum of the characters "51000120".
284        assert_eq!(Sum8::of(b"51000120").value(), 0x89);
285        // Cressi Goa dive request for dive id 1.
286        assert_eq!(CRC_16_XMODEM.checksum(&[0x02, 0x22, 0x01, 0x00]), 0x36FF);
287        // Suunto version query.
288        assert_eq!(Xor8::of(&[0x05, 0x00, 0x16, 0x14]).value(), 0x07);
289    }
290
291    #[test]
292    fn incremental_updates_equal_one_shot() {
293        let (head, tail) = CHECK_INPUT.split_at(4);
294        let mut sum = Sum8::new();
295        sum.update(head);
296        sum.update(tail);
297        assert_eq!(sum, Sum8::of(CHECK_INPUT));
298
299        let mut digest = CRC_16_IBM_3740.digest();
300        digest.update(head);
301        digest.update(tail);
302        assert_eq!(digest.finalize(), CRC_16_IBM_3740.checksum(CHECK_INPUT));
303    }
304
305    #[test]
306    fn seeded_sums_start_at_init() {
307        assert_eq!(Sum8::with_init(0xFF).value(), 0xFF);
308        assert_eq!(Sum8::with_init(0x01).negated(), 0xFF);
309        assert_eq!(Sum16::with_init(0xFFFF).value(), 0xFFFF);
310        let mut sum = Sum16::with_init(0xFFFF);
311        sum.update(&[0x02]);
312        assert_eq!(sum.value(), 0x0001);
313    }
314}