Skip to main content

flow_abi/
bytes.rs

1//! The byte primitives every binary form is built from (`abi.md`, *Numbers
2//! and text*): numbers, signed numbers, texts and runs of bytes, a cursor
3//! that reads them back refusing every spelling but the one, and the CRC-32C
4//! check history's commits carry (`trace.md`, *Writing and durability*).
5//!
6//! A **number** is written seven bits to a byte from the least significant
7//! up, every byte but the last with its high bit set, in the fewest bytes
8//! that hold it. A **signed number** `v` is the number `2v` when `v` is zero
9//! or more and `-2v - 1` when it is less. A **text** is a number, its length
10//! in bytes, then that many bytes of UTF-8.
11
12use num_bigint::{BigInt, BigUint, Sign};
13
14use crate::error::{DecodeError, DecodeErrorKind, Place};
15use crate::limits::Limits;
16
17/// `n`, a size or count, as a number to write: every `usize` this crate is
18/// built for fits 64 bits.
19///
20/// # Panics
21///
22/// Only where a `usize` is wider than 64 bits, which no target this crate
23/// is built for has.
24pub fn wide(n: usize) -> u64 {
25    u64::try_from(n).expect("a usize fits 64 bits")
26}
27
28/// `n`, a declaration's or parameter's number, as an index: every `usize`
29/// this crate is built for holds 32 bits.
30pub(crate) fn index(n: u32) -> usize {
31    usize::try_from(n).expect("a u32 fits a usize")
32}
33
34/// The constructor numbers of std's `Option` in the value encoding: `None`
35/// and `Some`, in the order std declares them (`abi.md`, *Each type*).
36pub(crate) const NONE: u64 = 0;
37pub(crate) const SOME: u64 = 1;
38
39/// The constructor numbers of std's `Result` in the value encoding: `Ok`
40/// and `Err`, in the order std declares them.
41pub(crate) const OK: u64 = 0;
42pub(crate) const ERR: u64 = 1;
43
44/// The number whose base-128 digits, least significant first, are `digits`.
45fn base_128(digits: &[u8]) -> BigUint {
46    BigUint::from_radix_le(digits, 128).expect("every digit read is below 128")
47}
48
49// === Writing ================================================================
50
51/// Writes the number `value`.
52pub 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
60/// The low seven bits of `value`.
61fn low_seven(value: u64) -> u8 {
62    u8::try_from(value & 0x7f).expect("seven bits fit a byte")
63}
64
65/// Writes the number `value`, of any size.
66pub fn write_biguint(out: &mut Vec<u8>, value: &BigUint) {
67    if value.bits() == 0 {
68        out.push(0);
69        return;
70    }
71    // Base-128 digits, least significant first: exactly the groups of
72    // seven bits the number is written in, the last one nonzero.
73    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
83/// Writes the signed number `value`, of any size.
84pub 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
104/// Writes the signed number `value`.
105pub fn write_signed(out: &mut Vec<u8>, value: i64) {
106    // `2v` for `v` of zero or more and `-2v - 1` below: the sign moved to
107    // the lowest bit, which every 64-bit value fits.
108    let zigzag = (value << 1) ^ (value >> 63);
109    write_uint(out, zigzag.cast_unsigned());
110}
111
112/// Writes `text`: its length in bytes, then its UTF-8.
113pub fn write_text(out: &mut Vec<u8>, text: &str) {
114    write_bytes(out, text.as_bytes());
115}
116
117/// Writes `bytes`: their length, then the bytes.
118pub 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// === Reading ================================================================
124
125/// A cursor over bytes that reads what the writers above write, and refuses
126/// every other spelling: a number in more bytes than it needs, a text that
127/// is not UTF-8, and anything that runs past the end.
128///
129/// A refusal is a [`DecodeError`] with an empty path, which says at which
130/// byte it happened; whoever reads a value at a type puts its path in.
131#[derive(Clone, Debug)]
132pub struct Reader<'a> {
133    bytes: &'a [u8],
134    at: usize,
135}
136
137/// Why bytes are not a number of at most 64 bits in its fewest bytes.
138#[derive(Clone, Copy, PartialEq, Eq, Debug)]
139pub enum NotAUint {
140    /// It does not fit 64 bits.
141    TooLarge,
142    /// It is written in more bytes than it needs.
143    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
155/// Whether a number of `digits` base-128 digits, the last `last`, is written
156/// in more bytes than it needs: the one rule every number of the encoding is
157/// held to.
158fn overlong(digits: usize, last: u8) -> bool {
159    digits > 1 && last == 0
160}
161
162/// Reads a number of at most 64 bits in its fewest bytes, taking its bytes
163/// one at a time from `next`: every number of at most 64 bits, and every
164/// frame's length, is read here.
165///
166/// # Errors
167///
168/// What `next` fails with, and what `refuse` makes of bytes that are not
169/// such a number. A refusal comes at the byte that shows it, so `next` has
170/// given no byte past that one.
171pub 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    /// A cursor at the first of `bytes`.
198    pub fn new(bytes: &'a [u8]) -> Self {
199        Reader { bytes, at: 0 }
200    }
201
202    /// How many bytes have been read.
203    pub fn position(&self) -> usize {
204        self.at
205    }
206
207    /// The bytes read since `start`, a position this cursor passed.
208    pub(crate) fn since(&self, start: usize) -> &'a [u8] {
209        &self.bytes[start..self.at]
210    }
211
212    /// How many bytes are left.
213    pub fn remaining(&self) -> usize {
214        self.bytes.len() - self.at
215    }
216
217    /// Whether every byte has been read.
218    pub fn is_empty(&self) -> bool {
219        self.remaining() == 0
220    }
221
222    /// A refusal of invalid data at byte `at`.
223    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    /// A refusal at byte `at` because a value passes a limit.
232    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    /// The next byte.
241    ///
242    /// # Errors
243    ///
244    /// A [`DecodeError`] when no bytes are left.
245    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    /// The next `Bool`: one byte, `0` or `1`.
255    ///
256    /// # Errors
257    ///
258    /// A [`DecodeError`] when no bytes are left or the byte is another.
259    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    /// The next `count` bytes.
272    ///
273    /// # Errors
274    ///
275    /// A [`DecodeError`] when fewer than `count` bytes are left.
276    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    /// The next number, which must fit 64 bits.
292    ///
293    /// # Errors
294    ///
295    /// A [`DecodeError`] when the input ends inside the number, it takes
296    /// more bytes than it needs, or it does not fit 64 bits.
297    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    /// The next number as an index or length: one that fits this host's
306    /// addresses.
307    ///
308    /// # Errors
309    ///
310    /// As [`Reader::uint`], and when the number does not fit a `usize`.
311    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    /// The next signed number, which must fit 64 bits.
318    ///
319    /// # Errors
320    ///
321    /// As [`Reader::uint`].
322    pub fn signed(&mut self) -> Result<i64, DecodeError> {
323        let zigzag = self.uint()?;
324        // Shifted right once, it holds 63 bits, which fit an `i64` as they are.
325        let half = (zigzag >> 1).cast_signed();
326        Ok(if zigzag & 1 == 0 { half } else { -half - 1 })
327    }
328
329    /// The next number, of any size up to `max_bits` bits. A longer one is
330    /// refused as a limit, as soon as it is known to be longer and before
331    /// the rest of it is read.
332    ///
333    /// # Errors
334    ///
335    /// A [`DecodeError`] when the input ends inside the number or it takes
336    /// more bytes than it needs, and a limit when it is longer than
337    /// `max_bits` bits.
338    pub fn biguint(&mut self, max_bits: u64) -> Result<BigUint, DecodeError> {
339        let start = self.at;
340        // A number of `b` bits, `b` at least 1, takes `ceil(b / 7)` bytes.
341        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    /// The next signed number, of any size, refused as a limit when its
376    /// magnitude takes more than [`Limits::int_bits`].
377    ///
378    /// # Errors
379    ///
380    /// As [`Reader::biguint`], with [`Limits::int_bits`] as its bound.
381    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        // The signed number of a magnitude of `b` bits takes `b + 1`.
390        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    /// The next integer when it is written in the bytes a `u64` holds and
418    /// within the `max_bits` [`Reader::biguint`] allows, read without a big
419    /// number, as nearly every integer is; `None`, reading nothing, for any
420    /// other, which [`Reader::biguint`] then reads and refuses as it does.
421    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    /// The next run of bytes, its length first, refused as a limit when it
465    /// is longer than [`Limits::text_bytes`].
466    ///
467    /// # Errors
468    ///
469    /// A [`DecodeError`] when the length does not read, is past the limit,
470    /// or is more than the bytes left.
471    pub fn bytes(&mut self, limits: &Limits) -> Result<&'a [u8], DecodeError> {
472        let start = self.at;
473        // A length past the limit, which is a `usize`, may not fit one.
474        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    /// The next text, its length first: valid UTF-8, and refused as a limit
487    /// when it is longer than [`Limits::text_bytes`].
488    ///
489    /// # Errors
490    ///
491    /// As [`Reader::bytes`], and when the bytes are not UTF-8.
492    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
499// === CRC-32C ================================================================
500
501/// The CRC-32C (Castagnoli) of `bytes`.
502pub fn crc32c(bytes: &[u8]) -> u32 {
503    Crc32c::new().update(bytes).finish()
504}
505
506/// A CRC-32C (Castagnoli) taken over bytes given a piece at a time: the
507/// reflected polynomial `0x82F63B78`, starting from all ones and ending
508/// with them flipped, so `crc32c(b"123456789")` is `0xE3069283`.
509#[derive(Clone, Copy, PartialEq, Eq, Debug)]
510pub struct Crc32c(u32);
511
512/// The remainder of each byte, one table lookup per byte.
513const 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/// The tables that take eight bytes a step ("slicing by 8"): `TABLES[k]`
536/// is the remainder of a byte followed by `k` zero bytes.
537#[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    /// The check of no bytes yet.
558    pub fn new() -> Self {
559        Crc32c(!0)
560    }
561
562    /// Takes `bytes` in, after every byte given before.
563    pub fn update(&mut self, bytes: &[u8]) -> &mut Self {
564        // Each block is taken as three lanes at once, each its own register,
565        // whose steps do not wait on each other; the registers are then
566        // joined as [`Crc32c::zeros`] describes, by the power one lane is.
567        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    /// The check of every byte given.
596    pub fn finish(&self) -> u32 {
597        !self.0
598    }
599
600    /// A check taken from nothing: the register at zero, not all ones. The
601    /// register is linear in the bytes, so the register of `a` then `b` is
602    /// [`Crc32c::zeros`] of `a`'s by `b`'s length, exclusive-or'd with
603    /// `b`'s from nothing ([`Crc32c::xor`]). That gives the check over any
604    /// range from two prefixes, with no byte read twice.
605    pub fn raw() -> Self {
606        Crc32c(0)
607    }
608
609    /// This check's register exclusive-or'd with `other`'s.
610    #[must_use]
611    pub fn xor(&self, other: &Crc32c) -> Self {
612        Crc32c(self.0 ^ other.0)
613    }
614
615    /// The register after `count` more zero bytes, in time logarithmic in
616    /// `count`: multiplying by x^(8·count) modulo the polynomial.
617    #[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
634/// The register after the eight bytes of `word`.
635fn 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
648/// x^8 in the reflected representation, where `1 << 31` is 1.
649const X_TO_THE_8: u32 = 1 << 23;
650
651/// The bytes in each of the three lanes [`Crc32c::update`] takes a block in:
652/// `2^LANE_BITS`.
653const LANE_BITS: usize = 8;
654const LANE: usize = 1 << LANE_BITS;
655
656/// x^(8·LANE), which a lane's register is multiplied by to stand before the
657/// next lane's.
658const LANE_SHIFT: u32 = POWERS[LANE_BITS];
659
660/// x^(8·2^k) for each k: what `2^k` zero bytes multiply a register by. One
661/// zero byte is x^8, and each power is the one before squared.
662const 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
672/// `a` times `b` modulo the reflected polynomial, taking `a`'s powers
673/// from the lowest and stopping after its highest.
674const 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}