symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
//! Variable-length integer encoding used for MQTT remaining length [MQTT-2.2.3]
//!
//! The scheme encodes values 0–268,435,455 in 1–4 bytes. Each byte uses
//! bit 7 as a continuation flag and bits 6–0 as payload.

use crate::DecodeError;

/// Maximum number of bytes a variable-length integer occupies [MQTT-2.2.3]
pub const MAX_LEN: usize = 4;

/// Encode `value` into the front of `dst`, returning the number of bytes written
///
/// Writing into a caller-owned slice (rather than appending to a buffer) lets the
/// packet encoder reserve a placeholder header, write the body, and only then fill
/// in the remaining length it just measured.
///
/// # Panics
///
/// Panics if `dst` is shorter than the encoding needs. Callers must reject values
/// above [`MAX_REMAINING_LEN`](crate::MAX_REMAINING_LEN) first, after which
/// [`MAX_LEN`] bytes always suffice.
pub fn encode_to(value: u32, dst: &mut [u8]) -> usize {
    let mut remaining = value;
    let mut written = 0;
    loop {
        // Low 7 bits carry the payload, bit 7 signals "more bytes follow"
        let mut byte = (remaining % 128) as u8;
        remaining /= 128;
        if remaining > 0 {
            byte |= 0x80;
        }
        dst[written] = byte;
        written += 1;
        if remaining == 0 {
            return written;
        }
    }
}

/// Read a variable-length integer without consuming `buf`
///
/// # Returns
///
/// `Ok(None)` when more bytes are needed, otherwise `Ok(Some((value, consumed)))`
/// where `consumed` is how many bytes the integer occupied
///
/// # Errors
///
/// Returns [`DecodeError::MalformedRemainingLength`] if the fourth byte still has
/// the continuation bit set, since no valid encoding exceeds [`MAX_LEN`] bytes
pub fn peek(buf: &[u8]) -> Result<Option<(u32, usize)>, DecodeError> {
    let mut multiplier: u32 = 1;
    let mut value: u32 = 0;

    for i in 0..MAX_LEN {
        let Some(&byte) = buf.get(i) else {
            return Ok(None);
        };
        value += (byte as u32 & 0x7F) * multiplier;

        if byte & 0x80 == 0 {
            return Ok(Some((value, i + 1)));
        }
        multiplier *= 128;
    }

    Err(DecodeError::MalformedRemainingLength)
}

/// Decode a variable-length integer, consuming bytes from `buf`
///
/// Unlike [`peek`], this advances the buffer position past the integer.
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] if the buffer is empty before the
/// encoding terminates.
///
/// Returns [`DecodeError::MalformedRemainingLength`] if the fourth byte still has
/// the continuation bit set.
pub fn decode(buf: &mut bytes::Bytes) -> Result<u32, DecodeError> {
    use bytes::Buf;

    let mut multiplier: u32 = 1;
    let mut value: u32 = 0;

    for _ in 0..MAX_LEN {
        if !buf.has_remaining() {
            return Err(DecodeError::InsufficientBytes { needed: 1 });
        }
        let byte = buf.get_u8();
        value += (byte as u32 & 0x7F) * multiplier;
        if byte & 0x80 == 0 {
            return Ok(value);
        }
        multiplier *= 128;
    }

    Err(DecodeError::MalformedRemainingLength)
}

/// Number of bytes needed to encode `value` as a variable-length integer
pub fn len(value: u32) -> usize {
    match value {
        0..=127 => 1,
        128..=16_383 => 2,
        16_384..=2_097_151 => 3,
        _ => 4,
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;

    use super::*;
    use crate::DecodeError;

    const BOUNDARY_VALUES: &[(u32, &[u8])] = &[
        (0, &[0x00]),
        (127, &[0x7F]),
        (128, &[0x80, 0x01]),
        (16_383, &[0xFF, 0x7F]),
        (16_384, &[0x80, 0x80, 0x01]),
        (2_097_151, &[0xFF, 0xFF, 0x7F]),
        (2_097_152, &[0x80, 0x80, 0x80, 0x01]),
        (268_435_455, &[0xFF, 0xFF, 0xFF, 0x7F]),
    ];

    #[test]
    fn encode_boundary_values() {
        for &(value, expected) in BOUNDARY_VALUES {
            let mut dst = [0u8; 4];
            let written = encode_to(value, &mut dst);
            assert_eq!(&dst[..written], expected, "encode_to({value}) failed");
        }
    }

    #[test]
    fn decode_boundary_values() {
        for &(expected, encoded) in BOUNDARY_VALUES {
            let mut buf = Bytes::copy_from_slice(encoded);
            let got = decode(&mut buf).unwrap();
            assert_eq!(got, expected, "decode({encoded:?}) failed");
            assert_eq!(buf.len(), 0);
        }
    }

    #[test]
    fn encode_decode_roundtrip() {
        for &(value, _) in BOUNDARY_VALUES {
            let mut dst = [0u8; 4];
            let written = encode_to(value, &mut dst);
            let mut buf = Bytes::copy_from_slice(&dst[..written]);
            assert_eq!(decode(&mut buf).unwrap(), value);
        }
    }

    #[test]
    fn peek_empty_buffer() {
        assert_eq!(peek(&[]), Ok(None));
    }

    #[test]
    fn peek_incomplete_one_byte_with_continuation() {
        assert_eq!(peek(&[0x80]), Ok(None));
    }

    #[test]
    fn peek_incomplete_two_bytes_with_continuation() {
        assert_eq!(peek(&[0x80, 0x80]), Ok(None));
    }

    #[test]
    fn peek_incomplete_three_bytes_with_continuation() {
        assert_eq!(peek(&[0x80, 0x80, 0x80]), Ok(None));
    }

    #[test]
    fn peek_malformed_four_bytes_all_continuation() {
        assert_eq!(
            peek(&[0x80, 0x80, 0x80, 0x80]),
            Err(DecodeError::MalformedRemainingLength)
        );
    }

    #[test]
    fn peek_value_with_trailing_bytes() {
        // Value 1 encoded as [0x01], followed by extra bytes
        assert_eq!(peek(&[0x01, 0x02, 0x03]), Ok(Some((1, 1))));
    }

    #[test]
    fn peek_boundary_values() {
        for &(value, encoded) in BOUNDARY_VALUES {
            let result = peek(encoded).unwrap().unwrap();
            assert_eq!(result, (value, encoded.len()), "peek({encoded:?}) failed");
        }
    }

    #[test]
    fn decode_empty_buffer() {
        let mut buf = Bytes::new();
        assert_eq!(decode(&mut buf), Err(DecodeError::InsufficientBytes { needed: 1 }));
    }

    #[test]
    fn decode_incomplete_continuation() {
        let mut buf = Bytes::from_static(&[0x80]);
        assert_eq!(decode(&mut buf), Err(DecodeError::InsufficientBytes { needed: 1 }));
    }

    #[test]
    fn decode_malformed() {
        let mut buf = Bytes::from_static(&[0x80, 0x80, 0x80, 0x80]);
        assert_eq!(decode(&mut buf), Err(DecodeError::MalformedRemainingLength));
    }

    #[test]
    fn len_boundary_values() {
        assert_eq!(len(0), 1);
        assert_eq!(len(127), 1);
        assert_eq!(len(128), 2);
        assert_eq!(len(16_383), 2);
        assert_eq!(len(16_384), 3);
        assert_eq!(len(2_097_151), 3);
        assert_eq!(len(2_097_152), 4);
        assert_eq!(len(268_435_455), 4);
    }
}