flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! The byte primitives every binary form is built from (`abi.md`, *Numbers
//! and text*): numbers, signed numbers, texts and runs of bytes, a cursor
//! that reads them back refusing every spelling but the one, and the CRC-32C
//! check history's commits carry (`trace.md`, *Writing and durability*).
//!
//! A **number** is written seven bits to a byte from the least significant
//! up, every byte but the last with its high bit set, in the fewest bytes
//! that hold it. A **signed number** `v` is the number `2v` when `v` is zero
//! or more and `-2v - 1` when it is less. A **text** is a number, its length
//! in bytes, then that many bytes of UTF-8.

use num_bigint::{BigInt, BigUint, Sign};

use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::limits::Limits;

/// `n`, a size or count, as a number to write: every `usize` this crate is
/// built for fits 64 bits.
///
/// # Panics
///
/// Only where a `usize` is wider than 64 bits, which no target this crate
/// is built for has.
pub fn wide(n: usize) -> u64 {
    u64::try_from(n).expect("a usize fits 64 bits")
}

/// `n`, a declaration's or parameter's number, as an index: every `usize`
/// this crate is built for holds 32 bits.
pub(crate) fn index(n: u32) -> usize {
    usize::try_from(n).expect("a u32 fits a usize")
}

/// The constructor numbers of std's `Option` in the value encoding: `None`
/// and `Some`, in the order std declares them (`abi.md`, *Each type*).
pub(crate) const NONE: u64 = 0;
pub(crate) const SOME: u64 = 1;

/// The constructor numbers of std's `Result` in the value encoding: `Ok`
/// and `Err`, in the order std declares them.
pub(crate) const OK: u64 = 0;
pub(crate) const ERR: u64 = 1;

/// The number whose base-128 digits, least significant first, are `digits`.
fn base_128(digits: &[u8]) -> BigUint {
    BigUint::from_radix_le(digits, 128).expect("every digit read is below 128")
}

// === Writing ================================================================

/// Writes the number `value`.
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));
}

/// The low seven bits of `value`.
fn low_seven(value: u64) -> u8 {
    u8::try_from(value & 0x7f).expect("seven bits fit a byte")
}

/// Writes the number `value`, of any size.
pub fn write_biguint(out: &mut Vec<u8>, value: &BigUint) {
    if value.bits() == 0 {
        out.push(0);
        return;
    }
    // Base-128 digits, least significant first: exactly the groups of
    // seven bits the number is written in, the last one nonzero.
    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 }),
    );
}

/// Writes the signed number `value`, of any size.
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);
}

/// Writes the signed number `value`.
pub fn write_signed(out: &mut Vec<u8>, value: i64) {
    // `2v` for `v` of zero or more and `-2v - 1` below: the sign moved to
    // the lowest bit, which every 64-bit value fits.
    let zigzag = (value << 1) ^ (value >> 63);
    write_uint(out, zigzag.cast_unsigned());
}

/// Writes `text`: its length in bytes, then its UTF-8.
pub fn write_text(out: &mut Vec<u8>, text: &str) {
    write_bytes(out, text.as_bytes());
}

/// Writes `bytes`: their length, then the bytes.
pub fn write_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
    write_uint(out, wide(bytes.len()));
    out.extend_from_slice(bytes);
}

// === Reading ================================================================

/// A cursor over bytes that reads what the writers above write, and refuses
/// every other spelling: a number in more bytes than it needs, a text that
/// is not UTF-8, and anything that runs past the end.
///
/// A refusal is a [`DecodeError`] with an empty path, which says at which
/// byte it happened; whoever reads a value at a type puts its path in.
#[derive(Clone, Debug)]
pub struct Reader<'a> {
    bytes: &'a [u8],
    at: usize,
}

/// Why bytes are not a number of at most 64 bits in its fewest bytes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NotAUint {
    /// It does not fit 64 bits.
    TooLarge,
    /// It is written in more bytes than it needs.
    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",
        })
    }
}

/// Whether a number of `digits` base-128 digits, the last `last`, is written
/// in more bytes than it needs: the one rule every number of the encoding is
/// held to.
fn overlong(digits: usize, last: u8) -> bool {
    digits > 1 && last == 0
}

/// Reads a number of at most 64 bits in its fewest bytes, taking its bytes
/// one at a time from `next`: every number of at most 64 bits, and every
/// frame's length, is read here.
///
/// # Errors
///
/// What `next` fails with, and what `refuse` makes of bytes that are not
/// such a number. A refusal comes at the byte that shows it, so `next` has
/// given no byte past that one.
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> {
    /// A cursor at the first of `bytes`.
    pub fn new(bytes: &'a [u8]) -> Self {
        Reader { bytes, at: 0 }
    }

    /// How many bytes have been read.
    pub fn position(&self) -> usize {
        self.at
    }

    /// The bytes read since `start`, a position this cursor passed.
    pub(crate) fn since(&self, start: usize) -> &'a [u8] {
        &self.bytes[start..self.at]
    }

    /// How many bytes are left.
    pub fn remaining(&self) -> usize {
        self.bytes.len() - self.at
    }

    /// Whether every byte has been read.
    pub fn is_empty(&self) -> bool {
        self.remaining() == 0
    }

    /// A refusal of invalid data at byte `at`.
    fn invalid(at: usize, problem: &str) -> DecodeError {
        DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Syntax { at },
            format!("{problem} at byte {at}"),
        )
    }

    /// A refusal at byte `at` because a value passes a limit.
    fn limited(at: usize, problem: &str) -> DecodeError {
        DecodeError::of(
            &Place::default(),
            DecodeErrorKind::TooLarge,
            format!("{problem} at byte {at}"),
        )
    }

    /// The next byte.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when no bytes are left.
    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)
    }

    /// The next `Bool`: one byte, `0` or `1`.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when no bytes are left or the byte is another.
    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,"),
            )),
        }
    }

    /// The next `count` bytes.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when fewer than `count` bytes are left.
    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)
    }

    /// The next number, which must fit 64 bits.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the input ends inside the number, it takes
    /// more bytes than it needs, or it does not fit 64 bits.
    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}")),
        )
    }

    /// The next number as an index or length: one that fits this host's
    /// addresses.
    ///
    /// # Errors
    ///
    /// As [`Reader::uint`], and when the number does not fit a `usize`.
    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"))
    }

    /// The next signed number, which must fit 64 bits.
    ///
    /// # Errors
    ///
    /// As [`Reader::uint`].
    pub fn signed(&mut self) -> Result<i64, DecodeError> {
        let zigzag = self.uint()?;
        // Shifted right once, it holds 63 bits, which fit an `i64` as they are.
        let half = (zigzag >> 1).cast_signed();
        Ok(if zigzag & 1 == 0 { half } else { -half - 1 })
    }

    /// The next number, of any size up to `max_bits` bits. A longer one is
    /// refused as a limit, as soon as it is known to be longer and before
    /// the rest of it is read.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the input ends inside the number or it takes
    /// more bytes than it needs, and a limit when it is longer than
    /// `max_bits` bits.
    pub fn biguint(&mut self, max_bits: u64) -> Result<BigUint, DecodeError> {
        let start = self.at;
        // A number of `b` bits, `b` at least 1, takes `ceil(b / 7)` bytes.
        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)
    }

    /// The next signed number, of any size, refused as a limit when its
    /// magnitude takes more than [`Limits::int_bits`].
    ///
    /// # Errors
    ///
    /// As [`Reader::biguint`], with [`Limits::int_bits`] as its bound.
    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),
            )
        };
        // The signed number of a magnitude of `b` bits takes `b + 1`.
        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)
    }

    /// The next integer when it is written in the bytes a `u64` holds and
    /// within the `max_bits` [`Reader::biguint`] allows, read without a big
    /// number, as nearly every integer is; `None`, reading nothing, for any
    /// other, which [`Reader::biguint`] then reads and refuses as it does.
    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))))
    }

    /// The next run of bytes, its length first, refused as a limit when it
    /// is longer than [`Limits::text_bytes`].
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the length does not read, is past the limit,
    /// or is more than the bytes left.
    pub fn bytes(&mut self, limits: &Limits) -> Result<&'a [u8], DecodeError> {
        let start = self.at;
        // A length past the limit, which is a `usize`, may not fit one.
        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)
    }

    /// The next text, its length first: valid UTF-8, and refused as a limit
    /// when it is longer than [`Limits::text_bytes`].
    ///
    /// # Errors
    ///
    /// As [`Reader::bytes`], and when the bytes are not UTF-8.
    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"))
    }
}

// === CRC-32C ================================================================

/// The CRC-32C (Castagnoli) of `bytes`.
pub fn crc32c(bytes: &[u8]) -> u32 {
    Crc32c::new().update(bytes).finish()
}

/// A CRC-32C (Castagnoli) taken over bytes given a piece at a time: the
/// reflected polynomial `0x82F63B78`, starting from all ones and ending
/// with them flipped, so `crc32c(b"123456789")` is `0xE3069283`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Crc32c(u32);

/// The remainder of each byte, one table lookup per byte.
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
};

/// The tables that take eight bytes a step ("slicing by 8"): `TABLES[k]`
/// is the remainder of a byte followed by `k` zero bytes.
#[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 {
    /// The check of no bytes yet.
    pub fn new() -> Self {
        Crc32c(!0)
    }

    /// Takes `bytes` in, after every byte given before.
    pub fn update(&mut self, bytes: &[u8]) -> &mut Self {
        // Each block is taken as three lanes at once, each its own register,
        // whose steps do not wait on each other; the registers are then
        // joined as [`Crc32c::zeros`] describes, by the power one lane is.
        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
    }

    /// The check of every byte given.
    pub fn finish(&self) -> u32 {
        !self.0
    }

    /// A check taken from nothing: the register at zero, not all ones. The
    /// register is linear in the bytes, so the register of `a` then `b` is
    /// [`Crc32c::zeros`] of `a`'s by `b`'s length, exclusive-or'd with
    /// `b`'s from nothing ([`Crc32c::xor`]). That gives the check over any
    /// range from two prefixes, with no byte read twice.
    pub fn raw() -> Self {
        Crc32c(0)
    }

    /// This check's register exclusive-or'd with `other`'s.
    #[must_use]
    pub fn xor(&self, other: &Crc32c) -> Self {
        Crc32c(self.0 ^ other.0)
    }

    /// The register after `count` more zero bytes, in time logarithmic in
    /// `count`: multiplying by x^(8·count) modulo the polynomial.
    #[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)
    }
}

/// The register after the eight bytes of `word`.
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])
}

/// x^8 in the reflected representation, where `1 << 31` is 1.
const X_TO_THE_8: u32 = 1 << 23;

/// The bytes in each of the three lanes [`Crc32c::update`] takes a block in:
/// `2^LANE_BITS`.
const LANE_BITS: usize = 8;
const LANE: usize = 1 << LANE_BITS;

/// x^(8·LANE), which a lane's register is multiplied by to stand before the
/// next lane's.
const LANE_SHIFT: u32 = POWERS[LANE_BITS];

/// x^(8·2^k) for each k: what `2^k` zero bytes multiply a register by. One
/// zero byte is x^8, and each power is the one before squared.
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
};

/// `a` times `b` modulo the reflected polynomial, taking `a`'s powers
/// from the lowest and stopping after its highest.
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()
    }
}