use num_bigint::{BigInt, BigUint, Sign};
use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::limits::Limits;
pub fn wide(n: usize) -> u64 {
u64::try_from(n).expect("a usize fits 64 bits")
}
pub(crate) fn index(n: u32) -> usize {
usize::try_from(n).expect("a u32 fits a usize")
}
pub(crate) const NONE: u64 = 0;
pub(crate) const SOME: u64 = 1;
pub(crate) const OK: u64 = 0;
pub(crate) const ERR: u64 = 1;
fn base_128(digits: &[u8]) -> BigUint {
BigUint::from_radix_le(digits, 128).expect("every digit read is below 128")
}
pub fn write_uint(out: &mut Vec<u8>, mut value: u64) {
while value >= 0x80 {
out.push(low_seven(value) | 0x80);
value >>= 7;
}
out.push(low_seven(value));
}
fn low_seven(value: u64) -> u8 {
u8::try_from(value & 0x7f).expect("seven bits fit a byte")
}
pub fn write_biguint(out: &mut Vec<u8>, value: &BigUint) {
if value.bits() == 0 {
out.push(0);
return;
}
let digits = value.to_radix_le(128);
let last = digits.len() - 1;
out.extend(
digits
.iter()
.enumerate()
.map(|(at, digit)| if at == last { *digit } else { digit | 0x80 }),
);
}
pub fn write_int(out: &mut Vec<u8>, value: &BigInt) {
let magnitude = value.magnitude();
if magnitude.bits() < 64 {
let small = magnitude.iter_u64_digits().next().unwrap_or(0) << 1;
write_uint(
out,
match value.sign() {
Sign::Minus => small - 1,
Sign::NoSign | Sign::Plus => small,
},
);
return;
}
let zigzag = match value.sign() {
Sign::Minus => (magnitude << 1u32) - 1u32,
Sign::NoSign | Sign::Plus => magnitude << 1u32,
};
write_biguint(out, &zigzag);
}
pub fn write_signed(out: &mut Vec<u8>, value: i64) {
let zigzag = (value << 1) ^ (value >> 63);
write_uint(out, zigzag.cast_unsigned());
}
pub fn write_text(out: &mut Vec<u8>, text: &str) {
write_bytes(out, text.as_bytes());
}
pub fn write_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
write_uint(out, wide(bytes.len()));
out.extend_from_slice(bytes);
}
#[derive(Clone, Debug)]
pub struct Reader<'a> {
bytes: &'a [u8],
at: usize,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NotAUint {
TooLarge,
Overlong,
}
impl std::fmt::Display for NotAUint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
NotAUint::TooLarge => "larger than 64 bits",
NotAUint::Overlong => "written in more bytes than it needs",
})
}
}
fn overlong(digits: usize, last: u8) -> bool {
digits > 1 && last == 0
}
pub fn read_uint<E>(
mut next: impl FnMut() -> Result<u8, E>,
refuse: impl FnOnce(NotAUint) -> E,
) -> Result<u64, E> {
let mut value = 0u64;
let mut shift = 0u32;
let mut digits = 0usize;
loop {
let byte = next()?;
digits += 1;
let low = u64::from(byte & 0x7f);
if shift > 63 || (shift == 63 && low > 1) {
return Err(refuse(NotAUint::TooLarge));
}
value |= low << shift;
if byte & 0x80 == 0 {
if overlong(digits, byte) {
return Err(refuse(NotAUint::Overlong));
}
return Ok(value);
}
shift += 7;
}
}
impl<'a> Reader<'a> {
pub fn new(bytes: &'a [u8]) -> Self {
Reader { bytes, at: 0 }
}
pub fn position(&self) -> usize {
self.at
}
pub(crate) fn since(&self, start: usize) -> &'a [u8] {
&self.bytes[start..self.at]
}
pub fn remaining(&self) -> usize {
self.bytes.len() - self.at
}
pub fn is_empty(&self) -> bool {
self.remaining() == 0
}
fn invalid(at: usize, problem: &str) -> DecodeError {
DecodeError::of(
&Place::default(),
DecodeErrorKind::Syntax { at },
format!("{problem} at byte {at}"),
)
}
fn limited(at: usize, problem: &str) -> DecodeError {
DecodeError::of(
&Place::default(),
DecodeErrorKind::TooLarge,
format!("{problem} at byte {at}"),
)
}
pub fn byte(&mut self) -> Result<u8, DecodeError> {
let byte = *self
.bytes
.get(self.at)
.ok_or_else(|| Self::invalid(self.at, "ends before its value does"))?;
self.at += 1;
Ok(byte)
}
pub fn bool(&mut self) -> Result<bool, DecodeError> {
let at = self.at;
match self.byte()? {
0 => Ok(false),
1 => Ok(true),
other => Err(Self::invalid(
at,
&format!("has {other} for a Bool, which is 0 or 1,"),
)),
}
}
pub fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
if count > self.remaining() {
return Err(Self::invalid(
self.at,
&format!(
"ends before its value does: {count} bytes are wanted, and {} are left",
self.remaining()
),
));
}
let taken = &self.bytes[self.at..self.at + count];
self.at += count;
Ok(taken)
}
pub fn uint(&mut self) -> Result<u64, DecodeError> {
let start = self.at;
read_uint(
|| self.byte(),
|not| Self::invalid(start, &format!("has a number {not}")),
)
}
pub fn count(&mut self) -> Result<usize, DecodeError> {
let start = self.at;
let value = self.uint()?;
usize::try_from(value).map_err(|_| Self::invalid(start, "has a count this host can't hold"))
}
pub fn signed(&mut self) -> Result<i64, DecodeError> {
let zigzag = self.uint()?;
let half = (zigzag >> 1).cast_signed();
Ok(if zigzag & 1 == 0 { half } else { -half - 1 })
}
pub fn biguint(&mut self, max_bits: u64) -> Result<BigUint, DecodeError> {
let start = self.at;
let most = usize::try_from(max_bits.div_ceil(7).max(1)).unwrap_or(usize::MAX);
let mut digits = Vec::new();
loop {
if digits.len() == most {
return Err(Self::limited(
start,
&format!("has a number larger than {max_bits} bits"),
));
}
let byte = self.byte()?;
digits.push(byte & 0x7f);
if byte & 0x80 == 0 {
break;
}
}
if digits
.last()
.is_some_and(|&last| overlong(digits.len(), last))
{
return Err(Self::invalid(
start,
&format!("has a number {}", NotAUint::Overlong),
));
}
let value = base_128(&digits);
if value.bits() > max_bits {
return Err(Self::limited(
start,
&format!("has a number larger than {max_bits} bits"),
));
}
Ok(value)
}
pub fn int(&mut self, limits: &Limits) -> Result<BigInt, DecodeError> {
let start = self.at;
let too_large = || {
Self::limited(
start,
&format!("has an integer larger than {} bits", limits.int_bits),
)
};
let max_bits = limits.int_bits.saturating_add(1);
if let Some(value) = self.small_int(max_bits)? {
if value.magnitude().bits() > limits.int_bits {
return Err(too_large());
}
return Ok(value);
}
let zigzag = self.biguint(max_bits).map_err(|error| match error.kind {
DecodeErrorKind::TooLarge => too_large(),
DecodeErrorKind::Syntax { .. }
| DecodeErrorKind::Missing
| DecodeErrorKind::Unknown
| DecodeErrorKind::Duplicate
| DecodeErrorKind::Mismatch => error,
})?;
let negative = zigzag.bit(0);
let value = if negative {
BigInt::from_biguint(Sign::Minus, (zigzag + 1u32) >> 1u32)
} else {
BigInt::from_biguint(Sign::Plus, zigzag >> 1u32)
};
if value.magnitude().bits() > limits.int_bits {
return Err(too_large());
}
Ok(value)
}
fn small_int(&mut self, max_bits: u64) -> Result<Option<BigInt>, DecodeError> {
let most = usize::try_from(max_bits.div_ceil(7).max(1))
.unwrap_or(usize::MAX)
.min(9);
let Some(length) = self
.bytes
.get(self.at..)
.unwrap_or_default()
.iter()
.take(most)
.position(|byte| byte & 0x80 == 0)
.map(|last| last + 1)
else {
return Ok(None);
};
let digits = &self.bytes[self.at..self.at + length];
if overlong(length, digits[length - 1]) {
return Err(Self::invalid(
self.at,
&format!("has a number {}", NotAUint::Overlong),
));
}
let zigzag = digits
.iter()
.rev()
.fold(0_u64, |value, byte| (value << 7) | u64::from(byte & 0x7f));
if u64::from(zigzag.bit_width()) > max_bits {
return Ok(None);
}
self.at += length;
let sign = if zigzag & 1 == 1 {
Sign::Minus
} else {
Sign::Plus
};
let magnitude = if zigzag & 1 == 1 {
(zigzag >> 1) + 1
} else {
zigzag >> 1
};
Ok(Some(BigInt::from_biguint(sign, BigUint::from(magnitude))))
}
pub fn bytes(&mut self, limits: &Limits) -> Result<&'a [u8], DecodeError> {
let start = self.at;
let length = usize::try_from(self.uint()?)
.ok()
.filter(|&length| length <= limits.text_bytes)
.ok_or_else(|| {
Self::limited(
start,
&format!("is longer than {} bytes", limits.text_bytes),
)
})?;
self.take(length)
}
pub fn text(&mut self, limits: &Limits) -> Result<&'a str, DecodeError> {
let start = self.at;
let bytes = self.bytes(limits)?;
std::str::from_utf8(bytes).map_err(|_| Self::invalid(start, "has a text that is not UTF-8"))
}
}
pub fn crc32c(bytes: &[u8]) -> u32 {
Crc32c::new().update(bytes).finish()
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Crc32c(u32);
const TABLE: [u32; 256] = {
let mut table = [0u32; 256];
let mut index = 0;
let mut byte: u32 = 0;
while index < 256 {
let mut crc = byte;
let mut bit = 0;
while bit < 8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0x82F6_3B78
} else {
crc >> 1
};
bit += 1;
}
table[index] = crc;
index += 1;
byte += 1;
}
table
};
#[expect(
clippy::as_conversions,
reason = "a byte masked from a u32 always fits a usize, and a const has no From"
)]
const TABLES: [[u32; 256]; 8] = {
let mut tables = [TABLE; 8];
let mut k = 1;
while k < 8 {
let mut index = 0;
while index < 256 {
let previous = tables[k - 1][index];
tables[k][index] = (previous >> 8) ^ TABLE[(previous & 0xFF) as usize];
index += 1;
}
k += 1;
}
tables
};
impl Crc32c {
pub fn new() -> Self {
Crc32c(!0)
}
pub fn update(&mut self, bytes: &[u8]) -> &mut Self {
let (blocks, bytes) = bytes.as_chunks::<{ 3 * LANE }>();
for block in blocks {
let (first, rest) = block.split_at(LANE);
let (second, third) = rest.split_at(LANE);
let (mut a, mut b, mut c) = (self.0, 0, 0);
let lanes = first.as_chunks::<8>().0.iter();
let lanes = lanes
.zip(second.as_chunks::<8>().0)
.zip(third.as_chunks::<8>().0);
for ((x, y), z) in lanes {
a = step(a, *x);
b = step(b, *y);
c = step(c, *z);
}
self.0 = multiply(LANE_SHIFT, multiply(LANE_SHIFT, a) ^ b) ^ c;
}
let (words, rest) = bytes.as_chunks::<8>();
for word in words {
self.0 = step(self.0, *word);
}
for byte in rest {
let [low, ..] = self.0.to_le_bytes();
let index = usize::from(low ^ byte);
self.0 = (self.0 >> 8) ^ TABLE[index];
}
self
}
pub fn finish(&self) -> u32 {
!self.0
}
pub fn raw() -> Self {
Crc32c(0)
}
#[must_use]
pub fn xor(&self, other: &Crc32c) -> Self {
Crc32c(self.0 ^ other.0)
}
#[must_use]
pub fn zeros(&self, count: u64) -> Self {
let mut register = self.0;
let mut count = count;
for power in POWERS {
if count == 0 {
break;
}
if count & 1 == 1 {
register = multiply(power, register);
}
count >>= 1;
}
Crc32c(register)
}
}
fn step(register: u32, word: [u8; 8]) -> u32 {
let [a, b, c, d] = register.to_le_bytes();
let at = |k: usize, byte: u8| TABLES[k][usize::from(byte)];
at(7, a ^ word[0])
^ at(6, b ^ word[1])
^ at(5, c ^ word[2])
^ at(4, d ^ word[3])
^ at(3, word[4])
^ at(2, word[5])
^ at(1, word[6])
^ at(0, word[7])
}
const X_TO_THE_8: u32 = 1 << 23;
const LANE_BITS: usize = 8;
const LANE: usize = 1 << LANE_BITS;
const LANE_SHIFT: u32 = POWERS[LANE_BITS];
const POWERS: [u32; 64] = {
let mut powers = [X_TO_THE_8; 64];
let mut k = 1;
while k < 64 {
powers[k] = multiply(powers[k - 1], powers[k - 1]);
k += 1;
}
powers
};
const fn multiply(mut a: u32, mut b: u32) -> u32 {
let mut product = 0;
while a != 0 {
if a & (1 << 31) != 0 {
product ^= b;
}
b = (b >> 1) ^ (0x82F6_3B78 & (b & 1).wrapping_neg());
a <<= 1;
}
product
}
impl Default for Crc32c {
fn default() -> Self {
Crc32c::new()
}
}