Skip to main content

fit_encoder/
crc.rs

1//! The FIT CRC-16 of the "CRC" section of <https://developer.garmin.com/fit/protocol/>, which is
2//! CRC-16/ARC.
3
4const TABLE: [u16; 16] = [
5    0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401,
6    0x5000, 0x9C01, 0x8801, 0x4400,
7];
8
9/// A running FIT CRC-16.
10///
11/// ```
12/// let mut crc = fit_encoder::Crc::new();
13/// crc.update(b"123456789");
14/// assert_eq!(crc.value(), 0xBB3D);
15/// ```
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub struct Crc(u16);
18
19impl Crc {
20    /// A CRC over no bytes.
21    #[must_use]
22    pub const fn new() -> Self {
23        Self(0)
24    }
25
26    /// Takes `bytes` into the CRC.
27    pub fn update(&mut self, bytes: &[u8]) {
28        for &byte in bytes {
29            self.0 = nibble(nibble(self.0, byte & 0xF), byte >> 4);
30        }
31    }
32
33    /// The CRC of the bytes so far.
34    #[must_use]
35    pub const fn value(self) -> u16 {
36        self.0
37    }
38
39    /// The CRC of what this one covers followed by `len` bytes whose CRC is `next`.
40    ///
41    /// The CRC starts at zero and has no final step, so it is linear: this is `self` carried
42    /// through `len` zero bytes, exclusive-ored with `next`.
43    pub(crate) fn then(self, next: Self, len: u32) -> Self {
44        let mut step = zero_byte();
45        let mut crc = self.0;
46        for bit in 0..u32::BITS {
47            if len.wrapping_shr(bit) & 1 == 1 {
48                crc = apply(&step, crc);
49            }
50            step = step.map(|column| apply(&step, column));
51        }
52        Self(crc ^ next.0)
53    }
54}
55
56/// A linear map of CRC states: column `i` is where bit `i` goes.
57type Matrix = [u16; 16];
58
59fn apply(m: &Matrix, v: u16) -> u16 {
60    (0..16u32)
61        .zip(m)
62        .filter(|&(i, _)| v.wrapping_shr(i) & 1 == 1)
63        .fold(0, |acc, (_, column)| acc ^ column)
64}
65
66/// The map that one zero byte makes of the state.
67fn zero_byte() -> Matrix {
68    core::array::from_fn(|i| {
69        let bit = 1u16.wrapping_shl(u32::try_from(i).unwrap_or(0));
70        nibble(nibble(bit, 0), 0)
71    })
72}
73
74fn nibble(crc: u16, nibble: u8) -> u16 {
75    let entry = |i: u16| TABLE.get(usize::from(i & 0xF)).copied().unwrap_or(0);
76    let tmp = entry(crc);
77    let crc = (crc >> 4) & 0x0FFF;
78    crc ^ tmp ^ entry(u16::from(nibble))
79}
80
81#[cfg(test)]
82mod tests {
83    use super::Crc;
84
85    fn crc(bytes: &[u8]) -> u16 {
86        let mut c = Crc::new();
87        c.update(bytes);
88        c.value()
89    }
90
91    #[test]
92    fn then_joins_two_crcs() {
93        let bytes: std::vec::Vec<u8> = (0..=255u8).cycle().take(1000).collect();
94        for split in [0, 1, 2, 13, 14, 500, 999, 1000] {
95            let (a, b) = bytes.split_at(split);
96            let (mut ca, mut cb) = (Crc::new(), Crc::new());
97            ca.update(a);
98            cb.update(b);
99            let len = u32::try_from(b.len()).unwrap();
100            assert_eq!(ca.then(cb, len).value(), crc(&bytes), "split at {split}");
101        }
102    }
103
104    #[test]
105    fn known_vectors() {
106        // CRC-16/ARC's check value, and other values of that algorithm.
107        assert_eq!(crc(b""), 0x0000);
108        assert_eq!(crc(b"123456789"), 0xBB3D);
109        assert_eq!(crc(&[0x00]), 0x0000);
110        assert_eq!(crc(&[0x01]), 0xC0C1);
111        assert_eq!(crc(&[0xFF]), 0x4040);
112        assert_eq!(crc(b"A"), 0x30C0);
113    }
114
115    #[test]
116    fn a_file_ending_in_its_crc_checks_to_zero() {
117        let mut bytes = b"any bytes at all".to_vec();
118        let c = crc(&bytes);
119        bytes.extend_from_slice(&c.to_le_bytes());
120        assert_eq!(crc(&bytes), 0);
121    }
122
123    #[test]
124    fn updates_compose() {
125        let mut c = Crc::new();
126        c.update(b"1234");
127        c.update(b"56789");
128        assert_eq!(c.value(), crc(b"123456789"));
129    }
130}