wire-codec 1.2.0

Binary frame codec and protocol codec toolkit. Length-prefixed, varint-prefixed, delimiter-based, checksummed, and custom framing strategies. Built-in varint, zigzag, bitfield, packed struct, CRC, and COBS encoding. Allocation-free core, no_std, runtime-agnostic, with optional tokio-util and futures codec adapters.
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! Unsigned LEB128 varint encoding, plus zigzag-mapped signed helpers.
//!
//! A varint encodes an unsigned integer in one to ten bytes. The low seven
//! bits of each byte carry payload, and the top bit signals continuation:
//! `1` means more bytes follow, `0` means the value is complete.
//!
//! The encoding is identical to the format used by Protocol Buffers, WebAssembly,
//! and DWARF. The signed helpers ([`encode_i32`], [`decode_i64`], ...) apply
//! the [`zigzag`][`crate::zigzag`] mapping first, matching protobuf's
//! `sint32` / `sint64` wire types.
//!
//! # Error contract
//!
//! Every function in this module is atomic: on error the cursor is left
//! exactly where it was. A streaming caller that receives
//! [`Error::UnexpectedEof`] can append more bytes and retry the same call
//! without cloning the cursor first.
//!
//! # Canonical encodings
//!
//! LEB128 allows a value to be padded with redundant `0x80` continuation
//! bytes followed by a `0x00` terminator (for example `[0x80, 0x00]` is an
//! overlong encoding of `0`). The plain `decode_*` functions accept these
//! overlong forms, as Protocol Buffers does. The `decode_*_canonical`
//! functions reject them with [`Error::InvalidEncoding`], so that every value
//! has exactly one accepted wire representation. Use the canonical forms when
//! the encoded bytes are hashed, signed, deduplicated, or compared between
//! implementations. The encoders always produce the canonical form.

use crate::buf::{ReadBuf, WriteBuf};
use crate::error::{Error, Result};
use crate::zigzag;

/// Maximum encoded length of a `u16` varint.
pub const MAX_LEN_U16: usize = 3;
/// Maximum encoded length of a `u32` varint.
pub const MAX_LEN_U32: usize = 5;
/// Maximum encoded length of a `u64` varint.
pub const MAX_LEN_U64: usize = 10;

/// Encoded length of `value` as a `u16` varint, in bytes (1 to 3).
///
/// # Example
///
/// ```
/// use wire_codec::varint;
/// assert_eq!(varint::encoded_len_u16(127), 1);
/// assert_eq!(varint::encoded_len_u16(u16::MAX), 3);
/// ```
#[inline]
#[must_use]
pub const fn encoded_len_u16(value: u16) -> usize {
    encoded_len_u64(value as u64)
}

/// Encoded length of `value` as a `u32` varint, in bytes (1 to 5).
///
/// # Example
///
/// ```
/// use wire_codec::varint;
/// assert_eq!(varint::encoded_len_u32(0), 1);
/// assert_eq!(varint::encoded_len_u32(127), 1);
/// assert_eq!(varint::encoded_len_u32(128), 2);
/// assert_eq!(varint::encoded_len_u32(u32::MAX), 5);
/// ```
#[inline]
#[must_use]
pub const fn encoded_len_u32(value: u32) -> usize {
    encoded_len_u64(value as u64)
}

/// Encoded length of `value` as a `u64` varint, in bytes (1 to 10).
///
/// # Example
///
/// ```
/// use wire_codec::varint;
/// assert_eq!(varint::encoded_len_u64(0), 1);
/// assert_eq!(varint::encoded_len_u64(u64::MAX), 10);
/// ```
#[inline]
#[must_use]
pub const fn encoded_len_u64(value: u64) -> usize {
    let bits = (u64::BITS - value.leading_zeros()) as usize;
    if bits == 0 { 1 } else { bits.div_ceil(7) }
}

/// Encoded length of `value` as a `usize` varint, in bytes (1 to 10).
///
/// # Example
///
/// ```
/// use wire_codec::varint;
/// assert_eq!(varint::encoded_len_usize(300), 2);
/// ```
#[inline]
#[must_use]
pub const fn encoded_len_usize(value: usize) -> usize {
    // `usize` is at most 64 bits on every supported target.
    encoded_len_u64(value as u64)
}

/// Encoded length of `value` as a zigzag `i32` varint, in bytes (1 to 5).
///
/// # Example
///
/// ```
/// use wire_codec::varint;
/// assert_eq!(varint::encoded_len_i32(-1), 1);
/// assert_eq!(varint::encoded_len_i32(i32::MIN), 5);
/// ```
#[inline]
#[must_use]
pub const fn encoded_len_i32(value: i32) -> usize {
    encoded_len_u32(zigzag::encode_i32(value))
}

/// Encoded length of `value` as a zigzag `i64` varint, in bytes (1 to 10).
///
/// # Example
///
/// ```
/// use wire_codec::varint;
/// assert_eq!(varint::encoded_len_i64(-750), 2);
/// assert_eq!(varint::encoded_len_i64(i64::MIN), 10);
/// ```
#[inline]
#[must_use]
pub const fn encoded_len_i64(value: i64) -> usize {
    encoded_len_u64(zigzag::encode_i64(value))
}

/// Encode `value` as a `u16` varint into `buf`.
///
/// # Errors
///
/// Returns [`Error::BufferFull`] if `buf` has fewer than [`encoded_len_u16`]
/// bytes available. Nothing is written on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, WriteBuf};
/// let mut out = [0u8; 3];
/// let mut buf = WriteBuf::new(&mut out);
/// varint::encode_u16(300, &mut buf).unwrap();
/// assert_eq!(buf.written(), &[0xAC, 0x02]);
/// ```
#[inline]
pub fn encode_u16(value: u16, buf: &mut WriteBuf<'_>) -> Result<()> {
    encode_raw(u64::from(value), buf)
}

/// Encode `value` as a `u32` varint into `buf`.
///
/// # Errors
///
/// Returns [`Error::BufferFull`] if `buf` has fewer than [`encoded_len_u32`]
/// bytes available. Nothing is written on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, WriteBuf};
/// let mut out = [0u8; 5];
/// let mut buf = WriteBuf::new(&mut out);
/// varint::encode_u32(300, &mut buf).unwrap();
/// assert_eq!(buf.written(), &[0xAC, 0x02]);
/// ```
#[inline]
pub fn encode_u32(value: u32, buf: &mut WriteBuf<'_>) -> Result<()> {
    encode_raw(u64::from(value), buf)
}

/// Encode `value` as a `u64` varint into `buf`.
///
/// # Errors
///
/// Returns [`Error::BufferFull`] if `buf` has fewer than [`encoded_len_u64`]
/// bytes available. Nothing is written on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, WriteBuf};
/// let mut out = [0u8; varint::MAX_LEN_U64];
/// let mut buf = WriteBuf::new(&mut out);
/// varint::encode_u64(u64::MAX, &mut buf).unwrap();
/// assert_eq!(buf.position(), 10);
/// ```
#[inline]
pub fn encode_u64(value: u64, buf: &mut WriteBuf<'_>) -> Result<()> {
    encode_raw(value, buf)
}

/// Encode `value` as a `usize` varint into `buf`.
///
/// The wire format is identical to [`encode_u64`], so a value written on a
/// 64-bit host can be read by [`decode_usize`] on a 32-bit host whenever it
/// fits.
///
/// # Errors
///
/// Returns [`Error::BufferFull`] if `buf` has fewer than
/// [`encoded_len_usize`] bytes available. Nothing is written on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, WriteBuf};
/// let payload = b"hello";
/// let mut out = [0u8; 16];
/// let mut buf = WriteBuf::new(&mut out);
/// varint::encode_usize(payload.len(), &mut buf).unwrap();
/// assert_eq!(buf.written(), &[5]);
/// ```
#[inline]
pub fn encode_usize(value: usize, buf: &mut WriteBuf<'_>) -> Result<()> {
    // `usize` is at most 64 bits on every supported target.
    encode_raw(value as u64, buf)
}

/// Encode `value` as a zigzag `i32` varint (protobuf `sint32`) into `buf`.
///
/// # Errors
///
/// Returns [`Error::BufferFull`] if `buf` has fewer than [`encoded_len_i32`]
/// bytes available. Nothing is written on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, WriteBuf};
/// let mut out = [0u8; 5];
/// let mut buf = WriteBuf::new(&mut out);
/// varint::encode_i32(-2, &mut buf).unwrap();
/// assert_eq!(buf.written(), &[3]);
/// ```
#[inline]
pub fn encode_i32(value: i32, buf: &mut WriteBuf<'_>) -> Result<()> {
    encode_raw(u64::from(zigzag::encode_i32(value)), buf)
}

/// Encode `value` as a zigzag `i64` varint (protobuf `sint64`) into `buf`.
///
/// # Errors
///
/// Returns [`Error::BufferFull`] if `buf` has fewer than [`encoded_len_i64`]
/// bytes available. Nothing is written on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, WriteBuf};
/// let mut out = [0u8; 10];
/// let mut buf = WriteBuf::new(&mut out);
/// varint::encode_i64(-750, &mut buf).unwrap();
/// assert_eq!(buf.written(), &[0xDB, 0x0B]);
/// ```
#[inline]
pub fn encode_i64(value: i64, buf: &mut WriteBuf<'_>) -> Result<()> {
    encode_raw(zigzag::encode_i64(value), buf)
}

/// Decode a `u16` varint from `buf`.
///
/// # Errors
///
/// - [`Error::UnexpectedEof`] if `buf` is exhausted before the terminator byte.
/// - [`Error::VarintOverflow`] if the decoded value exceeds `u16::MAX` or if
///   more than [`MAX_LEN_U16`] bytes would be consumed.
///
/// The cursor is unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0xFF, 0xFF, 0x03]);
/// assert_eq!(varint::decode_u16(&mut buf).unwrap(), u16::MAX);
/// ```
#[inline]
pub fn decode_u16(buf: &mut ReadBuf<'_>) -> Result<u16> {
    // The width check inside `decode_with` guarantees the value fits.
    decode_with(buf, MAX_LEN_U16, u16::BITS, false).map(|v| v as u16)
}

/// Decode a `u32` varint from `buf`.
///
/// # Errors
///
/// - [`Error::UnexpectedEof`] if `buf` is exhausted before the terminator byte.
/// - [`Error::VarintOverflow`] if the decoded value exceeds `u32::MAX` or if
///   more than [`MAX_LEN_U32`] bytes would be consumed.
///
/// The cursor is unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0xAC, 0x02]);
/// assert_eq!(varint::decode_u32(&mut buf).unwrap(), 300);
/// ```
#[inline]
pub fn decode_u32(buf: &mut ReadBuf<'_>) -> Result<u32> {
    decode_with(buf, MAX_LEN_U32, u32::BITS, false).map(|v| v as u32)
}

/// Decode a `u64` varint from `buf`.
///
/// # Errors
///
/// - [`Error::UnexpectedEof`] if `buf` is exhausted before the terminator byte.
/// - [`Error::VarintOverflow`] if more than [`MAX_LEN_U64`] bytes would be
///   consumed or the final byte carries bits that would overflow `u64`.
///
/// The cursor is unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01];
/// let mut buf = ReadBuf::new(&bytes);
/// assert_eq!(varint::decode_u64(&mut buf).unwrap(), u64::MAX);
/// assert!(buf.is_empty());
/// ```
#[inline]
pub fn decode_u64(buf: &mut ReadBuf<'_>) -> Result<u64> {
    decode_with(buf, MAX_LEN_U64, u64::BITS, false)
}

/// Decode a `usize` varint from `buf`.
///
/// The bytes are parsed as a `u64` varint and then converted, so the
/// accepted wire format is the same on every target.
///
/// # Errors
///
/// - [`Error::UnexpectedEof`] if `buf` is exhausted before the terminator byte.
/// - [`Error::VarintOverflow`] if the value overflows `u64`, or does not fit
///   in `usize` on this target (values above `u32::MAX` on 32-bit hosts).
///
/// The cursor is unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x05, b'h', b'e', b'l', b'l', b'o']);
/// let len = varint::decode_usize(&mut buf).unwrap();
/// assert_eq!(buf.read_bytes(len).unwrap(), b"hello");
/// ```
#[inline]
pub fn decode_usize(buf: &mut ReadBuf<'_>) -> Result<usize> {
    decode_usize_with(buf, false)
}

/// Decode a zigzag `i32` varint (protobuf `sint32`) from `buf`.
///
/// # Errors
///
/// Same contract as [`decode_u32`]. The cursor is unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x03]);
/// assert_eq!(varint::decode_i32(&mut buf).unwrap(), -2);
/// ```
#[inline]
pub fn decode_i32(buf: &mut ReadBuf<'_>) -> Result<i32> {
    decode_u32(buf).map(zigzag::decode_i32)
}

/// Decode a zigzag `i64` varint (protobuf `sint64`) from `buf`.
///
/// # Errors
///
/// Same contract as [`decode_u64`]. The cursor is unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0xDB, 0x0B]);
/// assert_eq!(varint::decode_i64(&mut buf).unwrap(), -750);
/// ```
#[inline]
pub fn decode_i64(buf: &mut ReadBuf<'_>) -> Result<i64> {
    decode_u64(buf).map(zigzag::decode_i64)
}

/// Decode a `u16` varint, rejecting overlong encodings.
///
/// # Errors
///
/// Everything [`decode_u16`] returns, plus [`Error::InvalidEncoding`] when
/// the value is padded with redundant continuation bytes. The cursor is
/// unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, Error, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x80, 0x00]);
/// assert_eq!(varint::decode_u16_canonical(&mut buf), Err(Error::InvalidEncoding));
/// assert_eq!(buf.position(), 0);
/// ```
#[inline]
pub fn decode_u16_canonical(buf: &mut ReadBuf<'_>) -> Result<u16> {
    decode_with(buf, MAX_LEN_U16, u16::BITS, true).map(|v| v as u16)
}

/// Decode a `u32` varint, rejecting overlong encodings.
///
/// # Errors
///
/// Everything [`decode_u32`] returns, plus [`Error::InvalidEncoding`] when
/// the value is padded with redundant continuation bytes. The cursor is
/// unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, Error, ReadBuf};
/// // `[0x80, 0x80, 0x80, 0x80, 0x00]` is a five-byte encoding of zero.
/// let mut buf = ReadBuf::new(&[0x80, 0x80, 0x80, 0x80, 0x00]);
/// assert_eq!(varint::decode_u32_canonical(&mut buf), Err(Error::InvalidEncoding));
///
/// let mut buf = ReadBuf::new(&[0xAC, 0x02]);
/// assert_eq!(varint::decode_u32_canonical(&mut buf), Ok(300));
/// ```
#[inline]
pub fn decode_u32_canonical(buf: &mut ReadBuf<'_>) -> Result<u32> {
    decode_with(buf, MAX_LEN_U32, u32::BITS, true).map(|v| v as u32)
}

/// Decode a `u64` varint, rejecting overlong encodings.
///
/// # Errors
///
/// Everything [`decode_u64`] returns, plus [`Error::InvalidEncoding`] when
/// the value is padded with redundant continuation bytes. The cursor is
/// unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, Error, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x81, 0x00]);
/// assert_eq!(varint::decode_u64_canonical(&mut buf), Err(Error::InvalidEncoding));
/// ```
#[inline]
pub fn decode_u64_canonical(buf: &mut ReadBuf<'_>) -> Result<u64> {
    decode_with(buf, MAX_LEN_U64, u64::BITS, true)
}

/// Decode a `usize` varint, rejecting overlong encodings.
///
/// # Errors
///
/// Everything [`decode_usize`] returns, plus [`Error::InvalidEncoding`] when
/// the value is padded with redundant continuation bytes. The cursor is
/// unchanged on error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x05]);
/// assert_eq!(varint::decode_usize_canonical(&mut buf), Ok(5));
/// ```
#[inline]
pub fn decode_usize_canonical(buf: &mut ReadBuf<'_>) -> Result<usize> {
    decode_usize_with(buf, true)
}

/// Decode a zigzag `i32` varint, rejecting overlong encodings.
///
/// # Errors
///
/// Same contract as [`decode_u32_canonical`]. The cursor is unchanged on
/// error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x01]);
/// assert_eq!(varint::decode_i32_canonical(&mut buf), Ok(-1));
/// ```
#[inline]
pub fn decode_i32_canonical(buf: &mut ReadBuf<'_>) -> Result<i32> {
    decode_u32_canonical(buf).map(zigzag::decode_i32)
}

/// Decode a zigzag `i64` varint, rejecting overlong encodings.
///
/// # Errors
///
/// Same contract as [`decode_u64_canonical`]. The cursor is unchanged on
/// error.
///
/// # Example
///
/// ```
/// use wire_codec::{varint, ReadBuf};
/// let mut buf = ReadBuf::new(&[0x02]);
/// assert_eq!(varint::decode_i64_canonical(&mut buf), Ok(1));
/// ```
#[inline]
pub fn decode_i64_canonical(buf: &mut ReadBuf<'_>) -> Result<i64> {
    decode_u64_canonical(buf).map(zigzag::decode_i64)
}

/// Encode `value` straight into the unwritten tail of `buf`.
///
/// The length is computed up front, so there is a single capacity check and
/// nothing is written when it fails.
#[inline(always)]
fn encode_raw(mut value: u64, buf: &mut WriteBuf<'_>) -> Result<()> {
    let dst = buf.spare_mut();
    // With room for the longest encoding the length check is skipped; the
    // common case (a large output buffer) pays one comparison.
    if dst.len() < MAX_LEN_U64 && dst.len() < encoded_len_u64(value) {
        return Err(Error::BufferFull);
    }
    let mut i = 0;
    while value >= 0x80 {
        // Truncation to the low 7 bits is the encoding itself.
        dst[i] = (value as u8) | 0x80;
        value >>= 7;
        i += 1;
    }
    dst[i] = value as u8;
    buf.commit(i + 1);
    Ok(())
}

/// Decode from `buf`, committing the cursor only on success.
#[inline(always)]
fn decode_with(buf: &mut ReadBuf<'_>, max_len: usize, bits: u32, canonical: bool) -> Result<u64> {
    let (value, len) = decode_slice(buf.remaining_slice(), max_len, bits, canonical)?;
    buf.consume(len);
    Ok(value)
}

#[inline(always)]
fn decode_usize_with(buf: &mut ReadBuf<'_>, canonical: bool) -> Result<usize> {
    let (value, len) = decode_slice(buf.remaining_slice(), MAX_LEN_U64, u64::BITS, canonical)?;
    let value = usize::try_from(value).map_err(|_| Error::VarintOverflow)?;
    buf.consume(len);
    Ok(value)
}

/// Core LEB128 decoder over a plain slice.
///
/// Returns the decoded value and the number of bytes it occupied. `bits` is
/// the width of the target type; `max_len` is `ceil(bits / 7)`. The final
/// byte of a maximum-length encoding may only carry `bits - 7 * (max_len - 1)`
/// payload bits; anything above that overflows the target.
#[inline(always)]
pub(crate) fn decode_slice(
    bytes: &[u8],
    max_len: usize,
    bits: u32,
    canonical: bool,
) -> Result<(u64, usize)> {
    let mut value: u64 = 0;
    let mut shift: u32 = 0;
    for i in 0..max_len {
        let Some(&byte) = bytes.get(i) else {
            return Err(Error::UnexpectedEof);
        };
        value |= u64::from(byte & 0x7F) << shift;
        if byte & 0x80 == 0 {
            if i == max_len - 1 && u32::from(byte) >> (bits - shift) != 0 {
                return Err(Error::VarintOverflow);
            }
            if canonical && byte == 0 && i != 0 {
                return Err(Error::InvalidEncoding);
            }
            return Ok((value, i + 1));
        }
        shift += 7;
    }
    Err(Error::VarintOverflow)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn round_trip_u32(value: u32) {
        let mut storage = [0u8; MAX_LEN_U32];
        let mut w = WriteBuf::new(&mut storage);
        encode_u32(value, &mut w).unwrap();
        let n = w.position();
        assert_eq!(n, encoded_len_u32(value));
        let mut r = ReadBuf::new(&storage[..n]);
        assert_eq!(decode_u32(&mut r).unwrap(), value);
        assert!(r.is_empty());
        let mut r = ReadBuf::new(&storage[..n]);
        assert_eq!(decode_u32_canonical(&mut r).unwrap(), value);
    }

    fn round_trip_u64(value: u64) {
        let mut storage = [0u8; MAX_LEN_U64];
        let mut w = WriteBuf::new(&mut storage);
        encode_u64(value, &mut w).unwrap();
        let n = w.position();
        assert_eq!(n, encoded_len_u64(value));
        let mut r = ReadBuf::new(&storage[..n]);
        assert_eq!(decode_u64(&mut r).unwrap(), value);
        assert!(r.is_empty());
        let mut r = ReadBuf::new(&storage[..n]);
        assert_eq!(decode_u64_canonical(&mut r).unwrap(), value);
    }

    #[test]
    fn u32_boundaries() {
        for &v in &[
            0u32,
            1,
            127,
            128,
            16_383,
            16_384,
            2_097_151,
            2_097_152,
            u32::MAX,
        ] {
            round_trip_u32(v);
        }
    }

    #[test]
    fn u64_boundaries() {
        for &v in &[
            0u64,
            127,
            128,
            1 << 35,
            1 << 56,
            (1 << 63) - 1,
            1 << 63,
            u64::MAX,
        ] {
            round_trip_u64(v);
        }
    }

    #[test]
    fn u16_round_trip_and_bounds() {
        for v in [0u16, 1, 127, 128, 16_383, 16_384, u16::MAX] {
            let mut storage = [0u8; MAX_LEN_U16];
            let mut w = WriteBuf::new(&mut storage);
            encode_u16(v, &mut w).unwrap();
            let n = w.position();
            assert_eq!(n, encoded_len_u16(v));
            let mut r = ReadBuf::new(&storage[..n]);
            assert_eq!(decode_u16(&mut r).unwrap(), v);
            let mut r = ReadBuf::new(&storage[..n]);
            assert_eq!(decode_u16_canonical(&mut r).unwrap(), v);
        }
        // 0x04 in the third byte is bit 16: one past u16::MAX.
        let mut r = ReadBuf::new(&[0xFF, 0xFF, 0x04]);
        assert_eq!(decode_u16(&mut r), Err(Error::VarintOverflow));
        let mut r = ReadBuf::new(&[0x80, 0x80, 0x80, 0x00]);
        assert_eq!(decode_u16(&mut r), Err(Error::VarintOverflow));
    }

    #[test]
    fn signed_round_trip() {
        for v in [0i32, 1, -1, 63, -64, 64, -65, i32::MAX, i32::MIN] {
            let mut storage = [0u8; MAX_LEN_U32];
            let mut w = WriteBuf::new(&mut storage);
            encode_i32(v, &mut w).unwrap();
            let n = w.position();
            assert_eq!(n, encoded_len_i32(v));
            assert_eq!(decode_i32(&mut ReadBuf::new(&storage[..n])).unwrap(), v);
            assert_eq!(
                decode_i32_canonical(&mut ReadBuf::new(&storage[..n])).unwrap(),
                v
            );
        }
        for v in [0i64, 1, -1, i64::from(i32::MIN) - 1, i64::MAX, i64::MIN] {
            let mut storage = [0u8; MAX_LEN_U64];
            let mut w = WriteBuf::new(&mut storage);
            encode_i64(v, &mut w).unwrap();
            let n = w.position();
            assert_eq!(n, encoded_len_i64(v));
            assert_eq!(decode_i64(&mut ReadBuf::new(&storage[..n])).unwrap(), v);
            assert_eq!(
                decode_i64_canonical(&mut ReadBuf::new(&storage[..n])).unwrap(),
                v
            );
        }
    }

    #[test]
    fn usize_round_trip() {
        for v in [0usize, 1, 300, usize::MAX] {
            let mut storage = [0u8; MAX_LEN_U64];
            let mut w = WriteBuf::new(&mut storage);
            encode_usize(v, &mut w).unwrap();
            let n = w.position();
            assert_eq!(n, encoded_len_usize(v));
            assert_eq!(decode_usize(&mut ReadBuf::new(&storage[..n])).unwrap(), v);
            assert_eq!(
                decode_usize_canonical(&mut ReadBuf::new(&storage[..n])).unwrap(),
                v
            );
        }
    }

    #[test]
    fn usize_too_wide_for_target_overflows() {
        // 2^32 encoded as a u64 varint.
        let bytes = [0x80, 0x80, 0x80, 0x80, 0x10];
        let mut r = ReadBuf::new(&bytes);
        let result = decode_usize(&mut r);
        if usize::BITS > 32 {
            assert_eq!(result.map(|v| v as u64), Ok(1u64 << 32));
        } else {
            assert_eq!(result, Err(Error::VarintOverflow));
            assert_eq!(r.position(), 0);
        }
    }

    #[test]
    fn decode_u32_overflow_on_sixth_byte() {
        let mut buf = ReadBuf::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x01]);
        assert_eq!(decode_u32(&mut buf), Err(Error::VarintOverflow));
        assert_eq!(buf.position(), 0, "cursor is unchanged on error");
    }

    #[test]
    fn decode_u32_overflow_in_final_byte() {
        // Five bytes, terminator carries bits above the 32-bit window.
        for last in [0x10u8, 0x1F, 0x7F] {
            let bytes = [0xFF, 0xFF, 0xFF, 0xFF, last];
            let mut buf = ReadBuf::new(&bytes);
            assert_eq!(decode_u32(&mut buf), Err(Error::VarintOverflow));
        }
        let mut buf = ReadBuf::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
        assert_eq!(decode_u32(&mut buf), Ok(u32::MAX));
    }

    #[test]
    fn decode_u64_final_byte_rules() {
        let mut bytes = [0xFFu8; MAX_LEN_U64];
        for last in [0x02u8, 0x03, 0x7F, 0x81, 0x80] {
            bytes[9] = last;
            let mut buf = ReadBuf::new(&bytes);
            assert_eq!(
                decode_u64(&mut buf),
                Err(Error::VarintOverflow),
                "last={last:#x}"
            );
            assert_eq!(buf.position(), 0);
        }
        bytes[9] = 0x01;
        assert_eq!(decode_u64(&mut ReadBuf::new(&bytes)), Ok(u64::MAX));
        bytes[9] = 0x00;
        // Lenient accepts the overlong form; canonical rejects it.
        assert_eq!(decode_u64(&mut ReadBuf::new(&bytes)), Ok(u64::MAX >> 1));
        assert_eq!(
            decode_u64_canonical(&mut ReadBuf::new(&bytes)),
            Err(Error::InvalidEncoding)
        );
    }

    #[test]
    fn decode_truncated_leaves_cursor_unchanged() {
        // Continuation bit set on every byte present.
        let mut buf = ReadBuf::new(&[0x80, 0x80]);
        assert_eq!(decode_u32(&mut buf), Err(Error::UnexpectedEof));
        assert_eq!(buf.position(), 0);
        let mut buf = ReadBuf::new(&[]);
        assert_eq!(decode_u64(&mut buf), Err(Error::UnexpectedEof));
    }

    #[test]
    fn streaming_retry_after_eof_succeeds() {
        let wire = [0xAC, 0x02, 0x07];
        let mut filled = 0;
        let value = loop {
            let mut r = ReadBuf::new(&wire[..filled]);
            match decode_u32(&mut r) {
                Ok(v) => {
                    assert_eq!(r.position(), 2);
                    break v;
                }
                Err(Error::UnexpectedEof) => {
                    assert_eq!(r.position(), 0);
                    filled += 1;
                }
                Err(e) => panic!("unexpected {e}"),
            }
        };
        assert_eq!(value, 300);
        assert_eq!(filled, 2);
    }

    #[test]
    fn overlong_forms() {
        let cases: [&[u8]; 4] = [
            &[0x80, 0x00],
            &[0x81, 0x00],
            &[0x80, 0x80, 0x80, 0x80, 0x00],
            &[0xFF, 0x80, 0x00],
        ];
        for bytes in cases {
            assert!(decode_u32(&mut ReadBuf::new(bytes)).is_ok());
            let mut r = ReadBuf::new(bytes);
            assert_eq!(decode_u32_canonical(&mut r), Err(Error::InvalidEncoding));
            assert_eq!(r.position(), 0);
        }
        // A lone zero byte is the canonical encoding of 0.
        assert_eq!(decode_u32_canonical(&mut ReadBuf::new(&[0x00])), Ok(0));
        assert_eq!(
            decode_usize_canonical(&mut ReadBuf::new(&[0x80, 0x00])),
            Err(Error::InvalidEncoding)
        );
    }

    #[test]
    fn encode_is_atomic_on_buffer_full() {
        let mut storage = [0xEEu8; 1];
        let mut w = WriteBuf::new(&mut storage);
        assert_eq!(encode_u32(300, &mut w), Err(Error::BufferFull));
        assert_eq!(w.position(), 0);
        assert_eq!(storage, [0xEE], "nothing is written on error");

        let mut storage = [0u8; 9];
        let mut w = WriteBuf::new(&mut storage);
        assert_eq!(encode_u64(u64::MAX, &mut w), Err(Error::BufferFull));
        assert_eq!(w.position(), 0);

        let mut storage = [0u8; 0];
        let mut w = WriteBuf::new(&mut storage);
        assert_eq!(encode_u16(0, &mut w), Err(Error::BufferFull));
        assert_eq!(encode_i32(0, &mut w), Err(Error::BufferFull));
        assert_eq!(encode_i64(0, &mut w), Err(Error::BufferFull));
        assert_eq!(encode_usize(0, &mut w), Err(Error::BufferFull));
    }

    #[test]
    fn exact_wire_bytes() {
        let mut storage = [0u8; MAX_LEN_U64];
        let mut w = WriteBuf::new(&mut storage);
        encode_u64(0x80, &mut w).unwrap();
        assert_eq!(w.written(), &[0x80, 0x01]);
        let mut w = WriteBuf::new(&mut storage);
        encode_u32(u32::MAX, &mut w).unwrap();
        assert_eq!(w.written(), &[0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
    }
}