Skip to main content

odradek_protocol/
records.rs

1//! Record batch (v2) encoding — the record set carried in Produce and
2//! Fetch `records` fields.
3//!
4//! This format predates and sits below the message schemas: a record set
5//! is an opaque `BYTES` field there, holding a sequence of batches. Each
6//! batch is CRC-protected (CRC-32C over everything after the crc field)
7//! and may hold its records compressed.
8//!
9//! Compressed batches are kept as raw bytes rather than decompressed:
10//! decoding then re-encoding one is byte-identical, which is what proxying
11//! requires, and it keeps this crate free of compression dependencies. The
12//! same applies to unknown compression codecs from the future.
13//!
14//! # Retention pins the source buffer
15//!
16//! A decoded key, value, or compressed payload is a refcounted slice of
17//! the buffer it was decoded from, not a copy — that is the point (see
18//! [`crate`] docs). The consequence is that holding on to *any* of them
19//! holds on to *all* of it: keep one 10-byte value out of a 64 MiB fetch
20//! response and the whole 64 MiB stays resident until it drops. For
21//! anything that outlives the response — a cache, a retry queue, a
22//! channel into another task — copy it out with
23//! `Bytes::copy_from_slice(&value)` and let the frame go.
24//!
25//! # Allocation is bounded
26//!
27//! Record and header counts are attacker-controlled and a decoded
28//! [`Record`] is ~15x the smallest wire form that can ask for one, so
29//! every decode here spends against a [`Budget`]; the `_with_limits`
30//! entry points take the policy, the plain ones apply the default. See
31//! [`crate::budget`].
32
33use bytes::{Buf, BufMut, Bytes, BytesMut};
34
35use crate::budget::{Budget, Limits};
36use crate::error::{DecodeError, EncodeError};
37use crate::wire;
38
39/// The only record batch magic this crate speaks. Magic 0 and 1 (the
40/// pre-0.11 "message set" formats) were removed from brokers in Kafka 4.0.
41pub const MAGIC: i8 = 2;
42
43/// Byte length of a batch's fields from `partition_leader_epoch` through
44/// the record count — everything `batch_length` counts except the records
45/// themselves.
46const BATCH_OVERHEAD: usize = 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4 + 4;
47
48/// Compression codec, from the low three bits of batch attributes.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Compression {
51    None,
52    Gzip,
53    Snappy,
54    Lz4,
55    Zstd,
56    /// A codec this crate does not know. Carried losslessly: the batch's
57    /// payload stays raw and re-encodes byte-identically.
58    Unknown(u8),
59}
60
61impl Compression {
62    fn from_attributes(attributes: i16) -> Compression {
63        match (attributes & 0x7) as u8 {
64            0 => Compression::None,
65            1 => Compression::Gzip,
66            2 => Compression::Snappy,
67            3 => Compression::Lz4,
68            4 => Compression::Zstd,
69            other => Compression::Unknown(other),
70        }
71    }
72
73    /// The attribute bits that select this codec — the inverse of
74    /// `Compression::from_attributes`, kept beside it so a new codec
75    /// number cannot land in one direction only.
76    pub fn attribute_bits(self) -> i16 {
77        match self {
78            Compression::None => 0,
79            Compression::Gzip => 1,
80            Compression::Snappy => 2,
81            Compression::Lz4 => 3,
82            Compression::Zstd => 4,
83            Compression::Unknown(bits) => i16::from(bits),
84        }
85    }
86}
87
88/// One record batch (magic 2).
89///
90/// `attributes` is kept raw for lossless round-trips; the typed accessors
91/// read its bits. There is no `magic` or `crc` field: magic is always
92/// [`MAGIC`] and the crc is computed on encode and verified on decode.
93#[derive(Debug, Clone, PartialEq, Eq, Default)]
94pub struct RecordBatch {
95    pub base_offset: i64,
96    pub partition_leader_epoch: i32,
97    pub attributes: i16,
98    pub last_offset_delta: i32,
99    pub base_timestamp: i64,
100    pub max_timestamp: i64,
101    pub producer_id: i64,
102    pub producer_epoch: i16,
103    pub base_sequence: i32,
104    pub records: Records,
105}
106
107/// The records of a batch: parsed when uncompressed, raw otherwise.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum Records {
110    /// Uncompressed records, fully parsed.
111    Plain(Vec<Record>),
112    /// Compressed records: the wire record count and the compressed bytes
113    /// exactly as they appeared after it.
114    Compressed { count: i32, payload: Bytes },
115}
116
117impl Default for Records {
118    fn default() -> Self {
119        Records::Plain(Vec::new())
120    }
121}
122
123/// One record within an uncompressed batch.
124///
125/// `key` and `value` are refcounted slices of the buffer this record was
126/// decoded from, so retaining either retains that entire buffer — a
127/// 10-byte value can pin a 64 MiB fetch response. Past the lifetime of
128/// the response, store `Bytes::copy_from_slice(&value)` instead.
129#[derive(Debug, Clone, PartialEq, Eq, Default)]
130pub struct Record {
131    pub attributes: i8,
132    /// Timestamp as an offset from the batch's `base_timestamp`.
133    pub timestamp_delta: i64,
134    /// Offset as a delta from the batch's `base_offset`.
135    pub offset_delta: i32,
136    pub key: Option<Bytes>,
137    pub value: Option<Bytes>,
138    pub headers: Vec<RecordHeader>,
139}
140
141/// A record header: string key, nullable bytes value.
142#[derive(Debug, Clone, PartialEq, Eq, Default)]
143pub struct RecordHeader {
144    pub key: String,
145    pub value: Option<Bytes>,
146}
147
148impl RecordBatch {
149    pub fn compression(&self) -> Compression {
150        Compression::from_attributes(self.attributes)
151    }
152
153    /// True when timestamps are log-append time (bit 3); false = create time.
154    pub fn is_log_append_time(&self) -> bool {
155        self.attributes & (1 << 3) != 0
156    }
157
158    pub fn is_transactional(&self) -> bool {
159        self.attributes & (1 << 4) != 0
160    }
161
162    pub fn is_control(&self) -> bool {
163        self.attributes & (1 << 5) != 0
164    }
165
166    pub fn has_delete_horizon(&self) -> bool {
167        self.attributes & (1 << 6) != 0
168    }
169
170    /// The wire record count: parsed length for plain records, the carried
171    /// count for compressed payloads.
172    pub fn record_count(&self) -> Result<i32, EncodeError> {
173        match &self.records {
174            Records::Plain(records) => {
175                i32::try_from(records.len()).map_err(|_| EncodeError::TooLong {
176                    len: records.len(),
177                    max: i32::MAX as usize,
178                })
179            }
180            Records::Compressed { count, .. } => Ok(*count),
181        }
182    }
183
184    /// Encode into any [`BufMut`].
185    ///
186    /// The crc covers everything after itself, so a destination that
187    /// cannot be read back forces the batch body through a scratch
188    /// buffer first. Callers that already hold a `BytesMut` should use
189    /// [`RecordBatch::encode_to`], which writes in place and skips both
190    /// the allocation and the copy.
191    pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), EncodeError> {
192        let mut scratch = BytesMut::new();
193        self.encode_to(&mut scratch)?;
194        buf.put_slice(&scratch);
195        Ok(())
196    }
197
198    /// Append this batch to `buf`, computing the crc over the bytes just
199    /// written rather than over a side buffer.
200    ///
201    /// The batch length and crc are back-patched once the body is in
202    /// place. On error `buf` is truncated back to the length it had on
203    /// entry, so a failed batch leaves no partial bytes behind.
204    pub fn encode_to(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
205        let start = buf.len();
206        match self.encode_in_place(buf, start) {
207            Ok(()) => Ok(()),
208            Err(error) => {
209                buf.truncate(start);
210                Err(error)
211            }
212        }
213    }
214
215    fn encode_in_place(&self, buf: &mut BytesMut, start: usize) -> Result<(), EncodeError> {
216        let record_count = self.record_count()?;
217        buf.put_i64(self.base_offset);
218        buf.put_i32(0); // batch_length, back-patched below
219        buf.put_i32(self.partition_leader_epoch);
220        buf.put_i8(MAGIC);
221        buf.put_u32(0); // crc, back-patched below
222        let body = buf.len();
223
224        buf.put_i16(self.attributes);
225        buf.put_i32(self.last_offset_delta);
226        buf.put_i64(self.base_timestamp);
227        buf.put_i64(self.max_timestamp);
228        buf.put_i64(self.producer_id);
229        buf.put_i16(self.producer_epoch);
230        buf.put_i32(self.base_sequence);
231        buf.put_i32(record_count);
232        match &self.records {
233            Records::Plain(records) => {
234                for record in records {
235                    record.encode(buf)?;
236                }
237            }
238            Records::Compressed { payload, .. } => buf.extend_from_slice(payload),
239        }
240
241        let batch_length = 4 + 1 + 4 + (buf.len() - body); // epoch + magic + crc + body
242        let batch_length = i32::try_from(batch_length).map_err(|_| EncodeError::TooLong {
243            len: batch_length,
244            max: i32::MAX as usize,
245        })?;
246        let crc = crc32c(&buf[body..]);
247        buf[start + 8..start + 12].copy_from_slice(&batch_length.to_be_bytes());
248        buf[body - 4..body].copy_from_slice(&crc.to_be_bytes());
249        Ok(())
250    }
251
252    /// Decode one batch, verifying magic and crc. Errors leave `buf` in an
253    /// unspecified position.
254    ///
255    /// Allocation is bounded by the default [`Limits`], derived from
256    /// `buf`'s length; [`RecordBatch::decode_with_limits`] takes another
257    /// policy.
258    pub fn decode(buf: &mut Bytes) -> Result<RecordBatch, DecodeError> {
259        Self::decode_with_limits(buf, Limits::default())
260    }
261
262    /// Decode one batch under `limits`.
263    pub fn decode_with_limits(buf: &mut Bytes, limits: Limits) -> Result<RecordBatch, DecodeError> {
264        let mut budget = limits.budget(buf.len());
265        Self::decode_with_budget(buf, &mut budget)
266    }
267
268    /// Decode one batch against an existing `budget`, so that a set of
269    /// batches — or a whole message carrying them — shares one bound.
270    pub fn decode_with_budget(
271        buf: &mut Bytes,
272        budget: &mut Budget,
273    ) -> Result<RecordBatch, DecodeError> {
274        if buf.len() < 12 {
275            return Err(DecodeError::Truncated {
276                needed: 12 - buf.len(),
277            });
278        }
279        let base_offset = buf.get_i64();
280        let batch_length = buf.get_i32();
281        let Ok(batch_length) = usize::try_from(batch_length) else {
282            return Err(DecodeError::InvalidLength(i64::from(batch_length)));
283        };
284        if batch_length < BATCH_OVERHEAD {
285            return Err(DecodeError::InvalidLength(batch_length as i64));
286        }
287        if buf.len() < batch_length {
288            return Err(DecodeError::Truncated {
289                needed: batch_length - buf.len(),
290            });
291        }
292        let partition_leader_epoch = buf.get_i32();
293        let magic = buf.get_i8();
294        if magic != MAGIC {
295            return Err(DecodeError::UnknownDiscriminant {
296                kind: "record batch magic",
297                value: i64::from(magic),
298            });
299        }
300        let crc = buf.get_u32();
301        // Everything after the crc field, i.e. attributes through the end.
302        let mut body = buf.split_to(batch_length - 9);
303        let actual = crc32c(&body);
304        if actual != crc {
305            return Err(DecodeError::CrcMismatch {
306                stored: crc,
307                computed: actual,
308            });
309        }
310
311        let attributes = body.get_i16();
312        let last_offset_delta = body.get_i32();
313        let base_timestamp = body.get_i64();
314        let max_timestamp = body.get_i64();
315        let producer_id = body.get_i64();
316        let producer_epoch = body.get_i16();
317        let base_sequence = body.get_i32();
318        let count = body.get_i32();
319        if count < 0 {
320            return Err(DecodeError::InvalidLength(i64::from(count)));
321        }
322        let records = if Compression::from_attributes(attributes) == Compression::None {
323            let mut records = Vec::new();
324            for _ in 0..count {
325                let mark = body.len();
326                let record = Record::decode_with_budget(&mut body, budget)?;
327                budget.progress(mark, body.len())?;
328                budget.push(&mut records, record)?;
329            }
330            if !body.is_empty() {
331                // Bytes inside the crc-covered region that no record
332                // accounts for: the count or the record lengths lie.
333                return Err(DecodeError::InvalidLength(body.len() as i64));
334            }
335            Records::Plain(records)
336        } else {
337            Records::Compressed {
338                count,
339                payload: body,
340            }
341        };
342        Ok(RecordBatch {
343            base_offset,
344            partition_leader_epoch,
345            attributes,
346            last_offset_delta,
347            base_timestamp,
348            max_timestamp,
349            producer_id,
350            producer_epoch,
351            base_sequence,
352            records,
353        })
354    }
355}
356
357impl Record {
358    /// Encoded length of everything after this record's length prefix.
359    ///
360    /// Computed rather than measured: the length prefix comes first on
361    /// the wire, and sizing the body analytically is what lets the
362    /// fields go straight to the destination instead of through a
363    /// per-record side buffer.
364    fn body_len(&self, header_count: i64) -> usize {
365        fn bytes_len(value: Option<&[u8]>) -> usize {
366            match value {
367                Some(v) => wire::varint_len(v.len() as i64) + v.len(),
368                None => wire::varint_len(-1),
369            }
370        }
371
372        let mut len = 1; // attributes
373        len += wire::varint_len(self.timestamp_delta);
374        len += wire::varint_len(i64::from(self.offset_delta));
375        len += bytes_len(self.key.as_deref());
376        len += bytes_len(self.value.as_deref());
377        len += wire::varint_len(header_count);
378        for header in &self.headers {
379            len += bytes_len(Some(header.key.as_bytes()));
380            len += bytes_len(header.value.as_deref());
381        }
382        len
383    }
384
385    pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), EncodeError> {
386        let header_count = i64::try_from(self.headers.len()).map_err(|_| EncodeError::TooLong {
387            len: self.headers.len(),
388            max: usize::try_from(i64::MAX).unwrap_or(usize::MAX),
389        })?;
390        let body_len = self.body_len(header_count);
391        let body_len = i64::try_from(body_len).map_err(|_| EncodeError::TooLong {
392            len: body_len,
393            max: usize::try_from(i64::MAX).unwrap_or(usize::MAX),
394        })?;
395
396        wire::put_varint(buf, body_len);
397        buf.put_i8(self.attributes);
398        wire::put_varint(buf, self.timestamp_delta);
399        wire::put_varint(buf, i64::from(self.offset_delta));
400        put_varint_bytes(buf, self.key.as_deref());
401        put_varint_bytes(buf, self.value.as_deref());
402        wire::put_varint(buf, header_count);
403        for header in &self.headers {
404            put_varint_bytes(buf, Some(header.key.as_bytes()));
405            put_varint_bytes(buf, header.value.as_deref());
406        }
407        Ok(())
408    }
409
410    /// Decode one record, bounding allocation by the default [`Limits`].
411    pub fn decode(buf: &mut Bytes) -> Result<Record, DecodeError> {
412        Self::decode_with_limits(buf, Limits::default())
413    }
414
415    /// Decode one record under `limits`.
416    pub fn decode_with_limits(buf: &mut Bytes, limits: Limits) -> Result<Record, DecodeError> {
417        let mut budget = limits.budget(buf.len());
418        Self::decode_with_budget(buf, &mut budget)
419    }
420
421    /// Decode one record against an existing `budget`.
422    pub fn decode_with_budget(buf: &mut Bytes, budget: &mut Budget) -> Result<Record, DecodeError> {
423        let length = wire::get_varint(buf)?;
424        let Ok(length) = usize::try_from(length) else {
425            return Err(DecodeError::InvalidLength(length));
426        };
427        if buf.len() < length {
428            return Err(DecodeError::Truncated {
429                needed: length - buf.len(),
430            });
431        }
432        let mut body = buf.split_to(length);
433        if body.is_empty() {
434            return Err(DecodeError::Truncated { needed: 1 });
435        }
436        let attributes = body.get_i8();
437        let timestamp_delta = wire::get_varint(&mut body)?;
438        let offset_delta = wire::get_varint(&mut body)?;
439        let Ok(offset_delta) = i32::try_from(offset_delta) else {
440            return Err(DecodeError::InvalidLength(offset_delta));
441        };
442        let key = get_varint_bytes(&mut body)?;
443        let value = get_varint_bytes(&mut body)?;
444        let header_count = wire::get_varint(&mut body)?;
445        if header_count < 0 {
446            return Err(DecodeError::InvalidLength(header_count));
447        }
448        let mut headers = Vec::new();
449        for _ in 0..header_count {
450            let mark = body.len();
451            let key = get_varint_bytes(&mut body)?.ok_or(DecodeError::InvalidLength(-1))?;
452            let key = String::from_utf8(key.into()).map_err(|_| DecodeError::InvalidUtf8)?;
453            let value = get_varint_bytes(&mut body)?;
454            budget.progress(mark, body.len())?;
455            budget.push(&mut headers, RecordHeader { key, value })?;
456        }
457        if !body.is_empty() {
458            return Err(DecodeError::InvalidLength(body.len() as i64));
459        }
460        Ok(Record {
461            attributes,
462            timestamp_delta,
463            offset_delta,
464            key,
465            value,
466            headers,
467        })
468    }
469}
470
471/// Decode a whole record set: batches back to back.
472///
473/// A fetch response may truncate the final batch mid-bytes (brokers send
474/// whole segments sliced by size); a partial trailing batch is discarded,
475/// not an error. Corruption inside a complete batch is still an error.
476///
477/// Allocation is bounded by the default [`Limits`], derived from `buf`'s
478/// length and shared by every batch in the set.
479pub fn decode_set(buf: &mut Bytes) -> Result<Vec<RecordBatch>, DecodeError> {
480    decode_set_with_limits(buf, Limits::default())
481}
482
483/// Decode a whole record set under `limits`, one budget for the set.
484pub fn decode_set_with_limits(
485    buf: &mut Bytes,
486    limits: Limits,
487) -> Result<Vec<RecordBatch>, DecodeError> {
488    let mut budget = limits.budget(buf.len());
489    decode_set_with_budget(buf, &mut budget)
490}
491
492/// Decode a whole record set against an existing `budget`, so a message
493/// and the records inside it draw on the same bound.
494pub fn decode_set_with_budget(
495    buf: &mut Bytes,
496    budget: &mut Budget,
497) -> Result<Vec<RecordBatch>, DecodeError> {
498    let mut batches = Vec::new();
499    loop {
500        if buf.len() < 12 {
501            buf.clear();
502            return Ok(batches);
503        }
504        let batch_length = i32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]);
505        let Ok(batch_length) = usize::try_from(batch_length) else {
506            return Err(DecodeError::InvalidLength(i64::from(batch_length)));
507        };
508        if buf.len() < 12 + batch_length {
509            buf.clear();
510            return Ok(batches);
511        }
512        // A batch is at least `BATCH_OVERHEAD` bytes, so this loop
513        // cannot spin; the budget still covers what each batch builds.
514        let batch = RecordBatch::decode_with_budget(buf, budget)?;
515        budget.push(&mut batches, batch)?;
516    }
517}
518
519/// Encode a record set into a [`BytesMut`], in place.
520///
521/// The counterpart to [`RecordBatch::encode_to`], and preferred for the
522/// same reason: [`encode_set`] has to take a generic destination, which
523/// cannot be read back, so it stages every batch through a scratch
524/// buffer and copies it across. Here the crc is computed over the bytes
525/// where they already sit.
526///
527/// On error `buf` keeps whatever whole batches preceded the failure;
528/// the failing batch leaves nothing behind, since
529/// [`RecordBatch::encode_to`] rolls itself back.
530pub fn encode_set_to(buf: &mut BytesMut, batches: &[RecordBatch]) -> Result<(), EncodeError> {
531    for batch in batches {
532        batch.encode_to(buf)?;
533    }
534    Ok(())
535}
536
537/// Encode a record set: batches back to back.
538///
539/// Prefer [`encode_set_to`] when the destination is a [`BytesMut`]; see
540/// there for what this one costs.
541pub fn encode_set(buf: &mut impl BufMut, batches: &[RecordBatch]) -> Result<(), EncodeError> {
542    // One scratch buffer for the whole set, reused batch to batch: a
543    // generic BufMut cannot be read back, and the crc must be written
544    // before the body it covers.
545    let mut scratch = BytesMut::new();
546    for batch in batches {
547        scratch.clear();
548        batch.encode_to(&mut scratch)?;
549        buf.put_slice(&scratch);
550    }
551    Ok(())
552}
553
554fn put_varint_bytes(buf: &mut impl BufMut, value: Option<&[u8]>) {
555    match value {
556        Some(v) => {
557            wire::put_varint(buf, v.len() as i64);
558            buf.put_slice(v);
559        }
560        None => wire::put_varint(buf, -1),
561    }
562}
563
564fn get_varint_bytes(buf: &mut Bytes) -> Result<Option<Bytes>, DecodeError> {
565    let length = wire::get_varint(buf)?;
566    if length == -1 {
567        return Ok(None);
568    }
569    let Ok(length) = usize::try_from(length) else {
570        return Err(DecodeError::InvalidLength(length));
571    };
572    if buf.len() < length {
573        return Err(DecodeError::Truncated {
574            needed: length - buf.len(),
575        });
576    }
577    Ok(Some(buf.split_to(length)))
578}
579
580/// CRC-32C (Castagnoli), the checksum record batches use. Distinct from
581/// the CRC-32 that magic 0/1 message sets used.
582///
583/// Two implementations, selected at compile time and bit-identical
584/// (`crc32c_implementations_agree` holds them to it):
585///
586/// - Default: a portable slicing-by-8 table implementation, safe Rust,
587///   no dependencies.
588/// - With the `hardware-crc` feature: the CPU's CRC-32C instruction via
589///   the `crc32c` crate, which picks it at runtime and falls back to
590///   software where it is absent. Worth it for throughput-sensitive
591///   pipelines; the portable path is fast enough that the default stays
592///   dependency-free.
593pub fn crc32c(data: &[u8]) -> u32 {
594    #[cfg(feature = "hardware-crc")]
595    {
596        ::crc32c::crc32c(data)
597    }
598    #[cfg(not(feature = "hardware-crc"))]
599    {
600        crc32c_portable(data)
601    }
602}
603
604/// The dependency-free CRC-32C, always compiled so the accelerated build
605/// can be differentially tested against it.
606///
607/// Slicing-by-8: each iteration folds eight input bytes at once through
608/// eight tables, breaking the serial dependency that makes the classic
609/// one-byte loop wait a table lookup per byte.
610// Unused in an accelerated non-test build; the differential test in
611// `hardware_crc_tests` is its only caller there.
612#[cfg_attr(
613    all(feature = "hardware-crc", not(test)),
614    expect(dead_code, reason = "differential test only")
615)]
616pub(crate) fn crc32c_portable(data: &[u8]) -> u32 {
617    let mut crc = !0u32;
618    let mut chunks = data.chunks_exact(8);
619    for chunk in &mut chunks {
620        // The reflected algorithm consumes bytes little-endian first.
621        let low = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]) ^ crc;
622        let high = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
623        crc = CRC32C_TABLES[7][(low & 0xff) as usize]
624            ^ CRC32C_TABLES[6][((low >> 8) & 0xff) as usize]
625            ^ CRC32C_TABLES[5][((low >> 16) & 0xff) as usize]
626            ^ CRC32C_TABLES[4][(low >> 24) as usize]
627            ^ CRC32C_TABLES[3][(high & 0xff) as usize]
628            ^ CRC32C_TABLES[2][((high >> 8) & 0xff) as usize]
629            ^ CRC32C_TABLES[1][((high >> 16) & 0xff) as usize]
630            ^ CRC32C_TABLES[0][(high >> 24) as usize];
631    }
632    // Up to seven bytes the wide loop could not take, a byte at a time.
633    for &byte in chunks.remainder() {
634        crc = (crc >> 8) ^ CRC32C_TABLES[0][((crc ^ u32::from(byte)) & 0xff) as usize];
635    }
636    !crc
637}
638
639static CRC32C_TABLES: [[u32; 256]; 8] = crc32c_tables();
640
641/// Table `n` holds the residue of a byte shifted `n` places further into
642/// the message, so table 0 is the classic byte-at-a-time table and each
643/// later one advances it by another byte.
644#[expect(clippy::cast_possible_truncation)] // i < 256
645const fn crc32c_tables() -> [[u32; 256]; 8] {
646    let mut tables = [[0u32; 256]; 8];
647    let mut i = 0;
648    while i < 256 {
649        let mut crc = i as u32;
650        let mut bit = 0;
651        while bit < 8 {
652            crc = if crc & 1 != 0 {
653                (crc >> 1) ^ 0x82f6_3b78
654            } else {
655                crc >> 1
656            };
657            bit += 1;
658        }
659        tables[0][i] = crc;
660        i += 1;
661    }
662    let mut slice = 1;
663    while slice < 8 {
664        let mut i = 0;
665        while i < 256 {
666            let previous = tables[slice - 1][i];
667            tables[slice][i] = (previous >> 8) ^ tables[0][(previous & 0xff) as usize];
668            i += 1;
669        }
670        slice += 1;
671    }
672    tables
673}
674
675#[cfg(all(test, feature = "hardware-crc"))]
676mod hardware_crc_tests {
677    use super::{crc32c, crc32c_portable};
678
679    /// The accelerated build must be indistinguishable from the portable
680    /// one. A CRC that differed by platform would corrupt every batch
681    /// this crate writes and reject every batch it reads, so the feature
682    /// is only safe while this holds — including at the lengths where
683    /// the two implementations' wide paths and remainders differ.
684    #[test]
685    fn crc32c_implementations_agree() {
686        let mut state = 0x9e37_79b9_7f4a_7c15u64;
687        let mut next = || {
688            state ^= state << 13;
689            state ^= state >> 7;
690            state ^= state << 17;
691            u8::try_from((state >> 33) & 0xff).expect("masked to a byte")
692        };
693        for len in [
694            0, 1, 2, 3, 7, 8, 9, 15, 16, 17, 23, 24, 25, 31, 32, 33, 63, 64, 65, 127, 128, 255,
695            256, 257, 1023, 1024, 1025, 4096, 4097,
696        ] {
697            let data: Vec<u8> = (0..len).map(|_| next()).collect();
698            assert_eq!(
699                crc32c(&data),
700                crc32c_portable(&data),
701                "hardware and portable crc disagree at {len} bytes"
702            );
703        }
704    }
705}