1use num_bigint::{BigInt, BigUint, Sign};
13
14use crate::error::{DecodeError, DecodeErrorKind, Place};
15use crate::limits::Limits;
16
17pub fn wide(n: usize) -> u64 {
25 u64::try_from(n).expect("a usize fits 64 bits")
26}
27
28pub(crate) fn index(n: u32) -> usize {
31 usize::try_from(n).expect("a u32 fits a usize")
32}
33
34pub(crate) const NONE: u64 = 0;
37pub(crate) const SOME: u64 = 1;
38
39pub(crate) const OK: u64 = 0;
42pub(crate) const ERR: u64 = 1;
43
44fn base_128(digits: &[u8]) -> BigUint {
46 BigUint::from_radix_le(digits, 128).expect("every digit read is below 128")
47}
48
49pub fn write_uint(out: &mut Vec<u8>, mut value: u64) {
53 while value >= 0x80 {
54 out.push(low_seven(value) | 0x80);
55 value >>= 7;
56 }
57 out.push(low_seven(value));
58}
59
60fn low_seven(value: u64) -> u8 {
62 u8::try_from(value & 0x7f).expect("seven bits fit a byte")
63}
64
65pub fn write_biguint(out: &mut Vec<u8>, value: &BigUint) {
67 if value.bits() == 0 {
68 out.push(0);
69 return;
70 }
71 let digits = value.to_radix_le(128);
74 let last = digits.len() - 1;
75 out.extend(
76 digits
77 .iter()
78 .enumerate()
79 .map(|(at, digit)| if at == last { *digit } else { digit | 0x80 }),
80 );
81}
82
83pub fn write_int(out: &mut Vec<u8>, value: &BigInt) {
85 let magnitude = value.magnitude();
86 if magnitude.bits() < 64 {
87 let small = magnitude.iter_u64_digits().next().unwrap_or(0) << 1;
88 write_uint(
89 out,
90 match value.sign() {
91 Sign::Minus => small - 1,
92 Sign::NoSign | Sign::Plus => small,
93 },
94 );
95 return;
96 }
97 let zigzag = match value.sign() {
98 Sign::Minus => (magnitude << 1u32) - 1u32,
99 Sign::NoSign | Sign::Plus => magnitude << 1u32,
100 };
101 write_biguint(out, &zigzag);
102}
103
104pub fn write_signed(out: &mut Vec<u8>, value: i64) {
106 let zigzag = (value << 1) ^ (value >> 63);
109 write_uint(out, zigzag.cast_unsigned());
110}
111
112pub fn write_text(out: &mut Vec<u8>, text: &str) {
114 write_bytes(out, text.as_bytes());
115}
116
117pub fn write_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
119 write_uint(out, wide(bytes.len()));
120 out.extend_from_slice(bytes);
121}
122
123#[derive(Clone, Debug)]
132pub struct Reader<'a> {
133 bytes: &'a [u8],
134 at: usize,
135}
136
137#[derive(Clone, Copy, PartialEq, Eq, Debug)]
139pub enum NotAUint {
140 TooLarge,
142 Overlong,
144}
145
146impl std::fmt::Display for NotAUint {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 f.write_str(match self {
149 NotAUint::TooLarge => "larger than 64 bits",
150 NotAUint::Overlong => "written in more bytes than it needs",
151 })
152 }
153}
154
155fn overlong(digits: usize, last: u8) -> bool {
159 digits > 1 && last == 0
160}
161
162pub fn read_uint<E>(
172 mut next: impl FnMut() -> Result<u8, E>,
173 refuse: impl FnOnce(NotAUint) -> E,
174) -> Result<u64, E> {
175 let mut value = 0u64;
176 let mut shift = 0u32;
177 let mut digits = 0usize;
178 loop {
179 let byte = next()?;
180 digits += 1;
181 let low = u64::from(byte & 0x7f);
182 if shift > 63 || (shift == 63 && low > 1) {
183 return Err(refuse(NotAUint::TooLarge));
184 }
185 value |= low << shift;
186 if byte & 0x80 == 0 {
187 if overlong(digits, byte) {
188 return Err(refuse(NotAUint::Overlong));
189 }
190 return Ok(value);
191 }
192 shift += 7;
193 }
194}
195
196impl<'a> Reader<'a> {
197 pub fn new(bytes: &'a [u8]) -> Self {
199 Reader { bytes, at: 0 }
200 }
201
202 pub fn position(&self) -> usize {
204 self.at
205 }
206
207 pub(crate) fn since(&self, start: usize) -> &'a [u8] {
209 &self.bytes[start..self.at]
210 }
211
212 pub fn remaining(&self) -> usize {
214 self.bytes.len() - self.at
215 }
216
217 pub fn is_empty(&self) -> bool {
219 self.remaining() == 0
220 }
221
222 fn invalid(at: usize, problem: &str) -> DecodeError {
224 DecodeError::of(
225 &Place::default(),
226 DecodeErrorKind::Syntax { at },
227 format!("{problem} at byte {at}"),
228 )
229 }
230
231 fn limited(at: usize, problem: &str) -> DecodeError {
233 DecodeError::of(
234 &Place::default(),
235 DecodeErrorKind::TooLarge,
236 format!("{problem} at byte {at}"),
237 )
238 }
239
240 pub fn byte(&mut self) -> Result<u8, DecodeError> {
246 let byte = *self
247 .bytes
248 .get(self.at)
249 .ok_or_else(|| Self::invalid(self.at, "ends before its value does"))?;
250 self.at += 1;
251 Ok(byte)
252 }
253
254 pub fn bool(&mut self) -> Result<bool, DecodeError> {
260 let at = self.at;
261 match self.byte()? {
262 0 => Ok(false),
263 1 => Ok(true),
264 other => Err(Self::invalid(
265 at,
266 &format!("has {other} for a Bool, which is 0 or 1,"),
267 )),
268 }
269 }
270
271 pub fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
277 if count > self.remaining() {
278 return Err(Self::invalid(
279 self.at,
280 &format!(
281 "ends before its value does: {count} bytes are wanted, and {} are left",
282 self.remaining()
283 ),
284 ));
285 }
286 let taken = &self.bytes[self.at..self.at + count];
287 self.at += count;
288 Ok(taken)
289 }
290
291 pub fn uint(&mut self) -> Result<u64, DecodeError> {
298 let start = self.at;
299 read_uint(
300 || self.byte(),
301 |not| Self::invalid(start, &format!("has a number {not}")),
302 )
303 }
304
305 pub fn count(&mut self) -> Result<usize, DecodeError> {
312 let start = self.at;
313 let value = self.uint()?;
314 usize::try_from(value).map_err(|_| Self::invalid(start, "has a count this host can't hold"))
315 }
316
317 pub fn signed(&mut self) -> Result<i64, DecodeError> {
323 let zigzag = self.uint()?;
324 let half = (zigzag >> 1).cast_signed();
326 Ok(if zigzag & 1 == 0 { half } else { -half - 1 })
327 }
328
329 pub fn biguint(&mut self, max_bits: u64) -> Result<BigUint, DecodeError> {
339 let start = self.at;
340 let most = usize::try_from(max_bits.div_ceil(7).max(1)).unwrap_or(usize::MAX);
342 let mut digits = Vec::new();
343 loop {
344 if digits.len() == most {
345 return Err(Self::limited(
346 start,
347 &format!("has a number larger than {max_bits} bits"),
348 ));
349 }
350 let byte = self.byte()?;
351 digits.push(byte & 0x7f);
352 if byte & 0x80 == 0 {
353 break;
354 }
355 }
356 if digits
357 .last()
358 .is_some_and(|&last| overlong(digits.len(), last))
359 {
360 return Err(Self::invalid(
361 start,
362 &format!("has a number {}", NotAUint::Overlong),
363 ));
364 }
365 let value = base_128(&digits);
366 if value.bits() > max_bits {
367 return Err(Self::limited(
368 start,
369 &format!("has a number larger than {max_bits} bits"),
370 ));
371 }
372 Ok(value)
373 }
374
375 pub fn int(&mut self, limits: &Limits) -> Result<BigInt, DecodeError> {
382 let start = self.at;
383 let too_large = || {
384 Self::limited(
385 start,
386 &format!("has an integer larger than {} bits", limits.int_bits),
387 )
388 };
389 let max_bits = limits.int_bits.saturating_add(1);
391 if let Some(value) = self.small_int(max_bits)? {
392 if value.magnitude().bits() > limits.int_bits {
393 return Err(too_large());
394 }
395 return Ok(value);
396 }
397 let zigzag = self.biguint(max_bits).map_err(|error| match error.kind {
398 DecodeErrorKind::TooLarge => too_large(),
399 DecodeErrorKind::Syntax { .. }
400 | DecodeErrorKind::Missing
401 | DecodeErrorKind::Unknown
402 | DecodeErrorKind::Duplicate
403 | DecodeErrorKind::Mismatch => error,
404 })?;
405 let negative = zigzag.bit(0);
406 let value = if negative {
407 BigInt::from_biguint(Sign::Minus, (zigzag + 1u32) >> 1u32)
408 } else {
409 BigInt::from_biguint(Sign::Plus, zigzag >> 1u32)
410 };
411 if value.magnitude().bits() > limits.int_bits {
412 return Err(too_large());
413 }
414 Ok(value)
415 }
416
417 fn small_int(&mut self, max_bits: u64) -> Result<Option<BigInt>, DecodeError> {
422 let most = usize::try_from(max_bits.div_ceil(7).max(1))
423 .unwrap_or(usize::MAX)
424 .min(9);
425 let Some(length) = self
426 .bytes
427 .get(self.at..)
428 .unwrap_or_default()
429 .iter()
430 .take(most)
431 .position(|byte| byte & 0x80 == 0)
432 .map(|last| last + 1)
433 else {
434 return Ok(None);
435 };
436 let digits = &self.bytes[self.at..self.at + length];
437 if overlong(length, digits[length - 1]) {
438 return Err(Self::invalid(
439 self.at,
440 &format!("has a number {}", NotAUint::Overlong),
441 ));
442 }
443 let zigzag = digits
444 .iter()
445 .rev()
446 .fold(0_u64, |value, byte| (value << 7) | u64::from(byte & 0x7f));
447 if u64::from(zigzag.bit_width()) > max_bits {
448 return Ok(None);
449 }
450 self.at += length;
451 let sign = if zigzag & 1 == 1 {
452 Sign::Minus
453 } else {
454 Sign::Plus
455 };
456 let magnitude = if zigzag & 1 == 1 {
457 (zigzag >> 1) + 1
458 } else {
459 zigzag >> 1
460 };
461 Ok(Some(BigInt::from_biguint(sign, BigUint::from(magnitude))))
462 }
463
464 pub fn bytes(&mut self, limits: &Limits) -> Result<&'a [u8], DecodeError> {
472 let start = self.at;
473 let length = usize::try_from(self.uint()?)
475 .ok()
476 .filter(|&length| length <= limits.text_bytes)
477 .ok_or_else(|| {
478 Self::limited(
479 start,
480 &format!("is longer than {} bytes", limits.text_bytes),
481 )
482 })?;
483 self.take(length)
484 }
485
486 pub fn text(&mut self, limits: &Limits) -> Result<&'a str, DecodeError> {
493 let start = self.at;
494 let bytes = self.bytes(limits)?;
495 std::str::from_utf8(bytes).map_err(|_| Self::invalid(start, "has a text that is not UTF-8"))
496 }
497}
498
499pub fn crc32c(bytes: &[u8]) -> u32 {
503 Crc32c::new().update(bytes).finish()
504}
505
506#[derive(Clone, Copy, PartialEq, Eq, Debug)]
510pub struct Crc32c(u32);
511
512const TABLE: [u32; 256] = {
514 let mut table = [0u32; 256];
515 let mut index = 0;
516 let mut byte: u32 = 0;
517 while index < 256 {
518 let mut crc = byte;
519 let mut bit = 0;
520 while bit < 8 {
521 crc = if crc & 1 == 1 {
522 (crc >> 1) ^ 0x82F6_3B78
523 } else {
524 crc >> 1
525 };
526 bit += 1;
527 }
528 table[index] = crc;
529 index += 1;
530 byte += 1;
531 }
532 table
533};
534
535#[expect(
538 clippy::as_conversions,
539 reason = "a byte masked from a u32 always fits a usize, and a const has no From"
540)]
541const TABLES: [[u32; 256]; 8] = {
542 let mut tables = [TABLE; 8];
543 let mut k = 1;
544 while k < 8 {
545 let mut index = 0;
546 while index < 256 {
547 let previous = tables[k - 1][index];
548 tables[k][index] = (previous >> 8) ^ TABLE[(previous & 0xFF) as usize];
549 index += 1;
550 }
551 k += 1;
552 }
553 tables
554};
555
556impl Crc32c {
557 pub fn new() -> Self {
559 Crc32c(!0)
560 }
561
562 pub fn update(&mut self, bytes: &[u8]) -> &mut Self {
564 let (blocks, bytes) = bytes.as_chunks::<{ 3 * LANE }>();
568 for block in blocks {
569 let (first, rest) = block.split_at(LANE);
570 let (second, third) = rest.split_at(LANE);
571 let (mut a, mut b, mut c) = (self.0, 0, 0);
572 let lanes = first.as_chunks::<8>().0.iter();
573 let lanes = lanes
574 .zip(second.as_chunks::<8>().0)
575 .zip(third.as_chunks::<8>().0);
576 for ((x, y), z) in lanes {
577 a = step(a, *x);
578 b = step(b, *y);
579 c = step(c, *z);
580 }
581 self.0 = multiply(LANE_SHIFT, multiply(LANE_SHIFT, a) ^ b) ^ c;
582 }
583 let (words, rest) = bytes.as_chunks::<8>();
584 for word in words {
585 self.0 = step(self.0, *word);
586 }
587 for byte in rest {
588 let [low, ..] = self.0.to_le_bytes();
589 let index = usize::from(low ^ byte);
590 self.0 = (self.0 >> 8) ^ TABLE[index];
591 }
592 self
593 }
594
595 pub fn finish(&self) -> u32 {
597 !self.0
598 }
599
600 pub fn raw() -> Self {
606 Crc32c(0)
607 }
608
609 #[must_use]
611 pub fn xor(&self, other: &Crc32c) -> Self {
612 Crc32c(self.0 ^ other.0)
613 }
614
615 #[must_use]
618 pub fn zeros(&self, count: u64) -> Self {
619 let mut register = self.0;
620 let mut count = count;
621 for power in POWERS {
622 if count == 0 {
623 break;
624 }
625 if count & 1 == 1 {
626 register = multiply(power, register);
627 }
628 count >>= 1;
629 }
630 Crc32c(register)
631 }
632}
633
634fn step(register: u32, word: [u8; 8]) -> u32 {
636 let [a, b, c, d] = register.to_le_bytes();
637 let at = |k: usize, byte: u8| TABLES[k][usize::from(byte)];
638 at(7, a ^ word[0])
639 ^ at(6, b ^ word[1])
640 ^ at(5, c ^ word[2])
641 ^ at(4, d ^ word[3])
642 ^ at(3, word[4])
643 ^ at(2, word[5])
644 ^ at(1, word[6])
645 ^ at(0, word[7])
646}
647
648const X_TO_THE_8: u32 = 1 << 23;
650
651const LANE_BITS: usize = 8;
654const LANE: usize = 1 << LANE_BITS;
655
656const LANE_SHIFT: u32 = POWERS[LANE_BITS];
659
660const POWERS: [u32; 64] = {
663 let mut powers = [X_TO_THE_8; 64];
664 let mut k = 1;
665 while k < 64 {
666 powers[k] = multiply(powers[k - 1], powers[k - 1]);
667 k += 1;
668 }
669 powers
670};
671
672const fn multiply(mut a: u32, mut b: u32) -> u32 {
675 let mut product = 0;
676 while a != 0 {
677 if a & (1 << 31) != 0 {
678 product ^= b;
679 }
680 b = (b >> 1) ^ (0x82F6_3B78 & (b & 1).wrapping_neg());
681 a <<= 1;
682 }
683 product
684}
685
686impl Default for Crc32c {
687 fn default() -> Self {
688 Crc32c::new()
689 }
690}