bufkit 0.7.0

Memory-backed buffer toolkit with Chunk/ChunkMut traits for predictable, explicit, and retry-friendly access; ideal for Sans-I/O style protocol parsers, database engines, and embedded systems.
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
pub use varing::{
  ConstDecodeError as ConstDecodeVarintError, ConstEncodeError as ConstEncodeVarintError,
  DecodeError as DecodeVarintError, EncodeError as EncodeVarintError, InsufficientData,
  InsufficientSpace,
};

use core::num::NonZeroUsize;

macro_rules! try_op_error {
  (
    #[doc = $doc:literal]
    #[error($msg:literal)]
    $op:ident
  ) => {
    paste::paste! {
      #[doc = $doc]
      #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
      #[error($msg)]
      pub struct [< Try $op:camel Error >] {
        requested: NonZeroUsize,
        available: usize,
      }

      impl [< Try $op:camel Error >] {
        #[doc = "Creates a new `Try" $op:camel "Error` with the requested and available bytes."]
        ///
        /// # Panics
        ///
        /// - If `requested <= available` (this would not be an error condition).
        /// - The `requested` value must be a non-zero.
        #[inline]
        pub const fn new(requested: NonZeroUsize, available: usize) -> Self {
          assert!(requested.get() > available, concat!(stringify!([< Try $op:camel Error >]), ": requested must be greater than available"));

          Self {
            requested,
            available,
          }
        }

        /// Returns the number of bytes requested for the operation.
        ///
        /// This is the minimum number of bytes needed for the operation to succeed.
        #[inline]
        pub const fn requested(&self) -> NonZeroUsize {
          self.requested
        }

        /// Returns the number of bytes available in the buffer.
        ///
        /// This is the actual number of bytes that were available when the operation failed.
        #[inline]
        pub const fn available(&self) -> usize {
          self.available
        }
      }
    }
  };
}

try_op_error!(
  #[doc = "An error that occurs when trying to advance the buffer cursor beyond available data.
  
This error indicates that an attempt was made to move the buffer's read position forward
by more bytes than are currently available. This is a recoverable error - the buffer
position remains unchanged and the operation can be retried with a smaller advance amount."]
  #[error(
    "not enough bytes available to advance (requested {requested} but only {available} available)"
  )]
  advance
);

#[cfg(feature = "std")]
impl From<TryAdvanceError> for std::io::Error {
  fn from(e: TryAdvanceError) -> Self {
    std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)
  }
}

try_op_error!(
  #[doc = "An error that occurs when trying to read data from a buffer with insufficient bytes.
  
This error indicates that a read operation failed because the buffer does not contain
enough bytes to satisfy the request. Failed read operations do not consume any bytes - the buffer position remains unchanged."]
  #[error(
    "not enough bytes available to read value (requested {requested} but only {available} available)"
  )]
  read
);

#[cfg(feature = "std")]
impl From<TryReadError> for std::io::Error {
  fn from(e: TryReadError) -> Self {
    std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)
  }
}

try_op_error!(
  #[doc = "An error that occurs when trying to peek at data beyond the buffer's available bytes.
  
This error indicates that a peek operation failed because the buffer does not contain
enough bytes at the current position. Peek operations never modify the buffer position,
so this error leaves the buffer in its original state."]
  #[error(
    "not enough bytes available to peek value (requested {requested} but only {available} available)"
  )]
  peek
);

#[cfg(feature = "std")]
impl From<TryPeekError> for std::io::Error {
  fn from(e: TryPeekError) -> Self {
    std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)
  }
}

impl From<TryPeekError> for TryReadError {
  #[inline]
  fn from(e: TryPeekError) -> Self {
    TryReadError {
      requested: e.requested,
      available: e.available,
    }
  }
}

/// An error that occurs when trying to create a segment with an invalid range.
///
/// This error indicates that the requested range extends beyond the buffer's boundaries
/// or is otherwise invalid (e.g., start > end). The original buffer remains unchanged.
///
/// # Examples
///
/// ```rust
/// # use bufkit::Chunk;
/// let data = b"Hello";
/// let buf = &data[..];
///
/// // Range extends beyond buffer
/// match buf.try_segment(2..10) {
///     Err(e) => {
///         assert_eq!(e.start(), 2);
///         assert_eq!(e.end(), 10);
///         assert_eq!(e.available(), 5);
///     }
///     _ => panic!("Expected error"),
/// }
///
/// // Invalid range (start > end)
/// assert!(buf.try_segment(4..2).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("invalid segment range {start}..{end} for buffer with {available} bytes")]
pub struct TrySegmentError {
  start: usize,
  end: usize,
  available: usize,
}

impl TrySegmentError {
  /// Creates a new `TrySegmentError`.
  ///
  /// # Panics
  ///
  /// In debug builds, panics if the range is valid (would not be an error) or the available bytes are less than the requested range.
  #[inline]
  pub const fn new(start: usize, end: usize, available: usize) -> Self {
    debug_assert!(
      start > end || end > available,
      "TrySegmentError: invalid error - range is valid"
    );

    Self {
      start,
      end,
      available,
    }
  }

  /// Returns the start index of the requested range.
  #[inline]
  pub const fn start(&self) -> usize {
    self.start
  }

  /// Returns the end index of the requested range (exclusive).
  #[inline]
  pub const fn end(&self) -> usize {
    self.end
  }

  /// Returns the total number of bytes available in the buffer.
  #[inline]
  pub const fn available(&self) -> usize {
    self.available
  }

  /// Returns the length of the requested range.
  ///
  /// Returns 0 if start > end (invalid range).
  #[inline]
  pub const fn requested(&self) -> usize {
    self.end.saturating_sub(self.start)
  }

  /// Returns whether the range itself is invalid (start > end).
  #[inline]
  pub const fn is_inverted(&self) -> bool {
    self.start > self.end
  }

  /// Returns how many bytes the range extends beyond the buffer.
  ///
  /// Returns 0 if the range doesn't extend beyond the buffer
  /// (e.g., when the error is due to start > end).
  #[inline]
  pub const fn overflow(&self) -> usize {
    self.end.saturating_sub(self.available)
  }
}

#[cfg(feature = "std")]
impl From<TrySegmentError> for std::io::Error {
  fn from(e: TrySegmentError) -> Self {
    std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
  }
}

/// An error that occurs when an offset is beyond the buffer's boundaries.
///
/// This error is typically used for operations that access a specific position
/// in the buffer, such as writing at an offset or splitting at a position.
///
/// # Example
///
/// ```rust
/// # use bufkit::ChunkMut;
/// let mut buf = [0u8; 10];
/// let mut writer = &mut buf[..];
///
/// // Trying to write at offset 15 in a 10-byte buffer
/// match writer.try_put_u32_le_at(42, 15) {
///     Err(e) => {
///         // Error contains OutOfBounds information
///     }
///     _ => panic!("Expected error"),
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("offset {offset} is out of bounds for buffer length {length}")]
pub struct OutOfBounds {
  offset: usize,
  length: usize,
}

impl OutOfBounds {
  /// Creates a new `OutOfBounds` error.
  ///
  /// # Panics
  ///
  /// In debug builds, panics if `offset < length` (would not be out of bounds).
  #[inline]
  pub const fn new(offset: usize, length: usize) -> Self {
    debug_assert!(offset >= length, "OutOfBounds: offset must be >= length");

    Self { offset, length }
  }

  /// Returns the offset that caused the error.
  #[inline]
  pub const fn offset(&self) -> usize {
    self.offset
  }

  /// Returns the actual length of the buffer.
  #[inline]
  pub const fn length(&self) -> usize {
    self.length
  }

  /// Returns how far beyond the buffer the offset extends.
  ///
  /// This is equivalent to `offset() - length() + 1`.
  #[inline]
  pub const fn excess(&self) -> usize {
    self.offset() - self.length() + 1
  }
}

#[cfg(feature = "std")]
impl From<OutOfBounds> for std::io::Error {
  fn from(e: OutOfBounds) -> Self {
    std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
  }
}

/// An error indicating insufficient space at a specific offset in a buffer.
///
/// This error provides detailed information about space requirements when a write
/// operation fails due to insufficient remaining capacity from a given offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error(
  "not enough bytes available at {offset} (requested {} but only {} available)",
  self.info.requested(), self.info.available()
)]
pub struct InsufficientSpaceAt {
  info: InsufficientSpace,
  /// The offset at which the write was attempted.
  offset: usize,
}

impl InsufficientSpaceAt {
  /// Creates a new `InsufficientSpaceAt` error.
  ///
  /// # Panics
  ///
  /// - If `requested <= available` (would not be an error).
  /// - The `requested` value must be a non-zero.
  #[inline]
  pub const fn new(requested: NonZeroUsize, available: usize, offset: usize) -> Self {
    assert!(
      requested.get() > available,
      "InsufficientSpaceAt: requested must be greater than available"
    );

    Self {
      info: InsufficientSpace::new(requested, available),
      offset,
    }
  }

  /// Returns the number of bytes requested to write.
  #[inline]
  pub const fn requested(&self) -> NonZeroUsize {
    self.info.requested()
  }

  /// Returns the number of bytes available from the offset.
  #[inline]
  pub const fn available(&self) -> usize {
    self.info.available()
  }

  /// Returns the offset at which the write was attempted.
  #[inline]
  pub const fn offset(&self) -> usize {
    self.offset
  }
}

/// An error indicating insufficient data available at a specific offset in a buffer.
///
/// This error provides detailed information about data requirements when a read
/// operation fails due to insufficient remaining capacity from a given offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InsufficientDataAt {
  info: InsufficientData,
  /// The offset at which the read was attempted.
  offset: usize,
}

impl core::fmt::Display for InsufficientDataAt {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self.requested() {
      Some(requested) => write!(
        f,
        "not enough bytes available at {}: available {}, requested {}",
        self.offset,
        self.info.available(),
        requested
      ),
      None => write!(
        f,
        "not enough bytes available at {}: available {}",
        self.offset,
        self.info.available()
      ),
    }
  }
}

impl core::error::Error for InsufficientDataAt {}

impl InsufficientDataAt {
  /// Creates a new `InsufficientDataAt` error.
  ///
  /// - `available`: the number of bytes available from the offset.
  /// - `offset`: the offset at which the read was attempted.
  #[inline]
  pub const fn new(available: usize, offset: usize) -> Self {
    Self {
      info: InsufficientData::new(available),
      offset,
    }
  }

  /// Creates a new `InsufficientDataAt` error with a specific requested size.
  ///
  /// # Panics
  ///
  /// - If `requested <= available` (would not be an error).
  #[inline]
  pub const fn with_requested(available: usize, offset: usize, requested: NonZeroUsize) -> Self {
    assert!(
      requested.get() > available,
      "InsufficientDataAt: requested must be greater than available"
    );

    Self {
      info: InsufficientData::with_required(requested, available),
      offset,
    }
  }

  /// Returns the number of bytes requested to read.
  #[inline]
  pub const fn requested(&self) -> Option<NonZeroUsize> {
    self.info.required()
  }

  /// Returns the number of bytes available from the offset.
  #[inline]
  pub const fn available(&self) -> usize {
    self.info.available()
  }

  /// Returns the offset at which the read was attempted.
  #[inline]
  pub const fn offset(&self) -> usize {
    self.offset
  }
}

#[cfg(feature = "std")]
impl From<InsufficientDataAt> for std::io::Error {
  fn from(e: InsufficientDataAt) -> Self {
    std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)
  }
}

/// An error that occurs when trying to peek at a specific offset in the buffer.
///
/// This error is returned when the offset is out of bounds or when there is insufficient data to peek the requested data.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TryPeekAtError {
  /// An error that occurs when trying to peek at an offset that is out of bounds for the buffer.
  #[error(transparent)]
  OutOfBounds(#[from] OutOfBounds),
  /// An error that occurs when there is not enough data in the buffer to peek the requested data.
  #[error(transparent)]
  InsufficientData(#[from] InsufficientDataAt),
}

impl TryPeekAtError {
  /// Creates a new `TryPeekAtError::OutOfBounds` error.
  #[inline]
  pub const fn out_of_bounds(offset: usize, length: usize) -> Self {
    Self::OutOfBounds(OutOfBounds::new(offset, length))
  }

  /// Creates a new `TryPeekAtError::InsufficientData` error.
  ///
  /// # Panics
  ///
  /// - In debug builds, panics if `requested <= available` (would not be an error).
  /// - The `requested` value must be a non-zero.
  #[inline]
  pub const fn insufficient_data(available: usize, offset: usize) -> Self {
    Self::InsufficientData(InsufficientDataAt::new(available, offset))
  }

  /// Creates a new `TryPeekAtError::InsufficientData` error.
  ///
  /// # Panics
  ///
  /// - In debug builds, panics if `requested <= available` (would not be an error).
  /// - The `requested` value must be a non-zero.
  #[inline]
  pub const fn insufficient_data_with_requested(
    available: usize,
    offset: usize,
    requested: NonZeroUsize,
  ) -> Self {
    Self::InsufficientData(InsufficientDataAt::with_requested(
      available, offset, requested,
    ))
  }
}

#[cfg(feature = "std")]
impl From<TryPeekAtError> for std::io::Error {
  fn from(e: TryPeekAtError) -> Self {
    std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)
  }
}

/// An error that occurs when trying to write at a specific offset in the buffer.
///
/// This error is returned when the offset is out of bounds or when there is insufficient space to write the requested data.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum TryPutAtError {
  /// An error that occurs when trying to write at an offset that is out of bounds for the buffer.
  #[error(transparent)]
  OutOfBounds(#[from] OutOfBounds),
  /// An error that occurs when there is not enough space in the buffer to write the requested data.
  #[error(transparent)]
  InsufficientSpace(#[from] InsufficientSpaceAt),
}

impl TryPutAtError {
  /// Creates a new `TryPutAtError::OutOfBounds` error.
  #[inline]
  pub const fn out_of_bounds(offset: usize, length: usize) -> Self {
    Self::OutOfBounds(OutOfBounds::new(offset, length))
  }

  /// Creates a new `TryPutAtError::InsufficientSpace` error.
  ///
  /// # Panics
  ///
  /// - In debug builds, panics if `requested <= available` (would not be an error).
  /// - The `requested` value must be a non-zero.
  #[inline]
  pub const fn insufficient_space(
    requested: NonZeroUsize,
    available: usize,
    offset: usize,
  ) -> Self {
    Self::InsufficientSpace(InsufficientSpaceAt::new(requested, available, offset))
  }
}

#[cfg(feature = "std")]
impl From<TryPutAtError> for std::io::Error {
  fn from(e: TryPutAtError) -> Self {
    match e {
      TryPutAtError::OutOfBounds(e) => std::io::Error::new(std::io::ErrorKind::InvalidInput, e),
      TryPutAtError::InsufficientSpace(e) => {
        if e.offset() >= e.available() {
          std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
        } else {
          std::io::Error::new(std::io::ErrorKind::WriteZero, e)
        }
      }
    }
  }
}

/// An error that occurs when trying to put type in LEB128 format at a specific offset in the buffer.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EncodeVarintAtError {
  /// The offset is out of bounds for the buffer length.
  #[error(transparent)]
  OutOfBounds(#[from] OutOfBounds),
  /// The buffer does not have enough capacity to encode the value.
  #[error(transparent)]
  InsufficientSpace(#[from] InsufficientSpaceAt),
  /// A custom error message.
  #[error("{0}")]
  #[cfg(not(any(feature = "std", feature = "alloc")))]
  Other(&'static str),

  /// A custom error message.
  #[error("{0}")]
  #[cfg(any(feature = "std", feature = "alloc"))]
  Other(std::borrow::Cow<'static, str>),
}

impl EncodeVarintAtError {
  /// Creates a new `EncodeVarintAtError::OutOfBounds` error.
  #[inline]
  pub const fn out_of_bounds(offset: usize, length: usize) -> Self {
    Self::OutOfBounds(OutOfBounds::new(offset, length))
  }

  /// Creates a new `EncodeVarintAtError::Insufficient` error.
  ///
  /// # Panics
  ///
  /// - If `requested <= available` (would not be an error).
  #[inline]
  pub const fn insufficient_space(
    requested: NonZeroUsize,
    available: usize,
    offset: usize,
  ) -> Self {
    Self::InsufficientSpace(InsufficientSpaceAt::new(requested, available, offset))
  }

  /// Creates a new `EncodeVarintAtError` error from `EncodeVarintError`.
  #[inline]
  pub fn from_varint_error(err: EncodeVarintError, offset: usize) -> Self {
    match err {
      EncodeVarintError::InsufficientSpace(e) => {
        Self::insufficient_space(e.requested(), e.available(), offset)
      }
      EncodeVarintError::Other(msg) => Self::Other(msg),
      _ => Self::other("unknown error"),
    }
  }

  /// Creates a new `EncodeVarintAtError` error from `ConstEncodeVarintError`.
  #[inline]
  pub const fn from_const_varint_error(err: ConstEncodeVarintError, offset: usize) -> Self {
    match err {
      ConstEncodeVarintError::InsufficientSpace(e) => {
        Self::insufficient_space(e.requested(), e.available(), offset)
      }
      #[cfg(not(any(feature = "std", feature = "alloc")))]
      ConstEncodeVarintError::Other(msg) => Self::Other(msg),
      #[cfg(any(feature = "std", feature = "alloc"))]
      ConstEncodeVarintError::Other(msg) => Self::Other(std::borrow::Cow::Borrowed(msg)),
      #[cfg(not(any(feature = "std", feature = "alloc")))]
      _ => Self::other("unknown error"),
      #[cfg(any(feature = "std", feature = "alloc"))]
      _ => Self::Other(std::borrow::Cow::Borrowed("unknown error")),
    }
  }

  /// Creates a new `EncodeVarintAtError::Other` error.
  #[cfg(not(any(feature = "std", feature = "alloc")))]
  #[inline]
  pub const fn other(msg: &'static str) -> Self {
    Self::Other(msg)
  }

  /// Creates a new `EncodeVarintAtError::Other` error.
  #[cfg(any(feature = "std", feature = "alloc"))]
  #[inline]
  pub fn other(msg: impl Into<std::borrow::Cow<'static, str>>) -> Self {
    Self::Other(msg.into())
  }
}

#[cfg(feature = "std")]
impl From<EncodeVarintAtError> for std::io::Error {
  fn from(e: EncodeVarintAtError) -> Self {
    match e {
      EncodeVarintAtError::OutOfBounds(e) => {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
      }
      EncodeVarintAtError::InsufficientSpace(e) => {
        if e.offset() >= e.available() {
          std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
        } else {
          std::io::Error::new(std::io::ErrorKind::WriteZero, e)
        }
      }
      EncodeVarintAtError::Other(msg) => std::io::Error::other(msg),
    }
  }
}

/// An error that occurs when trying to put type in LEB128 format at a specific offset in the buffer.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DecodeVarintAtError {
  /// The offset is out of bounds for the buffer length.
  #[error(transparent)]
  OutOfBounds(#[from] OutOfBounds),
  /// The buffer does not have enough capacity to encode the value.
  #[error(transparent)]
  InsufficientData(#[from] InsufficientDataAt),
  /// A custom error message.
  #[error("{0}")]
  #[cfg(not(any(feature = "std", feature = "alloc")))]
  Other(&'static str),

  /// A custom error message.
  #[error("{0}")]
  #[cfg(any(feature = "std", feature = "alloc"))]
  Other(std::borrow::Cow<'static, str>),
}

impl DecodeVarintAtError {
  /// Creates a new `DecodeVarintAtError::OutOfBounds` error.
  #[inline]
  pub const fn out_of_bounds(offset: usize, length: usize) -> Self {
    Self::OutOfBounds(OutOfBounds::new(offset, length))
  }

  /// Creates a new `DecodeVarintAtError::Insufficient` error.
  ///
  /// # Panics
  ///
  /// - In debug builds, panics if `requested <= available` (would not be an error).
  /// - The `requested` value must be a non-zero.
  #[inline]
  pub const fn insufficient_data(available: usize, offset: usize) -> Self {
    Self::InsufficientData(InsufficientDataAt::new(available, offset))
  }

  /// Creates a new `DecodeVarintAtError` error from `EncodeVarintError`.
  #[inline]
  pub fn from_varint_error(err: DecodeVarintError, offset: usize) -> Self {
    match err {
      DecodeVarintError::InsufficientData(e) => Self::insufficient_data(e.available(), offset),
      DecodeVarintError::Other(msg) => Self::other(msg),
      _ => Self::other("unknown error"),
    }
  }

  /// Creates a new `DecodeVarintAtError::Other` error from `ConstDecodeVarintError`.
  #[inline]
  pub const fn from_const_varint_error(err: ConstDecodeVarintError, offset: usize) -> Self {
    match err {
      ConstDecodeVarintError::InsufficientData(e) => Self::insufficient_data(e.available(), offset),
      #[cfg(not(any(feature = "std", feature = "alloc")))]
      ConstDecodeVarintError::Other(msg) => Self::Other(msg),
      #[cfg(any(feature = "std", feature = "alloc"))]
      ConstDecodeVarintError::Other(msg) => Self::Other(std::borrow::Cow::Borrowed(msg)),
      #[cfg(not(any(feature = "std", feature = "alloc")))]
      _ => Self::other("unknown error"),
      #[cfg(any(feature = "std", feature = "alloc"))]
      _ => Self::Other(std::borrow::Cow::Borrowed("unknown error")),
    }
  }

  /// Creates a new `DecodeVarintAtError::Other` error.
  #[cfg(not(any(feature = "std", feature = "alloc")))]
  #[inline]
  pub const fn other(msg: &'static str) -> Self {
    Self::Other(msg)
  }

  /// Creates a new `DecodeVarintAtError::Other` error.
  #[cfg(any(feature = "std", feature = "alloc"))]
  #[inline]
  pub fn other(msg: impl Into<std::borrow::Cow<'static, str>>) -> Self {
    Self::Other(msg.into())
  }
}

#[cfg(feature = "std")]
impl From<DecodeVarintAtError> for std::io::Error {
  fn from(e: DecodeVarintAtError) -> Self {
    match e {
      DecodeVarintAtError::Other(msg) => std::io::Error::other(msg),
      _ => std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e),
    }
  }
}

#[cfg(feature = "bytes_1")]
const _: () = {
  use bytes_1::TryGetError;

  impl From<TryGetError> for TryAdvanceError {
    fn from(e: TryGetError) -> Self {
      TryAdvanceError::new(
        NonZeroUsize::new(e.requested).expect("requested must be non-zero"),
        e.available,
      )
    }
  }

  impl From<TryGetError> for TryReadError {
    fn from(e: TryGetError) -> Self {
      TryReadError::new(
        NonZeroUsize::new(e.requested).expect("requested must be non-zero"),
        e.available,
      )
    }
  }
};