mavwire 0.1.0

no_std, no_alloc parser and encoder for MAVLink v1/v2 telemetry messages
Documentation
//! A fixed-capacity, NUL-padded text field, as carried by `PARAM_VALUE`'s
//! `param_id` and `STATUSTEXT`'s `text`.
//!
//! `MAVLink` char arrays are plain ASCII/UTF-8, NUL-padded to their
//! declared width (confirmed against `pymavlink`'s own `struct.pack`
//! behavior, which zero-pads a short byte string to the field width).

/// A `MAVLink` fixed-width, NUL-padded text field of `N` bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FixedText<const N: usize> {
    buf: [u8; N],
}

impl<const N: usize> FixedText<N> {
    /// Builds a field from raw wire bytes (already `N` bytes, NUL-padded).
    pub(crate) const fn from_bytes(buf: [u8; N]) -> Self {
        Self { buf }
    }

    /// Builds a field from text, truncating to `N` bytes and NUL-padding
    /// the rest if shorter.
    #[must_use]
    pub fn from_text(s: &str) -> Self {
        let mut buf = [0u8; N];
        let bytes = s.as_bytes();
        let len = bytes.len().min(N);
        buf[..len].copy_from_slice(&bytes[..len]);
        Self { buf }
    }

    /// The raw `N`-byte wire representation.
    pub(crate) const fn as_bytes(&self) -> &[u8; N] {
        &self.buf
    }

    /// The text, with trailing NUL padding trimmed.
    #[must_use]
    pub fn as_str(&self) -> &str {
        let mut end = N;
        while end > 0 && self.buf[end - 1] == 0 {
            end -= 1;
        }
        core::str::from_utf8(&self.buf[..end]).unwrap_or_default()
    }
}

impl<const N: usize> core::fmt::Display for FixedText<N> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.as_str())
    }
}

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

    #[test]
    fn round_trips_a_short_string() {
        let t: FixedText<16> = FixedText::from_text("THR_MAX");
        assert_eq!(t.as_str(), "THR_MAX");
        assert_eq!(t.as_bytes()[7], 0);
    }

    #[test]
    fn truncates_a_too_long_string() {
        let t: FixedText<4> = FixedText::from_text("hello");
        assert_eq!(t.as_str(), "hell");
    }

    #[test]
    fn from_bytes_trims_nul_padding() {
        let t = FixedText::from_bytes(*b"AB\0\0");
        assert_eq!(t.as_str(), "AB");
    }
}