xmachines-codec 1.0.0

Pluggable codecs for the events and snapshots of xmachines-rs machines, with JSON built in
Documentation
//! Base-128 varints (least significant group first, as protobuf, Avro and
//! the Kafka service's changelog marks write them) and zigzag signed
//! integers.

use crate::Error;

/// Appends `v` as a varint.
#[inline]
pub fn put_varint(out: &mut Vec<u8>, mut v: u64) {
    while v >= 0x80 {
        out.push((v as u8) | 0x80);
        v >>= 7;
    }
    out.push(v as u8);
}

/// Reads a varint from the front of `input`, moving it past the varint.
pub fn read_varint(input: &mut &[u8]) -> Result<u64, Error> {
    let mut v = 0u64;
    for i in 0..10 {
        let Some((&b, rest)) = input.split_first() else { return Err(Error::Decode("truncated varint".into())) };
        *input = rest;
        v |= u64::from(b & 0x7f) << (7 * i);
        if b < 0x80 {
            return Ok(v);
        }
    }
    Err(Error::Decode("varint too long".into()))
}

/// A signed integer as an unsigned one for a varint, small magnitudes
/// small (zigzag: 0, -1, 1, -2, ...).
#[inline]
pub fn zigzag(v: i64) -> u64 {
    ((v << 1) ^ (v >> 63)) as u64
}

/// The signed integer of a [`zigzag`] encoding.
#[inline]
pub fn unzigzag(v: u64) -> i64 {
    ((v >> 1) as i64) ^ -((v & 1) as i64)
}

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

    #[test]
    fn varints_and_zigzag_round_trip() {
        for v in [0u64, 1, 127, 128, 300, u32::MAX as u64, u64::MAX] {
            let mut out = Vec::new();
            put_varint(&mut out, v);
            let mut input = &out[..];
            assert_eq!(read_varint(&mut input).unwrap(), v);
            assert!(input.is_empty());
            assert!(read_varint(&mut &out[..out.len() - 1]).is_err(), "truncated");
        }
        assert!(read_varint(&mut &[0xff; 11][..]).is_err(), "too long");
        for v in [0i64, -1, 1, -64, 64, i64::MIN, i64::MAX] {
            assert_eq!(unzigzag(zigzag(v)), v);
        }
        assert_eq!(zigzag(-1), 1);
    }
}