1use bytes::{Buf, BufMut, Bytes};
18
19use crate::budget::{Budget, Limits};
20use crate::error::{DecodeError, EncodeError};
21
22fn ensure(buf: &impl Buf, needed: usize) -> Result<(), DecodeError> {
24 if buf.remaining() < needed {
25 Err(DecodeError::Truncated {
26 needed: needed - buf.remaining(),
27 })
28 } else {
29 Ok(())
30 }
31}
32
33fn len_from(raw: i64) -> Result<usize, DecodeError> {
34 usize::try_from(raw).map_err(|_| DecodeError::InvalidLength(raw))
35}
36
37fn compact_len(raw: u64) -> Result<usize, DecodeError> {
40 usize::try_from(raw)
41 .map_err(|_| DecodeError::InvalidLength(i64::try_from(raw).unwrap_or(i64::MAX)))
42}
43
44macro_rules! checked_get {
52 ($(#[$doc:meta] $name:ident -> $ty:ty [$len:expr] via $method:ident;)+) => {
53 $(
54 #[$doc]
55 pub fn $name(buf: &mut impl Buf) -> Result<$ty, DecodeError> {
56 ensure(buf, $len)?;
57 Ok(buf.$method())
58 }
59 )+
60 };
61}
62
63checked_get! {
64 get_i8 -> i8 [1] via get_i8;
66 get_i16 -> i16 [2] via get_i16;
68 get_u16 -> u16 [2] via get_u16;
70 get_i32 -> i32 [4] via get_i32;
72 get_u32 -> u32 [4] via get_u32;
74 get_i64 -> i64 [8] via get_i64;
76 get_f64 -> f64 [8] via get_f64;
78}
79
80pub fn get_bool(buf: &mut impl Buf) -> Result<bool, DecodeError> {
82 ensure(buf, 1)?;
83 Ok(buf.get_u8() != 0)
84}
85
86pub fn put_unsigned_varint(buf: &mut impl BufMut, mut value: u64) {
92 loop {
93 let mut byte = (value & 0x7f) as u8;
94 value >>= 7;
95 if value != 0 {
96 byte |= 0x80;
97 }
98 buf.put_u8(byte);
99 if value == 0 {
100 return;
101 }
102 }
103}
104
105pub fn get_unsigned_varint(buf: &mut impl Buf) -> Result<u64, DecodeError> {
108 let mut value = 0u64;
109 let mut shift = 0u32;
110 loop {
111 ensure(buf, 1)?;
112 let byte = buf.get_u8();
113 if shift == 63 && byte & 0xfe != 0 {
114 return Err(DecodeError::VarintOverflow);
115 }
116 value |= u64::from(byte & 0x7f) << shift;
117 if byte & 0x80 == 0 {
118 return Ok(value);
119 }
120 shift += 7;
121 if shift > 63 {
122 return Err(DecodeError::VarintOverflow);
123 }
124 }
125}
126
127pub fn put_varint(buf: &mut impl BufMut, value: i64) {
129 put_unsigned_varint(buf, zigzag_encode(value));
130}
131
132pub fn get_varint(buf: &mut impl Buf) -> Result<i64, DecodeError> {
134 Ok(zigzag_decode(get_unsigned_varint(buf)?))
135}
136
137fn zigzag_encode(value: i64) -> u64 {
138 ((value << 1) ^ (value >> 63)) as u64
139}
140
141fn zigzag_decode(value: u64) -> i64 {
142 ((value >> 1) as i64) ^ -((value & 1) as i64)
143}
144
145pub(crate) fn varint_len(value: i64) -> usize {
148 unsigned_varint_len(zigzag_encode(value))
149}
150
151pub fn unsigned_varint_len(value: u64) -> usize {
153 let bits = 64 - value.leading_zeros() as usize;
155 bits.div_ceil(7).max(1)
156}
157
158pub fn put_string(buf: &mut impl BufMut, value: &str) -> Result<(), EncodeError> {
164 let len = i16::try_from(value.len()).map_err(|_| EncodeError::TooLong {
165 len: value.len(),
166 max: i16::MAX as usize,
167 })?;
168 buf.put_i16(len);
169 buf.put_slice(value.as_bytes());
170 Ok(())
171}
172
173pub fn put_nullable_string(buf: &mut impl BufMut, value: Option<&str>) -> Result<(), EncodeError> {
175 match value {
176 Some(s) => put_string(buf, s),
177 None => {
178 buf.put_i16(-1);
179 Ok(())
180 }
181 }
182}
183
184pub fn get_string(buf: &mut impl Buf) -> Result<String, DecodeError> {
186 get_nullable_string(buf)?.ok_or(DecodeError::InvalidLength(-1))
187}
188
189pub fn get_nullable_string(buf: &mut impl Buf) -> Result<Option<String>, DecodeError> {
191 ensure(buf, 2)?;
192 let raw = buf.get_i16();
193 if raw == -1 {
194 return Ok(None);
195 }
196 let len = len_from(raw.into())?;
197 read_utf8(buf, len).map(Some)
198}
199
200pub fn put_compact_string(buf: &mut impl BufMut, value: &str) {
202 put_unsigned_varint(buf, value.len() as u64 + 1);
203 buf.put_slice(value.as_bytes());
204}
205
206pub fn put_compact_nullable_string(buf: &mut impl BufMut, value: Option<&str>) {
208 match value {
209 Some(s) => put_compact_string(buf, s),
210 None => put_unsigned_varint(buf, 0),
211 }
212}
213
214pub fn get_compact_string(buf: &mut impl Buf) -> Result<String, DecodeError> {
216 get_compact_nullable_string(buf)?.ok_or(DecodeError::InvalidLength(-1))
217}
218
219pub fn get_compact_nullable_string(buf: &mut impl Buf) -> Result<Option<String>, DecodeError> {
221 match get_unsigned_varint(buf)? {
222 0 => Ok(None),
223 n => read_utf8(buf, compact_len(n - 1)?).map(Some),
224 }
225}
226
227fn read_utf8(buf: &mut impl Buf, len: usize) -> Result<String, DecodeError> {
228 ensure(buf, len)?;
229 let bytes = buf.copy_to_bytes(len);
230 String::from_utf8(bytes.into()).map_err(|_| DecodeError::InvalidUtf8)
231}
232
233pub fn put_bytes(buf: &mut impl BufMut, value: &[u8]) -> Result<(), EncodeError> {
239 let len = i32::try_from(value.len()).map_err(|_| EncodeError::TooLong {
240 len: value.len(),
241 max: i32::MAX as usize,
242 })?;
243 buf.put_i32(len);
244 buf.put_slice(value);
245 Ok(())
246}
247
248pub fn put_nullable_bytes(buf: &mut impl BufMut, value: Option<&[u8]>) -> Result<(), EncodeError> {
250 match value {
251 Some(b) => put_bytes(buf, b),
252 None => {
253 buf.put_i32(-1);
254 Ok(())
255 }
256 }
257}
258
259pub fn get_nullable_bytes(buf: &mut impl Buf) -> Result<Option<Bytes>, DecodeError> {
261 ensure(buf, 4)?;
262 let raw = buf.get_i32();
263 if raw == -1 {
264 return Ok(None);
265 }
266 let len = len_from(raw.into())?;
267 ensure(buf, len)?;
268 Ok(Some(buf.copy_to_bytes(len)))
269}
270
271pub fn put_compact_bytes(buf: &mut impl BufMut, value: &[u8]) {
273 put_unsigned_varint(buf, value.len() as u64 + 1);
274 buf.put_slice(value);
275}
276
277pub fn put_compact_nullable_bytes(buf: &mut impl BufMut, value: Option<&[u8]>) {
279 match value {
280 Some(b) => put_compact_bytes(buf, b),
281 None => put_unsigned_varint(buf, 0),
282 }
283}
284
285pub fn get_compact_nullable_bytes(buf: &mut impl Buf) -> Result<Option<Bytes>, DecodeError> {
287 match get_unsigned_varint(buf)? {
288 0 => Ok(None),
289 n => {
290 let len = compact_len(n - 1)?;
291 ensure(buf, len)?;
292 Ok(Some(buf.copy_to_bytes(len)))
293 }
294 }
295}
296
297pub fn put_array_len(buf: &mut impl BufMut, len: Option<usize>) -> Result<(), EncodeError> {
303 match len {
304 Some(n) => {
305 let n = i32::try_from(n).map_err(|_| EncodeError::TooLong {
306 len: n,
307 max: i32::MAX as usize,
308 })?;
309 buf.put_i32(n);
310 }
311 None => buf.put_i32(-1),
312 }
313 Ok(())
314}
315
316pub fn get_array_len(buf: &mut impl Buf) -> Result<Option<usize>, DecodeError> {
318 ensure(buf, 4)?;
319 let raw = buf.get_i32();
320 if raw == -1 {
321 return Ok(None);
322 }
323 len_from(raw.into()).map(Some)
324}
325
326pub fn put_compact_array_len(buf: &mut impl BufMut, len: Option<usize>) {
328 match len {
329 Some(n) => put_unsigned_varint(buf, n as u64 + 1),
330 None => put_unsigned_varint(buf, 0),
331 }
332}
333
334pub fn get_compact_array_len(buf: &mut impl Buf) -> Result<Option<usize>, DecodeError> {
336 match get_unsigned_varint(buf)? {
337 0 => Ok(None),
338 n => compact_len(n - 1).map(Some),
339 }
340}
341
342pub fn put_uuid(buf: &mut impl BufMut, value: [u8; 16]) {
348 buf.put_slice(&value);
349}
350
351pub fn get_uuid(buf: &mut impl Buf) -> Result<[u8; 16], DecodeError> {
353 ensure(buf, 16)?;
354 let mut out = [0u8; 16];
355 buf.copy_to_slice(&mut out);
356 Ok(out)
357}
358
359#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct RawTaggedField {
368 pub tag: u32,
369 pub data: Bytes,
370}
371
372pub fn put_tagged_fields(buf: &mut impl BufMut, fields: &[RawTaggedField]) {
375 put_unsigned_varint(buf, fields.len() as u64);
376 for field in fields {
377 put_unsigned_varint(buf, u64::from(field.tag));
378 put_unsigned_varint(buf, field.data.len() as u64);
379 buf.put_slice(&field.data);
380 }
381}
382
383pub fn get_tagged_fields(buf: &mut impl Buf) -> Result<Vec<RawTaggedField>, DecodeError> {
389 let mut budget = Limits::default().budget(buf.remaining());
390 get_tagged_fields_with_budget(buf, &mut budget)
391}
392
393pub fn get_tagged_fields_with_budget(
404 buf: &mut impl Buf,
405 budget: &mut Budget,
406) -> Result<Vec<RawTaggedField>, DecodeError> {
407 let count = get_unsigned_varint(buf)?;
408 let mut fields: Vec<RawTaggedField> = Vec::new();
409 let mut previous: Option<u32> = None;
410 for _ in 0..count {
411 let tag =
414 u32::try_from(get_unsigned_varint(buf)?).map_err(|_| DecodeError::VarintOverflow)?;
415 if let Some(previous) = previous {
416 if tag <= previous {
417 return Err(DecodeError::TaggedFieldOrder { previous, tag });
418 }
419 }
420 previous = Some(tag);
421 let len = len_from(i64::try_from(get_unsigned_varint(buf)?).unwrap_or(-1))?;
422 ensure(buf, len)?;
423 budget.push(
424 &mut fields,
425 RawTaggedField {
426 tag,
427 data: buf.copy_to_bytes(len),
428 },
429 )?;
430 }
431 Ok(fields)
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437 use bytes::BytesMut;
438
439 #[track_caller]
440 fn roundtrip_unsigned(value: u64) {
441 let mut buf = BytesMut::new();
442 put_unsigned_varint(&mut buf, value);
443 assert_eq!(buf.len(), unsigned_varint_len(value), "length of {value}");
444 let mut read = buf.freeze();
445 assert_eq!(get_unsigned_varint(&mut read), Ok(value));
446 assert!(!read.has_remaining());
447 }
448
449 #[test]
450 fn unsigned_varint_roundtrip() {
451 for value in [0, 1, 127, 128, 300, 16383, 16384, u32::MAX as u64, u64::MAX] {
452 roundtrip_unsigned(value);
453 }
454 }
455
456 #[test]
457 fn unsigned_varint_known_encoding() {
458 let mut buf = BytesMut::new();
459 put_unsigned_varint(&mut buf, 300);
460 assert_eq!(&buf[..], &[0xac, 0x02]);
461 }
462
463 #[test]
464 fn unsigned_varint_overflow_rejected() {
465 let mut buf = Bytes::from_static(&[0x80; 11]);
467 assert_eq!(
468 get_unsigned_varint(&mut buf),
469 Err(DecodeError::VarintOverflow)
470 );
471 let mut buf =
473 Bytes::from_static(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02]);
474 assert_eq!(
475 get_unsigned_varint(&mut buf),
476 Err(DecodeError::VarintOverflow)
477 );
478 }
479
480 #[test]
481 fn unsigned_varint_truncated() {
482 let mut buf = Bytes::from_static(&[0x80]);
483 assert_eq!(
484 get_unsigned_varint(&mut buf),
485 Err(DecodeError::Truncated { needed: 1 })
486 );
487 }
488
489 #[test]
490 fn zigzag_known_values() {
491 for (plain, encoded) in [(0i64, 0u64), (-1, 1), (1, 2), (-2, 3), (2, 4)] {
492 assert_eq!(zigzag_encode(plain), encoded);
493 assert_eq!(zigzag_decode(encoded), plain);
494 }
495 assert_eq!(zigzag_decode(zigzag_encode(i64::MIN)), i64::MIN);
496 assert_eq!(zigzag_decode(zigzag_encode(i64::MAX)), i64::MAX);
497 }
498
499 #[test]
500 fn signed_varint_roundtrip() {
501 for value in [0i64, -1, 1, -300, 300, i32::MIN as i64, i64::MAX, i64::MIN] {
502 let mut buf = BytesMut::new();
503 put_varint(&mut buf, value);
504 assert_eq!(get_varint(&mut buf.freeze()), Ok(value));
505 }
506 }
507
508 #[test]
509 fn string_roundtrip() {
510 let mut buf = BytesMut::new();
511 put_string(&mut buf, "hello").unwrap();
512 assert_eq!(&buf[..], b"\x00\x05hello");
513 assert_eq!(get_string(&mut buf.freeze()).unwrap(), "hello");
514 }
515
516 #[test]
517 fn nullable_string_null() {
518 let mut buf = BytesMut::new();
519 put_nullable_string(&mut buf, None).unwrap();
520 assert_eq!(&buf[..], &[0xff, 0xff]);
521 assert_eq!(get_nullable_string(&mut buf.freeze()), Ok(None));
522 }
523
524 #[test]
525 fn compact_string_roundtrip() {
526 let mut buf = BytesMut::new();
527 put_compact_string(&mut buf, "topic-a");
528 assert_eq!(buf[0], 8); assert_eq!(get_compact_string(&mut buf.freeze()).unwrap(), "topic-a");
530
531 let mut buf = BytesMut::new();
532 put_compact_nullable_string(&mut buf, None);
533 assert_eq!(&buf[..], &[0x00]);
534 assert_eq!(get_compact_nullable_string(&mut buf.freeze()), Ok(None));
535 }
536
537 #[test]
538 fn invalid_utf8_rejected() {
539 let mut buf = Bytes::from_static(&[0x00, 0x02, 0xff, 0xfe]);
540 assert_eq!(get_string(&mut buf), Err(DecodeError::InvalidUtf8));
541 }
542
543 #[test]
544 fn bytes_roundtrip() {
545 let payload = &[1u8, 2, 3][..];
546 let mut buf = BytesMut::new();
547 put_bytes(&mut buf, payload).unwrap();
548 assert_eq!(
549 get_nullable_bytes(&mut buf.freeze()).unwrap().as_deref(),
550 Some(payload)
551 );
552
553 let mut buf = BytesMut::new();
554 put_nullable_bytes(&mut buf, None).unwrap();
555 assert_eq!(get_nullable_bytes(&mut buf.freeze()), Ok(None));
556
557 let mut buf = BytesMut::new();
558 put_compact_bytes(&mut buf, payload);
559 assert_eq!(
560 get_compact_nullable_bytes(&mut buf.freeze())
561 .unwrap()
562 .as_deref(),
563 Some(payload)
564 );
565 }
566
567 #[test]
568 fn array_len_roundtrip() {
569 for len in [None, Some(0), Some(5), Some(100_000)] {
570 let mut buf = BytesMut::new();
571 put_array_len(&mut buf, len).unwrap();
572 assert_eq!(get_array_len(&mut buf.freeze()), Ok(len));
573
574 let mut buf = BytesMut::new();
575 put_compact_array_len(&mut buf, len);
576 assert_eq!(get_compact_array_len(&mut buf.freeze()), Ok(len));
577 }
578 }
579
580 #[test]
581 fn negative_array_len_rejected() {
582 let mut buf = Bytes::from_static(&[0xff, 0xff, 0xff, 0xfe]); assert_eq!(get_array_len(&mut buf), Err(DecodeError::InvalidLength(-2)));
584 }
585
586 #[test]
587 fn uuid_roundtrip() {
588 let id: [u8; 16] = *b"0123456789abcdef";
589 let mut buf = BytesMut::new();
590 put_uuid(&mut buf, id);
591 assert_eq!(get_uuid(&mut buf.freeze()), Ok(id));
592 }
593
594 #[test]
595 fn tagged_fields_roundtrip() {
596 let fields = vec![
597 RawTaggedField {
598 tag: 0,
599 data: Bytes::from_static(b"abc"),
600 },
601 RawTaggedField {
602 tag: 7,
603 data: Bytes::new(),
604 },
605 ];
606 let mut buf = BytesMut::new();
607 put_tagged_fields(&mut buf, &fields);
608 assert_eq!(get_tagged_fields(&mut buf.freeze()), Ok(fields));
609
610 let mut buf = BytesMut::new();
612 put_tagged_fields(&mut buf, &[]);
613 assert_eq!(&buf[..], &[0x00]);
614 }
615
616 fn raw_section(fields: &[(u32, &[u8])]) -> Bytes {
619 let mut buf = BytesMut::new();
620 put_unsigned_varint(&mut buf, fields.len() as u64);
621 for (tag, data) in fields {
622 put_unsigned_varint(&mut buf, u64::from(*tag));
623 put_unsigned_varint(&mut buf, data.len() as u64);
624 buf.put_slice(data);
625 }
626 buf.freeze()
627 }
628
629 #[test]
630 fn tagged_fields_must_ascend() {
631 assert_eq!(
632 get_tagged_fields(&mut raw_section(&[(7, b"a"), (2, b"b")])),
633 Err(DecodeError::TaggedFieldOrder {
634 previous: 7,
635 tag: 2
636 })
637 );
638 }
639
640 #[test]
641 fn duplicate_tags_are_rejected() {
642 assert_eq!(
645 get_tagged_fields(&mut raw_section(&[(99, b"first"), (99, b"second")])),
646 Err(DecodeError::TaggedFieldOrder {
647 previous: 99,
648 tag: 99
649 })
650 );
651 assert!(get_tagged_fields(&mut raw_section(&[(0, b"a"), (1, b"b")])).is_ok());
653 }
654
655 #[test]
656 fn tagged_fields_are_bounded_by_input_size() {
657 let fields: Vec<(u32, &[u8])> = (0..4096u32).map(|tag| (tag, &[][..])).collect();
660 let section = raw_section(&fields);
661 let mut tight = Limits::default()
662 .with_min_alloc_bytes(0)
663 .with_alloc_factor(4)
664 .budget(section.len());
665 assert!(matches!(
666 get_tagged_fields_with_budget(&mut section.clone(), &mut tight),
667 Err(DecodeError::AllocationLimit { .. })
668 ));
669 assert!(tight.used() <= tight.limit());
670 let mut roomy = Limits::default()
673 .with_alloc_factor(64)
674 .budget(section.len());
675 assert_eq!(
676 get_tagged_fields_with_budget(&mut section.clone(), &mut roomy)
677 .expect("decodes")
678 .len(),
679 4096
680 );
681 }
682}