fit-encoder 0.1.0

Write FIT activity files (the Flexible and Interoperable Data Transfer format) as a stream: file header first, CRC last, sizes known in advance. no_std, no allocation. Independent; not affiliated with Garmin
Documentation
//! The FIT CRC-16 of the "CRC" section of <https://developer.garmin.com/fit/protocol/>, which is
//! CRC-16/ARC.

const TABLE: [u16; 16] = [
    0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401,
    0x5000, 0x9C01, 0x8801, 0x4400,
];

/// A running FIT CRC-16.
///
/// ```
/// let mut crc = fit_encoder::Crc::new();
/// crc.update(b"123456789");
/// assert_eq!(crc.value(), 0xBB3D);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Crc(u16);

impl Crc {
    /// A CRC over no bytes.
    #[must_use]
    pub const fn new() -> Self {
        Self(0)
    }

    /// Takes `bytes` into the CRC.
    pub fn update(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            self.0 = nibble(nibble(self.0, byte & 0xF), byte >> 4);
        }
    }

    /// The CRC of the bytes so far.
    #[must_use]
    pub const fn value(self) -> u16 {
        self.0
    }

    /// The CRC of what this one covers followed by `len` bytes whose CRC is `next`.
    ///
    /// The CRC starts at zero and has no final step, so it is linear: this is `self` carried
    /// through `len` zero bytes, exclusive-ored with `next`.
    pub(crate) fn then(self, next: Self, len: u32) -> Self {
        let mut step = zero_byte();
        let mut crc = self.0;
        for bit in 0..u32::BITS {
            if len.wrapping_shr(bit) & 1 == 1 {
                crc = apply(&step, crc);
            }
            step = step.map(|column| apply(&step, column));
        }
        Self(crc ^ next.0)
    }
}

/// A linear map of CRC states: column `i` is where bit `i` goes.
type Matrix = [u16; 16];

fn apply(m: &Matrix, v: u16) -> u16 {
    (0..16u32)
        .zip(m)
        .filter(|&(i, _)| v.wrapping_shr(i) & 1 == 1)
        .fold(0, |acc, (_, column)| acc ^ column)
}

/// The map that one zero byte makes of the state.
fn zero_byte() -> Matrix {
    core::array::from_fn(|i| {
        let bit = 1u16.wrapping_shl(u32::try_from(i).unwrap_or(0));
        nibble(nibble(bit, 0), 0)
    })
}

fn nibble(crc: u16, nibble: u8) -> u16 {
    let entry = |i: u16| TABLE.get(usize::from(i & 0xF)).copied().unwrap_or(0);
    let tmp = entry(crc);
    let crc = (crc >> 4) & 0x0FFF;
    crc ^ tmp ^ entry(u16::from(nibble))
}

#[cfg(test)]
mod tests {
    use super::Crc;

    fn crc(bytes: &[u8]) -> u16 {
        let mut c = Crc::new();
        c.update(bytes);
        c.value()
    }

    #[test]
    fn then_joins_two_crcs() {
        let bytes: std::vec::Vec<u8> = (0..=255u8).cycle().take(1000).collect();
        for split in [0, 1, 2, 13, 14, 500, 999, 1000] {
            let (a, b) = bytes.split_at(split);
            let (mut ca, mut cb) = (Crc::new(), Crc::new());
            ca.update(a);
            cb.update(b);
            let len = u32::try_from(b.len()).unwrap();
            assert_eq!(ca.then(cb, len).value(), crc(&bytes), "split at {split}");
        }
    }

    #[test]
    fn known_vectors() {
        // CRC-16/ARC's check value, and other values of that algorithm.
        assert_eq!(crc(b""), 0x0000);
        assert_eq!(crc(b"123456789"), 0xBB3D);
        assert_eq!(crc(&[0x00]), 0x0000);
        assert_eq!(crc(&[0x01]), 0xC0C1);
        assert_eq!(crc(&[0xFF]), 0x4040);
        assert_eq!(crc(b"A"), 0x30C0);
    }

    #[test]
    fn a_file_ending_in_its_crc_checks_to_zero() {
        let mut bytes = b"any bytes at all".to_vec();
        let c = crc(&bytes);
        bytes.extend_from_slice(&c.to_le_bytes());
        assert_eq!(crc(&bytes), 0);
    }

    #[test]
    fn updates_compose() {
        let mut c = Crc::new();
        c.update(b"1234");
        c.update(b"56789");
        assert_eq!(c.value(), crc(b"123456789"));
    }
}