Skip to content

Instantly share code, notes, and snippets.

@lac5
Last active June 17, 2024 15:15
Show Gist options
  • Save lac5/d3691e6286cb0653f8b294a983b3e0f8 to your computer and use it in GitHub Desktop.
Save lac5/d3691e6286cb0653f8b294a983b3e0f8 to your computer and use it in GitHub Desktop.
use std::fmt;
use std::error::Error;
type Buffer = Vec<u8>;
pub trait ReadU24BE {
fn read_u24_be(&self, pos: usize) -> Result<u32, OutOfRangeError>;
}
impl ReadU24BE for Buffer {
fn read_u24_be(&self, offset: usize) -> Result<u32, OutOfRangeError> {
let len = self.len();
if len - offset < 3 {
return Err(OutOfRangeError::new(len - 3, offset));
}
let mut sum: u32 = 0;
sum |= u32::from(self[offset+0]) << 16;
sum |= u32::from(self[offset+1]) << 8;
sum |= u32::from(self[offset+2]) << 0;
Ok(sum)
}
}
#[derive(Debug)]
pub struct OutOfRangeError {
max: usize,
received: usize,
}
impl OutOfRangeError {
pub fn new(max: usize, received: usize) -> Self {
Self { max, received }
}
}
impl fmt::Display for OutOfRangeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "The offset is out of range. It must be <= {}. Received {}", self.max, self.received)
}
}
impl Error for OutOfRangeError {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment