1use bytes::{Buf, BufMut, Bytes, BytesMut};
34
35use crate::budget::{Budget, Limits};
36use crate::error::{DecodeError, EncodeError};
37use crate::wire;
38
39pub const MAGIC: i8 = 2;
42
43const BATCH_OVERHEAD: usize = 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4 + 4;
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Compression {
51 None,
52 Gzip,
53 Snappy,
54 Lz4,
55 Zstd,
56 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 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum Records {
110 Plain(Vec<Record>),
112 Compressed { count: i32, payload: Bytes },
115}
116
117impl Default for Records {
118 fn default() -> Self {
119 Records::Plain(Vec::new())
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, Default)]
130pub struct Record {
131 pub attributes: i8,
132 pub timestamp_delta: i64,
134 pub offset_delta: i32,
136 pub key: Option<Bytes>,
137 pub value: Option<Bytes>,
138 pub headers: Vec<RecordHeader>,
139}
140
141#[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 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 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 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 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); buf.put_i32(self.partition_leader_epoch);
220 buf.put_i8(MAGIC);
221 buf.put_u32(0); 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); 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 pub fn decode(buf: &mut Bytes) -> Result<RecordBatch, DecodeError> {
259 Self::decode_with_limits(buf, Limits::default())
260 }
261
262 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 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 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 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 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; 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 pub fn decode(buf: &mut Bytes) -> Result<Record, DecodeError> {
412 Self::decode_with_limits(buf, Limits::default())
413 }
414
415 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 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
471pub fn decode_set(buf: &mut Bytes) -> Result<Vec<RecordBatch>, DecodeError> {
480 decode_set_with_limits(buf, Limits::default())
481}
482
483pub 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
492pub 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 let batch = RecordBatch::decode_with_budget(buf, budget)?;
515 budget.push(&mut batches, batch)?;
516 }
517}
518
519pub 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
537pub fn encode_set(buf: &mut impl BufMut, batches: &[RecordBatch]) -> Result<(), EncodeError> {
542 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
580pub 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#[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 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 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#[expect(clippy::cast_possible_truncation)] const 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 #[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}