#[expect(clippy::cast_possible_truncation, reason = "the low 7 bits, by design")]
pub(crate) fn varint(out: &mut Vec<u8>, mut v: u64) {
while v >= 0x80 {
out.push((v as u8) | 0x80);
v >>= 7;
}
out.push(v as u8);
}
pub(crate) fn read_varint(b: &mut &[u8]) -> u64 {
if let Some((v, len)) = decode(b) {
*b = &b[len..];
v
} else {
*b = &[];
0
}
}
fn decode(src: &[u8]) -> Option<(u64, usize)> {
let mut v = 0_u64;
let mut shift = 0;
let mut done = false;
for &byte in src {
v |= u64::from(byte & 0x7f) << shift;
shift += 7;
if shift > 63 {
done = byte < 2;
break;
} else if byte < 0x80 {
done = true;
break;
}
}
done.then_some((v, shift / 7))
}
pub(crate) fn zigzag(d: i64) -> u64 {
((d << 1) ^ (d >> 63)).cast_unsigned()
}
pub(crate) fn unzigzag(v: u64) -> i64 {
(v >> 1).cast_signed() ^ -((v & 1).cast_signed())
}
pub(crate) fn pack_ids(out: &mut Vec<u8>, ids: impl Iterator<Item = i64>) {
let mut prev = 0_i64;
for id in ids {
varint(out, zigzag(id.wrapping_sub(prev)));
prev = id;
}
}
pub(crate) fn unpack_ids(mut b: &[u8]) -> Vec<i64> {
let mut prev = 0_i64;
let mut ids = Vec::new();
while !b.is_empty() {
prev = prev.wrapping_add(unzigzag(read_varint(&mut b)));
ids.push(prev);
}
ids
}
#[cfg(test)]
mod tests {
use super::*;
fn packed(ids: &[i64]) -> Vec<u8> {
let mut b = Vec::new();
pack_ids(&mut b, ids.iter().copied());
b
}
#[test]
fn ids_round_trip() {
let big = 1_i64 << 36;
for ids in [
&[][..],
&[7],
&[1, 2, 3, 1000, 1001],
&[1000, 999, 5, 4],
&[big, big + 1, big - 3, big + 70_000],
&[big, -big, 3, i64::MAX, i64::MIN, 0],
] {
assert_eq!(unpack_ids(&packed(ids)), ids);
}
assert_eq!(packed(&[]), b"");
}
#[test]
fn varints_read_whole_and_damaged() {
for v in [0, 1, 127, 128, 300, 1 << 35, u64::MAX] {
let mut b = Vec::new();
varint(&mut b, v);
b.push(0x55);
let mut s = &b[..];
assert_eq!((read_varint(&mut s), s), (v, &[0x55][..]), "{v}");
}
for damaged in [&[0x80][..], &[0xff; 10], &[0xff; 11]] {
let mut s = damaged;
assert_eq!((read_varint(&mut s), s.len()), (0, 0), "{damaged:?}");
}
}
#[test]
fn ids_have_known_bytes() {
assert_eq!(
packed(&[100, 101, 99, 399]),
[0xc8, 0x01, 0x02, 0x03, 0xd8, 0x04]
);
}
}