coip-format 0.1.0

Core binary format definitions, schema, varint, CRC32C, and wire codecs for COI (.coi) columnar IP databases
Documentation
use alloc::string::String;
use alloc::vec::Vec;

use crate::FormatError;

/// Encode an unsigned 64-bit integer as LEB128 varint.
#[inline]
pub fn write_uvarint(out: &mut Vec<u8>, mut v: u64) {
    while v >= 0x80 {
        out.push(((v as u8) & 0x7F) | 0x80);
        v >>= 7;
    }
    out.push(v as u8);
}

/// Decode an unsigned LEB128 varint from `buf`, returning `(value, bytes_consumed)`.
#[inline]
pub fn read_uvarint(buf: &[u8]) -> Result<(u64, usize), FormatError> {
    let mut result = 0u64;
    let mut shift = 0u32;
    for (i, &byte) in buf.iter().enumerate() {
        if i == 9 && byte > 1 {
            return Err(FormatError::VarintOverflow);
        }
        result |= ((byte & 0x7F) as u64) << shift;
        if (byte & 0x80) == 0 {
            return Ok((result, i + 1));
        }
        shift += 7;
        if shift >= 64 {
            return Err(FormatError::VarintOverflow);
        }
    }
    Err(FormatError::UnexpectedEof)
}

/// ZigZag-encode a signed 64-bit integer into `u64`.
#[inline]
pub const fn zigzag_encode(v: i64) -> u64 {
    ((v << 1) ^ (v >> 63)) as u64
}

/// ZigZag-decode a `u64` back into `i64`.
#[inline]
pub const fn zigzag_decode(u: u64) -> i64 {
    ((u >> 1) as i64) ^ -((u & 1) as i64)
}

/// Write a ZigZag-encoded signed varint.
#[inline]
pub fn write_svarint(out: &mut Vec<u8>, v: i64) {
    write_uvarint(out, zigzag_encode(v));
}

/// Read a ZigZag-encoded signed varint.
#[inline]
pub fn read_svarint(buf: &[u8]) -> Result<(i64, usize), FormatError> {
    let (u, n) = read_uvarint(buf)?;
    Ok((zigzag_decode(u), n))
}

/// Write a length-prefixed UTF-8 string (`uvarint` len + UTF-8 bytes).
#[inline]
pub fn write_string(out: &mut Vec<u8>, s: &str) {
    write_uvarint(out, s.len() as u64);
    out.extend_from_slice(s.as_bytes());
}

/// Zero-copy bounds-checked little-endian slice reader.
#[derive(Debug, Clone, Copy)]
pub struct Cursor<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    #[inline]
    pub const fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    #[inline]
    pub const fn pos(&self) -> usize {
        self.pos
    }

    #[inline]
    pub const fn remaining(&self) -> usize {
        self.buf.len().saturating_sub(self.pos)
    }

    #[inline]
    pub fn remaining_slice(&self) -> &'a [u8] {
        &self.buf[self.pos..]
    }

    #[inline]
    pub fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], FormatError> {
        let end = self
            .pos
            .checked_add(len)
            .ok_or(FormatError::UnexpectedEof)?;
        if end > self.buf.len() {
            return Err(FormatError::UnexpectedEof);
        }
        let slice = &self.buf[self.pos..end];
        self.pos = end;
        Ok(slice)
    }

    #[inline]
    pub fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
        let slice = self.read_bytes(N)?;
        let mut arr = [0u8; N];
        arr.copy_from_slice(slice);
        Ok(arr)
    }

    #[inline]
    pub fn read_u8(&mut self) -> Result<u8, FormatError> {
        Ok(self.read_array::<1>()?[0])
    }

    #[inline]
    pub fn read_u16(&mut self) -> Result<u16, FormatError> {
        Ok(u16::from_le_bytes(self.read_array::<2>()?))
    }

    #[inline]
    pub fn read_u32(&mut self) -> Result<u32, FormatError> {
        Ok(u32::from_le_bytes(self.read_array::<4>()?))
    }

    #[inline]
    pub fn read_u64(&mut self) -> Result<u64, FormatError> {
        Ok(u64::from_le_bytes(self.read_array::<8>()?))
    }

    #[inline]
    pub fn read_u128(&mut self) -> Result<u128, FormatError> {
        Ok(u128::from_le_bytes(self.read_array::<16>()?))
    }

    #[inline]
    pub fn read_i32(&mut self) -> Result<i32, FormatError> {
        Ok(i32::from_le_bytes(self.read_array::<4>()?))
    }

    #[inline]
    pub fn read_i64(&mut self) -> Result<i64, FormatError> {
        Ok(i64::from_le_bytes(self.read_array::<8>()?))
    }

    #[inline]
    pub fn read_f32(&mut self) -> Result<f32, FormatError> {
        Ok(f32::from_bits(self.read_u32()?))
    }

    #[inline]
    pub fn read_f64(&mut self) -> Result<f64, FormatError> {
        Ok(f64::from_bits(self.read_u64()?))
    }

    #[inline]
    pub fn read_uvarint(&mut self) -> Result<u64, FormatError> {
        let (v, n) = read_uvarint(&self.buf[self.pos..])?;
        self.pos += n;
        Ok(v)
    }

    #[inline]
    pub fn read_svarint(&mut self) -> Result<i64, FormatError> {
        let (v, n) = read_svarint(&self.buf[self.pos..])?;
        self.pos += n;
        Ok(v)
    }

    #[inline]
    pub fn read_str(&mut self) -> Result<&'a str, FormatError> {
        let len = usize::try_from(self.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
        let bytes = self.read_bytes(len)?;
        core::str::from_utf8(bytes).map_err(|_| FormatError::InvalidUtf8)
    }

    #[inline]
    pub fn read_string(&mut self) -> Result<String, FormatError> {
        Ok(String::from(self.read_str()?))
    }
}

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

    #[test]
    fn test_varint_roundtrip() {
        let samples = [0u64, 1, 127, 128, 16383, 16384, u32::MAX as u64, u64::MAX];
        for v in samples {
            let mut buf = Vec::new();
            write_uvarint(&mut buf, v);
            let (got, n) = read_uvarint(&buf).unwrap();
            assert_eq!(got, v);
            assert_eq!(n, buf.len());
        }
    }

    #[test]
    fn test_zigzag_roundtrip() {
        let samples = [0i64, 1, -1, 2, -2, 123456, -123456, i64::MAX, i64::MIN];
        for v in samples {
            let mut buf = Vec::new();
            write_svarint(&mut buf, v);
            let (got, n) = read_svarint(&buf).unwrap();
            assert_eq!(got, v);
            assert_eq!(n, buf.len());
        }
    }
}