rtcm3 0.1.0

no_std, no_alloc parser and encoder for RTCM3 GNSS RTK correction messages
Documentation
//! MSB-first bit writer, the encode-side counterpart to
//! [`super::reader::BitReader`].

use crate::error::BitError;

/// Writes fixed-width fields into a byte slice, most-significant-bit
/// first, zero-filling any bits never written.
pub struct BitWriter<'a> {
    data: &'a mut [u8],
    bit_pos: usize,
}

impl<'a> BitWriter<'a> {
    /// Builds a writer over `data`, zeroing it first so unwritten bits
    /// (e.g. padding at the end of a message) read back as `0`.
    pub fn new(data: &'a mut [u8]) -> Self {
        data.fill(0);
        Self { data, bit_pos: 0 }
    }

    /// How many unwritten bits remain.
    #[must_use]
    pub const fn remaining_bits(&self) -> usize {
        self.data.len() * 8 - self.bit_pos
    }

    /// How many whole bytes have been touched so far (bits written,
    /// rounded up) - used to size a variable-length message's payload
    /// after encoding it, since RTCM3 messages aren't always a whole
    /// number of bits (unused trailing bits in the last byte are padding,
    /// left zero by [`Self::new`]).
    #[must_use]
    pub const fn bytes_written(&self) -> usize {
        self.bit_pos.div_ceil(8)
    }

    /// Writes a single bit.
    ///
    /// # Errors
    /// Returns [`BitError::BufferFull`] if no bits remain.
    pub fn write_bool(&mut self, value: bool) -> Result<(), BitError> {
        self.write_u64(u64::from(value), 1)
    }

    /// Writes the low `nbits` bits of `value` (`1..=64`).
    ///
    /// # Errors
    /// Returns [`BitError::OutOfRange`] if `nbits` is `0` or greater than
    /// `64`, or [`BitError::BufferFull`] if fewer than `nbits` bits remain.
    pub fn write_u64(&mut self, value: u64, nbits: u32) -> Result<(), BitError> {
        if nbits == 0 || nbits > 64 {
            return Err(BitError::OutOfRange { field: "nbits" });
        }
        if (nbits as usize) > self.remaining_bits() {
            return Err(BitError::BufferFull);
        }
        for i in (0..nbits).rev() {
            let bit = ((value >> i) & 1) as u8;
            let byte_idx = self.bit_pos / 8;
            let bit_idx = 7 - (self.bit_pos % 8);
            self.data[byte_idx] |= bit << bit_idx;
            self.bit_pos += 1;
        }
        Ok(())
    }

    /// Writes the low `nbits` bits of `value` (`1..=32`).
    ///
    /// # Errors
    /// Same as [`Self::write_u64`].
    pub fn write_u32(&mut self, value: u32, nbits: u32) -> Result<(), BitError> {
        self.write_u64(u64::from(value), nbits)
    }

    /// Writes the low `nbits` bits of a signed value's two's-complement
    /// representation (`1..=32`).
    ///
    /// # Errors
    /// Same as [`Self::write_u64`].
    pub fn write_i32(&mut self, value: i32, nbits: u32) -> Result<(), BitError> {
        #[allow(
            clippy::cast_sign_loss,
            reason = "reinterpreting the two's-complement bit pattern, not a numeric conversion"
        )]
        let bits = value as u32;
        let mask = if nbits >= 32 {
            u32::MAX
        } else {
            (1u32 << nbits) - 1
        };
        self.write_u32(bits & mask, nbits)
    }

    /// Skips `nbits` bits, leaving them zero.
    ///
    /// # Errors
    /// Returns [`BitError::BufferFull`] if fewer than `nbits` bits remain.
    pub fn skip(&mut self, nbits: u32) -> Result<(), BitError> {
        if (nbits as usize) > self.remaining_bits() {
            return Err(BitError::BufferFull);
        }
        self.bit_pos += nbits as usize;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bits::reader::BitReader;

    #[test]
    fn writes_and_reads_back_known_values() {
        let mut buf = [0u8; 2];
        let mut w = BitWriter::new(&mut buf);
        w.write_u32(0b1010, 4).unwrap();
        w.write_u32(0b1100, 4).unwrap();
        w.write_u32(0b1111_0000, 8).unwrap();

        let mut r = BitReader::new(&buf);
        assert_eq!(r.read_u8(4).unwrap(), 0b1010);
        assert_eq!(r.read_u8(4).unwrap(), 0b1100);
        assert_eq!(r.read_u16(8).unwrap(), 0b1111_0000);
    }

    #[test]
    fn write_read_signed_round_trips() {
        for (value, nbits) in [(-1i32, 6), (0, 6), (31, 6), (-32, 6)] {
            let mut buf = [0u8; 1];
            let mut w = BitWriter::new(&mut buf);
            w.write_i32(value, nbits).unwrap();
            let mut r = BitReader::new(&buf);
            assert_eq!(r.read_i32(nbits).unwrap(), value);
        }
    }

    #[test]
    fn buffer_full_is_reported_not_panicked() {
        let mut buf = [0u8; 1];
        let mut w = BitWriter::new(&mut buf);
        assert_eq!(w.write_u64(0, 9), Err(BitError::BufferFull));
    }

    #[test]
    fn bytes_written_rounds_up_to_a_whole_byte() {
        let mut buf = [0u8; 3];
        let mut w = BitWriter::new(&mut buf);
        assert_eq!(w.bytes_written(), 0);
        w.write_u32(0, 1).unwrap();
        assert_eq!(w.bytes_written(), 1);
        w.write_u32(0, 15).unwrap();
        assert_eq!(w.bytes_written(), 2);
    }

    #[test]
    fn skip_leaves_bits_zero() {
        let mut buf = [0xFFu8; 1];
        let mut w = BitWriter::new(&mut buf);
        w.skip(8).unwrap();
        assert_eq!(buf, [0x00]);
    }
}