rtcm3 0.1.0

no_std, no_alloc parser and encoder for RTCM3 GNSS RTK correction messages
Documentation
//! Message-type-dispatched (DF002) decoding/encoding of a frame's payload
//! into a typed [`Rtcm3Message`].

mod glonass_bias;
mod gps_msm7;
mod station_arp;

pub use glonass_bias::GlonassBias;
pub use gps_msm7::{CellData, GpsMsm7, SatelliteData};
pub use station_arp::StationArp;

use crate::bits::{BitReader, BitWriter};
use crate::error::MessageError;

/// A decoded RTCM3 message, one variant per supported message type.
///
/// `#[non_exhaustive]`: more message types will be added.
///
/// [`GpsMsm7`] makes this enum's size dominated by its largest variant
/// (~1.4KB, from its two 64-element field arrays): a `no_alloc` crate has
/// no `Box` available to shrink the small variants down instead, so every
/// value of this type costs the large variant's size regardless of which
/// one it actually holds.
#[allow(
    clippy::large_enum_variant,
    reason = "no_alloc means no Box to shrink the small variants with; see the doc comment above"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Rtcm3Message {
    /// Stationary RTK Reference Station ARP (type 1005).
    StationArp(StationArp),
    /// GLONASS Code-Phase Biases (type 1230).
    GlonassBias(GlonassBias),
    /// GPS Full Pseudoranges and `PhaseRanges` plus CNR, high resolution
    /// (type 1077).
    GpsMsm7(GpsMsm7),
}

impl Rtcm3Message {
    /// Decodes a frame's payload, reading the 12-bit message type (DF002)
    /// first to dispatch to the right message decoder.
    ///
    /// # Errors
    /// Returns [`MessageError::UnknownMessageType`] if the payload's
    /// message type isn't one this crate decodes, or a wrapped
    /// [`crate::error::BitError`] if the payload is shorter than the
    /// message type declares.
    pub fn decode(payload: &[u8]) -> Result<Self, MessageError> {
        let mut r = BitReader::new(payload);
        let message_type = r.read_u16(12)?;
        match message_type {
            station_arp::TYPE => Ok(Self::StationArp(StationArp::decode(&mut r)?)),
            glonass_bias::TYPE => Ok(Self::GlonassBias(GlonassBias::decode(&mut r)?)),
            gps_msm7::TYPE => Ok(Self::GpsMsm7(GpsMsm7::decode(&mut r)?)),
            other => Err(MessageError::UnknownMessageType(other)),
        }
    }

    /// Encodes this message's payload (message type plus fields) into
    /// `buf`, returning the number of bytes written.
    ///
    /// # Errors
    /// Returns a [`crate::error::BitError`] if `buf` is too small.
    pub fn encode(&self, buf: &mut [u8]) -> Result<usize, crate::error::BitError> {
        let mut w = BitWriter::new(buf);
        match self {
            Self::StationArp(m) => {
                w.write_u32(u32::from(station_arp::TYPE), 12)?;
                m.encode(&mut w)?;
            }
            Self::GlonassBias(m) => {
                w.write_u32(u32::from(glonass_bias::TYPE), 12)?;
                m.encode(&mut w)?;
            }
            Self::GpsMsm7(m) => {
                w.write_u32(u32::from(gps_msm7::TYPE), 12)?;
                m.encode(&mut w)?;
            }
        }
        Ok(w.bytes_written())
    }
}

#[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 decodes_a_real_captured_frame() {
        let payload: [u8; 19] = hex_decode("3ed000038a58d9493c872f34109d07d6af4820");
        let msg = Rtcm3Message::decode(&payload).unwrap();
        let Rtcm3Message::StationArp(m) = msg else {
            panic!("expected StationArp");
        };
        assert_eq!(m.reference_station_id, 0);
    }

    #[test]
    fn rejects_an_unknown_message_type() {
        // 12 bits = 4095, an unassigned message type.
        let payload = [0xFFu8, 0xF0];
        assert_eq!(
            Rtcm3Message::decode(&payload),
            Err(MessageError::UnknownMessageType(4095))
        );
    }

    #[test]
    fn encode_then_decode_round_trips() {
        let original = Rtcm3Message::StationArp(StationArp {
            reference_station_id: 42,
            itrf_realization_year: 19,
            gps_indicator: true,
            glonass_indicator: true,
            galileo_indicator: false,
            reference_station_indicator: false,
            ecef_x_raw: 44_440_308_028,
            single_oscillator_indicator: false,
            ecef_y_raw: 30_856_712_349,
            quarter_cycle_indicator: 1,
            ecef_z_raw: 33_666_582_560,
        });
        let mut buf = [0u8; 19];
        let n = original.encode(&mut buf).unwrap();
        assert_eq!(n, 19);
        let decoded = Rtcm3Message::decode(&buf[..n]).unwrap();
        assert_eq!(decoded, original);
    }
}

// Fuzzes Rtcm3Message::decode over arbitrary payload bytes of varying
// length, not just the hand-picked fixtures above. Unlike mavwire's fixed-
// size messages, a short or arbitrary payload can legitimately run out of
// bits partway through a message this crate supports (most sharply for
// GpsMsm7, whose satellite/signal/cell masks can claim far more data than
// a short payload actually has) - that's an expected BitError, not a bug,
// so the property under test is "never panics", not "always succeeds".
#[cfg(test)]
mod proptests {
    extern crate std;

    use proptest::prelude::*;
    use std::vec::Vec;

    use super::Rtcm3Message;

    proptest! {
        #[test]
        fn decode_never_panics(bytes in prop::collection::vec(any::<u8>(), 0..300)) {
            let _ = Rtcm3Message::decode(&bytes);
        }

        #[test]
        fn decode_never_panics_for_known_message_types(
            message_type in prop_oneof![
                Just(super::station_arp::TYPE),
                Just(super::glonass_bias::TYPE),
                Just(super::gps_msm7::TYPE),
            ],
            mut rest in prop::collection::vec(any::<u8>(), 0..280),
        ) {
            // The first two bytes carry the 12-bit type code in their high
            // bits, matching a real payload's start; exact bit alignment
            // with `rest` doesn't matter for a no-panic fuzz test, only
            // that decode sees a known type code followed by arbitrary
            // trailing content of varying length.
            #[allow(
                clippy::cast_possible_truncation,
                reason = "message_type is one of three 12-bit constants, always fits these shifts"
            )]
            let mut buf: Vec<u8> = std::vec![(message_type >> 4) as u8, ((message_type & 0xF) << 4) as u8];
            buf.append(&mut rest);
            let _ = Rtcm3Message::decode(&buf);
        }
    }
}