use core::{self, fmt};
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
Insufficient,
Overflow
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Insufficient => f.write_str("not enough input bytes"),
Error::Overflow => f.write_str("input bytes exceed maximum")
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
macro_rules! decode {
($buf:expr, $max_bytes:expr, $typ:ident) => {{
let mut n = 0;
for (i, b) in $buf.iter().cloned().enumerate() {
let k = $typ::from(b & 0x7F);
n |= k << (i * 7);
if is_last(b) {
return Ok((n, &$buf[i+1..]))
}
if i == $max_bytes {
return Err(Error::Overflow)
}
}
Err(Error::Insufficient)
}}
}
#[inline]
pub fn is_last(b: u8) -> bool {
b & 0x80 == 0
}
#[inline]
pub fn u8(buf: &[u8]) -> Result<(u8, &[u8]), Error> {
decode!(buf, 1, u8)
}
#[inline]
pub fn u16(buf: &[u8]) -> Result<(u16, &[u8]), Error> {
decode!(buf, 2, u16)
}
#[inline]
pub fn u32(buf: &[u8]) -> Result<(u32, &[u8]), Error> {
decode!(buf, 4, u32)
}
#[inline]
pub fn u64(buf: &[u8]) -> Result<(u64, &[u8]), Error> {
decode!(buf, 9, u64)
}
#[inline]
pub fn u128(buf: &[u8]) -> Result<(u128, &[u8]), Error> {
decode!(buf, 18, u128)
}
#[inline]
#[cfg(target_pointer_width = "64")]
pub fn usize(buf: &[u8]) -> Result<(usize, &[u8]), Error> {
u64(buf).map(|(n, i)| (n as usize, i))
}
#[inline]
#[cfg(target_pointer_width = "32")]
pub fn usize(buf: &[u8]) -> Result<(usize, &[u8]), Error> {
u32(buf).map(|(n, i)| (n as usize, i))
}