Try get methods for Buf trait (#753)

This commit is contained in:
hpenne
2025-01-21 13:41:42 +01:00
committed by GitHub
parent a1b1208127
commit 3ab876fee6
4 changed files with 1604 additions and 46 deletions
+37 -2
View File
@@ -132,12 +132,47 @@ fn min_u64_usize(a: u64, b: usize) -> usize {
}
}
/// Error type for the `try_get_` methods of [`Buf`].
/// Indicates that there were not enough remaining
/// bytes in the buffer while attempting
/// to get a value from a [`Buf`] with one
/// of the `try_get_` methods.
#[derive(Debug, PartialEq, Eq)]
pub struct TryGetError {
/// The number of bytes necessary to get the value
pub requested: usize,
/// The number of bytes available in the buffer
pub available: usize,
}
impl core::fmt::Display for TryGetError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
write!(
f,
"Not enough bytes remaining in buffer to read value (requested {} but only {} available)",
self.requested,
self.available
)
}
}
#[cfg(feature = "std")]
impl std::error::Error for TryGetError {}
#[cfg(feature = "std")]
impl From<TryGetError> for std::io::Error {
fn from(error: TryGetError) -> Self {
std::io::Error::new(std::io::ErrorKind::Other, error)
}
}
/// Panic with a nice error message.
#[cold]
fn panic_advance(idx: usize, len: usize) -> ! {
fn panic_advance(error_info: &TryGetError) -> ! {
panic!(
"advance out of bounds: the len is {} but advancing by {}",
len, idx
error_info.available, error_info.requested
);
}