Skip to main content

coip_format/
varint.rs

1use alloc::string::String;
2use alloc::vec::Vec;
3
4use crate::FormatError;
5
6/// Encode an unsigned 64-bit integer as LEB128 varint.
7#[inline]
8pub fn write_uvarint(out: &mut Vec<u8>, mut v: u64) {
9    while v >= 0x80 {
10        out.push(((v as u8) & 0x7F) | 0x80);
11        v >>= 7;
12    }
13    out.push(v as u8);
14}
15
16/// Decode an unsigned LEB128 varint from `buf`, returning `(value, bytes_consumed)`.
17#[inline]
18pub fn read_uvarint(buf: &[u8]) -> Result<(u64, usize), FormatError> {
19    let mut result = 0u64;
20    let mut shift = 0u32;
21    for (i, &byte) in buf.iter().enumerate() {
22        if i == 9 && byte > 1 {
23            return Err(FormatError::VarintOverflow);
24        }
25        result |= ((byte & 0x7F) as u64) << shift;
26        if (byte & 0x80) == 0 {
27            return Ok((result, i + 1));
28        }
29        shift += 7;
30        if shift >= 64 {
31            return Err(FormatError::VarintOverflow);
32        }
33    }
34    Err(FormatError::UnexpectedEof)
35}
36
37/// ZigZag-encode a signed 64-bit integer into `u64`.
38#[inline]
39pub const fn zigzag_encode(v: i64) -> u64 {
40    ((v << 1) ^ (v >> 63)) as u64
41}
42
43/// ZigZag-decode a `u64` back into `i64`.
44#[inline]
45pub const fn zigzag_decode(u: u64) -> i64 {
46    ((u >> 1) as i64) ^ -((u & 1) as i64)
47}
48
49/// Write a ZigZag-encoded signed varint.
50#[inline]
51pub fn write_svarint(out: &mut Vec<u8>, v: i64) {
52    write_uvarint(out, zigzag_encode(v));
53}
54
55/// Read a ZigZag-encoded signed varint.
56#[inline]
57pub fn read_svarint(buf: &[u8]) -> Result<(i64, usize), FormatError> {
58    let (u, n) = read_uvarint(buf)?;
59    Ok((zigzag_decode(u), n))
60}
61
62/// Write a length-prefixed UTF-8 string (`uvarint` len + UTF-8 bytes).
63#[inline]
64pub fn write_string(out: &mut Vec<u8>, s: &str) {
65    write_uvarint(out, s.len() as u64);
66    out.extend_from_slice(s.as_bytes());
67}
68
69/// Zero-copy bounds-checked little-endian slice reader.
70#[derive(Debug, Clone, Copy)]
71pub struct Cursor<'a> {
72    buf: &'a [u8],
73    pos: usize,
74}
75
76impl<'a> Cursor<'a> {
77    #[inline]
78    pub const fn new(buf: &'a [u8]) -> Self {
79        Self { buf, pos: 0 }
80    }
81
82    #[inline]
83    pub const fn pos(&self) -> usize {
84        self.pos
85    }
86
87    #[inline]
88    pub const fn remaining(&self) -> usize {
89        self.buf.len().saturating_sub(self.pos)
90    }
91
92    #[inline]
93    pub fn remaining_slice(&self) -> &'a [u8] {
94        &self.buf[self.pos..]
95    }
96
97    #[inline]
98    pub fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], FormatError> {
99        let end = self
100            .pos
101            .checked_add(len)
102            .ok_or(FormatError::UnexpectedEof)?;
103        if end > self.buf.len() {
104            return Err(FormatError::UnexpectedEof);
105        }
106        let slice = &self.buf[self.pos..end];
107        self.pos = end;
108        Ok(slice)
109    }
110
111    #[inline]
112    pub fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
113        let slice = self.read_bytes(N)?;
114        let mut arr = [0u8; N];
115        arr.copy_from_slice(slice);
116        Ok(arr)
117    }
118
119    #[inline]
120    pub fn read_u8(&mut self) -> Result<u8, FormatError> {
121        Ok(self.read_array::<1>()?[0])
122    }
123
124    #[inline]
125    pub fn read_u16(&mut self) -> Result<u16, FormatError> {
126        Ok(u16::from_le_bytes(self.read_array::<2>()?))
127    }
128
129    #[inline]
130    pub fn read_u32(&mut self) -> Result<u32, FormatError> {
131        Ok(u32::from_le_bytes(self.read_array::<4>()?))
132    }
133
134    #[inline]
135    pub fn read_u64(&mut self) -> Result<u64, FormatError> {
136        Ok(u64::from_le_bytes(self.read_array::<8>()?))
137    }
138
139    #[inline]
140    pub fn read_u128(&mut self) -> Result<u128, FormatError> {
141        Ok(u128::from_le_bytes(self.read_array::<16>()?))
142    }
143
144    #[inline]
145    pub fn read_i32(&mut self) -> Result<i32, FormatError> {
146        Ok(i32::from_le_bytes(self.read_array::<4>()?))
147    }
148
149    #[inline]
150    pub fn read_i64(&mut self) -> Result<i64, FormatError> {
151        Ok(i64::from_le_bytes(self.read_array::<8>()?))
152    }
153
154    #[inline]
155    pub fn read_f32(&mut self) -> Result<f32, FormatError> {
156        Ok(f32::from_bits(self.read_u32()?))
157    }
158
159    #[inline]
160    pub fn read_f64(&mut self) -> Result<f64, FormatError> {
161        Ok(f64::from_bits(self.read_u64()?))
162    }
163
164    #[inline]
165    pub fn read_uvarint(&mut self) -> Result<u64, FormatError> {
166        let (v, n) = read_uvarint(&self.buf[self.pos..])?;
167        self.pos += n;
168        Ok(v)
169    }
170
171    #[inline]
172    pub fn read_svarint(&mut self) -> Result<i64, FormatError> {
173        let (v, n) = read_svarint(&self.buf[self.pos..])?;
174        self.pos += n;
175        Ok(v)
176    }
177
178    #[inline]
179    pub fn read_str(&mut self) -> Result<&'a str, FormatError> {
180        let len = usize::try_from(self.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
181        let bytes = self.read_bytes(len)?;
182        core::str::from_utf8(bytes).map_err(|_| FormatError::InvalidUtf8)
183    }
184
185    #[inline]
186    pub fn read_string(&mut self) -> Result<String, FormatError> {
187        Ok(String::from(self.read_str()?))
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn test_varint_roundtrip() {
197        let samples = [0u64, 1, 127, 128, 16383, 16384, u32::MAX as u64, u64::MAX];
198        for v in samples {
199            let mut buf = Vec::new();
200            write_uvarint(&mut buf, v);
201            let (got, n) = read_uvarint(&buf).unwrap();
202            assert_eq!(got, v);
203            assert_eq!(n, buf.len());
204        }
205    }
206
207    #[test]
208    fn test_zigzag_roundtrip() {
209        let samples = [0i64, 1, -1, 2, -2, 123456, -123456, i64::MAX, i64::MIN];
210        for v in samples {
211            let mut buf = Vec::new();
212            write_svarint(&mut buf, v);
213            let (got, n) = read_svarint(&buf).unwrap();
214            assert_eq!(got, v);
215            assert_eq!(n, buf.len());
216        }
217    }
218}