rtcm3 0.1.0

no_std, no_alloc parser and encoder for RTCM3 GNSS RTK correction messages
Documentation
//! Raw RTCM3 frame parsing and encoding.
//!
//! A frame is variable-length (0-1023 byte payload), so [`Frame`] borrows
//! its bytes from the caller rather than owning a fixed-size array.
//! Unlike a per-message checksum scheme, RTCM3's CRC-24Q covers the whole
//! frame with no per-message secret byte, so [`Frame::parse`] verifies it
//! directly - there's no deferred checksum step.

use crate::crc;
use crate::error::FrameError;

const PREAMBLE: u8 = 0xD3;
const HEADER_LEN: usize = 3;
const CRC_LEN: usize = 3;

/// Largest possible frame: 3-byte header + 1023-byte payload + 3-byte CRC.
pub const MAX_FRAME_LEN: usize = HEADER_LEN + 1023 + CRC_LEN;

/// A parsed, CRC-validated RTCM3 frame, borrowed from the caller's buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frame<'a> {
    payload: &'a [u8],
}

impl<'a> Frame<'a> {
    /// Parses and CRC-validates a single frame from the start of `buf`.
    /// `buf` may contain trailing bytes after the frame (e.g. the start of
    /// the next frame in a stream) - only the leading frame is parsed.
    ///
    /// # Errors
    /// Returns a [`FrameError`] if `buf` is shorter than the frame its own
    /// header declares, the first byte isn't `0xD3`, the reserved bits
    /// before the length field are set, or the CRC-24Q doesn't match.
    pub fn parse(buf: &'a [u8]) -> Result<Self, FrameError> {
        if buf.len() < HEADER_LEN {
            return Err(FrameError::TooShort {
                needed: HEADER_LEN,
                got: buf.len(),
            });
        }
        if buf[0] != PREAMBLE {
            return Err(FrameError::UnknownPreamble(buf[0]));
        }
        if buf[1] & 0xFC != 0 {
            return Err(FrameError::ReservedBitsSet);
        }
        let length = (usize::from(buf[1] & 0x03) << 8) | usize::from(buf[2]);
        let needed = HEADER_LEN + length + CRC_LEN;
        if buf.len() < needed {
            return Err(FrameError::TooShort {
                needed,
                got: buf.len(),
            });
        }

        let body = &buf[..HEADER_LEN + length];
        let crc_bytes = &buf[HEADER_LEN + length..needed];
        let expected = (u32::from(crc_bytes[0]) << 16)
            | (u32::from(crc_bytes[1]) << 8)
            | u32::from(crc_bytes[2]);
        if crc::checksum(body) != expected {
            return Err(FrameError::ChecksumMismatch);
        }

        Ok(Self {
            payload: &buf[HEADER_LEN..HEADER_LEN + length],
        })
    }

    /// The message payload (everything after the 3-byte header, before the
    /// 3-byte CRC).
    #[must_use]
    pub const fn payload(&self) -> &'a [u8] {
        self.payload
    }

    /// This frame's total length in bytes (header + payload + CRC), i.e.
    /// how far to advance past it in a byte stream containing more than
    /// one frame. Never `0` (a parsed frame is always at least 6 bytes),
    /// so there's no `is_empty` counterpart.
    #[must_use]
    pub const fn byte_len(&self) -> usize {
        HEADER_LEN + self.payload.len() + CRC_LEN
    }
}

/// Encodes a frame around `payload` into `buf`, returning the number of
/// bytes written.
///
/// # Errors
/// Returns a [`FrameError`] if `payload` is longer than 1023 bytes (the
/// largest length RTCM3's 10-bit length field can represent) or `buf` is
/// too small to hold the encoded frame (size it with [`MAX_FRAME_LEN`] to
/// always be safe).
pub fn encode(buf: &mut [u8], payload: &[u8]) -> Result<usize, FrameError> {
    if payload.len() > 1023 {
        return Err(FrameError::PayloadTooLong {
            max: 1023,
            got: payload.len(),
        });
    }
    let total = HEADER_LEN + payload.len() + CRC_LEN;
    if buf.len() < total {
        return Err(FrameError::TooShort {
            needed: total,
            got: buf.len(),
        });
    }

    buf[0] = PREAMBLE;
    #[allow(
        clippy::cast_possible_truncation,
        reason = "payload.len() <= 1023, checked above, so this fits in the 10-bit length field split across these two bytes"
    )]
    {
        buf[1] = (payload.len() >> 8) as u8;
        buf[2] = payload.len() as u8;
    }
    buf[HEADER_LEN..HEADER_LEN + payload.len()].copy_from_slice(payload);

    let crc = crc::checksum(&buf[..HEADER_LEN + payload.len()]);
    #[allow(
        clippy::cast_possible_truncation,
        reason = "checksum() returns a 24-bit value in the low 3 bytes; each shift-and-store below takes one of those bytes"
    )]
    {
        buf[HEADER_LEN + payload.len()] = (crc >> 16) as u8;
        buf[HEADER_LEN + payload.len() + 1] = (crc >> 8) as u8;
        buf[HEADER_LEN + payload.len() + 2] = crc as u8;
    }

    Ok(total)
}

// Frame::parse bounds-checks buf.len() against the header's own declared
// length before ever slicing, so it never panics regardless of buffer
// size. But both parse and encode call crc::checksum, whose outer loop
// needs an explicit #[kani::unwind] bound regardless of caller (see
// crc.rs) - every harness below needs one covering the largest slice
// checksum could see in that harness (buf.len() for parse; header + the
// fixed payload size for encode).
#[cfg(kani)]
mod kani_proofs {
    use super::{Frame, encode};

    #[kani::proof]
    #[kani::unwind(17)]
    fn parse_never_panics() {
        let buf: [u8; 16] = kani::any();
        let _ = Frame::parse(&buf);
    }

    #[kani::proof]
    #[kani::unwind(17)]
    fn encode_never_panics() {
        let mut buf = [0u8; 32];
        let payload: [u8; 8] = kani::any();
        let _ = encode(&mut buf, &payload);
    }

    #[kani::proof]
    #[kani::unwind(17)]
    fn encode_then_parse_round_trips() {
        let mut buf = [0u8; 32];
        let payload: [u8; 8] = kani::any();
        let n = encode(&mut buf, &payload).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.payload(), &payload);
    }
}

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

    fn hex_decode<const N: usize>(hex: &str) -> [u8; N] {
        let mut out = [0u8; N];
        for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
            let s = core::str::from_utf8(chunk).unwrap();
            out[i] = u8::from_str_radix(s, 16).unwrap();
        }
        out
    }

    #[test]
    fn parses_a_real_captured_mt1230_frame() {
        // From pyrtcm's own test corpus (pygpsdata-1230.bin).
        let buf: [u8; 10] = hex_decode("d300044ce00080ededd6");
        let frame = Frame::parse(&buf).unwrap();
        assert_eq!(frame.payload().len(), 4);
        assert_eq!(frame.byte_len(), 10);
    }

    #[test]
    fn rejects_an_unknown_preamble() {
        assert_eq!(
            Frame::parse(&[0x00, 0x00, 0x00]),
            Err(FrameError::UnknownPreamble(0x00))
        );
    }

    #[test]
    fn rejects_reserved_bits_set() {
        let mut buf: [u8; 10] = hex_decode("d300044ce00080ededd6");
        buf[1] |= 0x04;
        assert_eq!(Frame::parse(&buf), Err(FrameError::ReservedBitsSet));
    }

    #[test]
    fn rejects_a_bad_checksum() {
        let mut buf: [u8; 10] = hex_decode("d300044ce00080ededd6");
        buf[9] ^= 0xFF;
        assert_eq!(Frame::parse(&buf), Err(FrameError::ChecksumMismatch));
    }

    #[test]
    fn rejects_a_buffer_shorter_than_the_declared_length() {
        let buf: [u8; 10] = hex_decode("d300044ce00080ededd6");
        assert_eq!(
            Frame::parse(&buf[..5]),
            Err(FrameError::TooShort { needed: 10, got: 5 })
        );
    }

    #[test]
    fn encode_matches_a_real_pyrtcm_mt1230_frame() {
        let expected: [u8; 10] = hex_decode("d300044ce00080ededd6");
        let payload = &expected[3..7];
        let mut buf = [0u8; MAX_FRAME_LEN];
        let n = encode(&mut buf, payload).unwrap();
        assert_eq!(&buf[..n], &expected[..]);
    }

    #[test]
    fn encode_round_trips_through_parse() {
        let payload = [1u8, 2, 3, 4, 5];
        let mut buf = [0u8; MAX_FRAME_LEN];
        let n = encode(&mut buf, &payload).unwrap();
        let frame = Frame::parse(&buf[..n]).unwrap();
        assert_eq!(frame.payload(), &payload);
    }
}