feat: clean up errors

This commit is contained in:
rvcas
2022-06-04 14:01:45 -04:00
parent 377c5c206c
commit 1ecd47a361
15 changed files with 294 additions and 204 deletions

View File

@@ -5,4 +5,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[dependencies]
anyhow = "1.0.57"
thiserror = "1.0.31"

View File

@@ -1,11 +1,17 @@
use crate::{decoder::Decoder, filler::Filler};
mod decoder;
mod error;
use crate::filler::Filler;
pub use decoder::Decoder;
pub use error::Error;
pub trait Decode<'b>: Sized {
fn decode(d: &mut Decoder) -> Result<Self, String>;
fn decode(d: &mut Decoder) -> Result<Self, Error>;
}
impl Decode<'_> for Filler {
fn decode(d: &mut Decoder) -> Result<Filler, String> {
fn decode(d: &mut Decoder) -> Result<Filler, Error> {
d.filler()?;
Ok(Filler::FillerEnd)
@@ -13,43 +19,43 @@ impl Decode<'_> for Filler {
}
impl Decode<'_> for Vec<u8> {
fn decode(d: &mut Decoder) -> Result<Self, String> {
fn decode(d: &mut Decoder) -> Result<Self, Error> {
d.bytes()
}
}
impl Decode<'_> for u8 {
fn decode(d: &mut Decoder) -> Result<Self, String> {
fn decode(d: &mut Decoder) -> Result<Self, Error> {
d.u8()
}
}
impl Decode<'_> for isize {
fn decode(d: &mut Decoder) -> Result<Self, String> {
fn decode(d: &mut Decoder) -> Result<Self, Error> {
d.integer()
}
}
impl Decode<'_> for usize {
fn decode(d: &mut Decoder) -> Result<Self, String> {
fn decode(d: &mut Decoder) -> Result<Self, Error> {
d.word()
}
}
impl Decode<'_> for char {
fn decode(d: &mut Decoder) -> Result<Self, String> {
fn decode(d: &mut Decoder) -> Result<Self, Error> {
d.char()
}
}
impl Decode<'_> for String {
fn decode(d: &mut Decoder) -> Result<Self, String> {
fn decode(d: &mut Decoder) -> Result<Self, Error> {
d.utf8()
}
}
impl Decode<'_> for bool {
fn decode(d: &mut Decoder) -> Result<bool, String> {
fn decode(d: &mut Decoder) -> Result<bool, Error> {
d.bool()
}
}

View File

@@ -1,5 +1,7 @@
use crate::{decode::Decode, zigzag};
use super::Error;
pub struct Decoder<'b> {
buffer: &'b [u8],
used_bits: i64,
@@ -15,35 +17,38 @@ impl<'b> Decoder<'b> {
}
}
pub fn decode<T: Decode<'b>>(&mut self) -> Result<T, String> {
/// Encode any type that implements [`Decode`].
pub fn decode<T: Decode<'b>>(&mut self) -> Result<T, Error> {
T::decode(self)
}
pub fn integer(&mut self) -> Result<isize, String> {
pub fn integer(&mut self) -> Result<isize, Error> {
Ok(zigzag::to_isize(self.word()?))
}
pub fn bool(&mut self) -> Result<bool, String> {
pub fn bool(&mut self) -> Result<bool, Error> {
let current_byte = self.buffer[self.pos];
let b = 0 != (current_byte & (128 >> self.used_bits));
self.increment_buffer_by_bit();
Ok(b)
}
pub fn u8(&mut self) -> Result<u8, String> {
pub fn u8(&mut self) -> Result<u8, Error> {
self.bits8(8)
}
pub fn bytes(&mut self) -> Result<Vec<u8>, String> {
pub fn bytes(&mut self) -> Result<Vec<u8>, Error> {
self.filler()?;
self.byte_array()
}
pub fn char(&mut self) -> Result<char, String> {
Ok(char::from_u32(self.word()? as u32).unwrap())
pub fn char(&mut self) -> Result<char, Error> {
let character = self.word()? as u32;
char::from_u32(character).ok_or(Error::DecodeChar(character))
}
pub fn string(&mut self) -> Result<String, String> {
pub fn string(&mut self) -> Result<String, Error> {
let mut s = String::new();
while self.bit()? {
s += &self.char()?.to_string();
@@ -51,17 +56,17 @@ impl<'b> Decoder<'b> {
Ok(s)
}
pub fn utf8(&mut self) -> Result<String, String> {
pub fn utf8(&mut self) -> Result<String, Error> {
// TODO: Better Error Handling
Ok(String::from_utf8(Vec::<u8>::decode(self)?).unwrap())
String::from_utf8(Vec::<u8>::decode(self)?).map_err(Error::from)
}
pub fn filler(&mut self) -> Result<(), String> {
pub fn filler(&mut self) -> Result<(), Error> {
while self.zero()? {}
Ok(())
}
pub fn word(&mut self) -> Result<usize, String> {
pub fn word(&mut self) -> Result<usize, Error> {
let mut leading_bit = 1;
let mut final_word: usize = 0;
let mut shl: usize = 0;
@@ -78,8 +83,8 @@ impl<'b> Decoder<'b> {
pub fn decode_list_with<T: Decode<'b>>(
&mut self,
decoder_func: for<'r> fn(&'r mut Decoder) -> Result<T, String>,
) -> Result<Vec<T>, String> {
decoder_func: for<'r> fn(&'r mut Decoder) -> Result<T, Error>,
) -> Result<Vec<T>, Error> {
let mut vec_array: Vec<T> = Vec::new();
while self.bit()? {
vec_array.push(decoder_func(self)?)
@@ -87,46 +92,60 @@ impl<'b> Decoder<'b> {
Ok(vec_array)
}
fn zero(&mut self) -> Result<bool, String> {
fn zero(&mut self) -> Result<bool, Error> {
let current_bit = self.bit()?;
Ok(!current_bit)
}
fn bit(&mut self) -> Result<bool, String> {
fn bit(&mut self) -> Result<bool, Error> {
if self.pos >= self.buffer.len() {
return Err("DecoderState: Reached end of buffer".to_string());
return Err(Error::EndOfBuffer);
}
let b = self.buffer[self.pos] & (128 >> self.used_bits) > 0;
self.increment_buffer_by_bit();
Ok(b)
}
fn byte_array(&mut self) -> Result<Vec<u8>, String> {
fn byte_array(&mut self) -> Result<Vec<u8>, Error> {
if self.used_bits != 0 {
return Err("DecoderState.byteArray: Buffer is not byte aligned".to_string());
return Err(Error::BufferNotByteAligned);
}
self.ensure_bytes(1)?;
let mut blk_len = self.buffer[self.pos];
self.pos += 1;
let mut blk_array: Vec<u8> = Vec::new();
while blk_len != 0 {
self.ensure_bytes(blk_len as usize + 1)?;
let decoded_array = &self.buffer[self.pos..self.pos + blk_len as usize];
blk_array.extend(decoded_array);
self.pos += blk_len as usize;
blk_len = self.buffer[self.pos];
}
Ok(blk_array)
}
// can decode up to a max of 8 bits
pub fn bits8(&mut self, num_bits: usize) -> Result<u8, String> {
pub fn bits8(&mut self, num_bits: usize) -> Result<u8, Error> {
if num_bits > 8 {
return Err(
"Decoder.bits8: incorrect value of num_bits - must be less than 9".to_string(),
);
return Err(Error::IncorrectNumBits);
}
self.ensure_bits(num_bits)?;
let unused_bits = 8 - self.used_bits as usize;
let leading_zeroes = 8 - num_bits;
let r = (self.buffer[self.pos] << self.used_bits as usize) >> leading_zeroes;
@@ -136,30 +155,28 @@ impl<'b> Decoder<'b> {
} else {
r
};
self.drop_bits(num_bits);
Ok(x)
}
fn ensure_bytes(&mut self, required_bytes: usize) -> Result<(), String> {
fn ensure_bytes(&mut self, required_bytes: usize) -> Result<(), Error> {
if required_bytes as isize > self.buffer.len() as isize - self.pos as isize {
return Err(format!(
"DecoderState: Not enough data available: {:#?} - required bytes {}",
self.buffer, required_bytes
));
Err(Error::NotEnoughBytes(required_bytes))
} else {
Ok(())
}
Ok(())
}
fn ensure_bits(&mut self, required_bits: usize) -> Result<(), String> {
fn ensure_bits(&mut self, required_bits: usize) -> Result<(), Error> {
if required_bits as isize
> (self.buffer.len() as isize - self.pos as isize) * 8 - self.used_bits as isize
{
return Err(format!(
"DecoderState: Not enough data available: {:#?} - required bits {}",
self.buffer, required_bits
));
Err(Error::NotEnoughBits(required_bits))
} else {
Ok(())
}
Ok(())
}
fn drop_bits(&mut self, num_bits: usize) {

View File

@@ -0,0 +1,23 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("Reached end of buffer")]
EndOfBuffer,
#[error("Buffer is not byte aligned")]
BufferNotByteAligned,
#[error("Incorrect value of num_bits, must be less than 9")]
IncorrectNumBits,
#[error("Not enough data available, required {0} bytes")]
NotEnoughBytes(usize),
#[error("Not enough data available, required {0} bits")]
NotEnoughBits(usize),
#[error(transparent)]
DecodeUtf8(#[from] std::string::FromUtf8Error),
#[error("Decoding u32 to char {0}")]
DecodeChar(u32),
#[error("{0}")]
Message(String),
#[error(transparent)]
Custom(#[from] anyhow::Error),
}

View File

@@ -1,11 +1,17 @@
use crate::{encoder::Encoder, filler::Filler};
mod encoder;
mod error;
use crate::filler::Filler;
pub use encoder::Encoder;
pub use error::Error;
pub trait Encode {
fn encode(&self, e: &mut Encoder) -> Result<(), String>;
fn encode(&self, e: &mut Encoder) -> Result<(), Error>;
}
impl Encode for bool {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.bool(*self);
Ok(())
@@ -13,7 +19,7 @@ impl Encode for bool {
}
impl Encode for u8 {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.u8(*self)?;
Ok(())
@@ -21,15 +27,15 @@ impl Encode for u8 {
}
impl Encode for isize {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
e.integer(*self)?;
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.integer(*self);
Ok(())
}
}
impl Encode for usize {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.word(*self);
Ok(())
@@ -37,15 +43,15 @@ impl Encode for usize {
}
impl Encode for char {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
e.char(*self)?;
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.char(*self);
Ok(())
}
}
impl Encode for &str {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.utf8(self)?;
Ok(())
@@ -53,7 +59,7 @@ impl Encode for &str {
}
impl Encode for String {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.utf8(self)?;
Ok(())
@@ -61,7 +67,7 @@ impl Encode for String {
}
impl Encode for Vec<u8> {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.bytes(self)?;
Ok(())
@@ -69,7 +75,7 @@ impl Encode for Vec<u8> {
}
impl Encode for &[u8] {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.bytes(self)?;
Ok(())
@@ -77,7 +83,7 @@ impl Encode for &[u8] {
}
impl<T: Encode> Encode for Box<T> {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
self.as_ref().encode(e)?;
Ok(())
@@ -85,7 +91,7 @@ impl<T: Encode> Encode for Box<T> {
}
impl Encode for Filler {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
fn encode(&self, e: &mut Encoder) -> Result<(), Error> {
e.filler();
Ok(())

View File

@@ -1,5 +1,7 @@
use crate::{encode::Encode, zigzag};
use super::Error;
pub struct Encoder {
pub buffer: Vec<u8>,
// Int
@@ -24,12 +26,13 @@ impl Encoder {
}
/// Encode any type that implements [`Encode`].
pub fn encode<T: Encode>(&mut self, x: T) -> Result<&mut Self, String> {
pub fn encode<T: Encode>(&mut self, x: T) -> Result<&mut Self, Error> {
x.encode(self)?;
Ok(self)
}
pub fn u8(&mut self, x: u8) -> Result<&mut Self, String> {
pub fn u8(&mut self, x: u8) -> Result<&mut Self, Error> {
if self.used_bits == 0 {
self.current_byte = x;
self.next_word();
@@ -51,93 +54,54 @@ impl Encoder {
self
}
pub fn bytes(&mut self, x: &[u8]) -> Result<&mut Self, String> {
pub fn bytes(&mut self, x: &[u8]) -> Result<&mut Self, Error> {
// use filler to write current buffer so bits used gets reset
self.filler();
self.byte_array(x)
}
pub fn byte_array(&mut self, arr: &[u8]) -> Result<&mut Self, String> {
pub fn byte_array(&mut self, arr: &[u8]) -> Result<&mut Self, Error> {
if self.used_bits != 0 {
return Err("Buffer is not byte aligned".to_string());
return Err(Error::BufferNotByteAligned);
}
self.write_blk(arr, &mut 0);
Ok(self)
}
pub fn integer(&mut self, i: isize) -> Result<&mut Self, String> {
pub fn integer(&mut self, i: isize) -> &mut Self {
let i = zigzag::to_usize(i);
self.word(i);
Ok(self)
self
}
pub fn char(&mut self, c: char) -> Result<&mut Self, String> {
pub fn char(&mut self, c: char) -> &mut Self {
self.word(c as usize);
Ok(self)
self
}
// TODO: Do we need this?
pub fn string(&mut self, s: &str) -> Result<&mut Self, String> {
pub fn string(&mut self, s: &str) -> &mut Self {
for i in s.chars() {
self.one();
self.char(i)?;
self.char(i);
}
self.zero();
Ok(self)
self
}
pub fn utf8(&mut self, s: &str) -> Result<&mut Self, String> {
pub fn utf8(&mut self, s: &str) -> Result<&mut Self, Error> {
self.bytes(s.as_bytes())
}
fn zero(&mut self) {
if self.used_bits == 7 {
self.next_word();
} else {
self.used_bits += 1;
}
}
fn one(&mut self) {
if self.used_bits == 7 {
self.current_byte |= 1;
self.next_word();
} else {
self.current_byte |= 128 >> self.used_bits;
self.used_bits += 1;
}
}
fn byte_unaligned(&mut self, x: u8) {
let x_shift = self.current_byte | (x >> self.used_bits);
self.buffer.push(x_shift);
self.current_byte = x << (8 - self.used_bits);
}
fn next_word(&mut self) {
self.buffer.push(self.current_byte);
self.current_byte = 0;
self.used_bits = 0;
}
fn write_blk(&mut self, arr: &[u8], src_ptr: &mut usize) {
let src_len = arr.len() - *src_ptr;
let blk_len = src_len.min(255);
self.buffer.push(blk_len as u8);
if blk_len == 0 {
return;
}
self.buffer.extend(&arr[*src_ptr..blk_len]);
*src_ptr += blk_len;
self.write_blk(arr, src_ptr);
}
pub fn word(&mut self, c: usize) {
pub fn word(&mut self, c: usize) -> &mut Self {
loop {
let mut w = (c & 127) as u8;
let c = c >> 7;
@@ -151,22 +115,26 @@ impl Encoder {
break;
}
}
self
}
pub fn encode_list_with(
&mut self,
encoder_func: for<'r> fn(u8, &'r mut Encoder) -> Result<(), String>,
list: Vec<u8>,
) -> Result<(), String> {
encoder_func: for<'r> fn(u8, &'r mut Encoder) -> Result<(), Error>,
) -> Result<&mut Self, Error> {
for item in list {
self.one();
encoder_func(item, self)?;
}
self.zero();
Ok(())
Ok(self)
}
pub fn bits(&mut self, num_bits: i64, val: u8) {
pub fn bits(&mut self, num_bits: i64, val: u8) -> &mut Self {
match (num_bits, val) {
(1, 0) => self.zero(),
(1, 1) => self.one(),
@@ -207,10 +175,63 @@ impl Encoder {
}
}
}
self
}
pub(crate) fn filler(&mut self) {
pub(crate) fn filler(&mut self) -> &mut Self {
self.current_byte |= 1;
self.next_word();
self
}
fn zero(&mut self) {
if self.used_bits == 7 {
self.next_word();
} else {
self.used_bits += 1;
}
}
fn one(&mut self) {
if self.used_bits == 7 {
self.current_byte |= 1;
self.next_word();
} else {
self.current_byte |= 128 >> self.used_bits;
self.used_bits += 1;
}
}
fn byte_unaligned(&mut self, x: u8) {
let x_shift = self.current_byte | (x >> self.used_bits);
self.buffer.push(x_shift);
self.current_byte = x << (8 - self.used_bits);
}
fn next_word(&mut self) {
self.buffer.push(self.current_byte);
self.current_byte = 0;
self.used_bits = 0;
}
fn write_blk(&mut self, arr: &[u8], src_ptr: &mut usize) {
let src_len = arr.len() - *src_ptr;
let blk_len = src_len.min(255);
self.buffer.push(blk_len as u8);
if blk_len == 0 {
return;
}
self.buffer.extend(&arr[*src_ptr..blk_len]);
*src_ptr += blk_len;
self.write_blk(arr, src_ptr);
}
}

View File

@@ -0,0 +1,11 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("Buffer is not byte aligned")]
BufferNotByteAligned,
#[error("{0}")]
Message(String),
#[error(transparent)]
Custom(#[from] anyhow::Error),
}

View File

@@ -1,13 +1,13 @@
pub enum Filler {
// FillerStart(Box<Filler>),
FillerStart(Box<Filler>),
FillerEnd,
}
// impl Filler {
// pub fn len(&self) -> usize {
// match self {
// Filler::FillerStart(f) => f.len() + 1,
// Filler::FillerEnd => 1,
// }
// }
// }
impl Filler {
pub fn length(&self) -> usize {
match self {
Filler::FillerStart(f) => f.length() + 1,
Filler::FillerEnd => 1,
}
}
}

View File

@@ -1,31 +1,27 @@
mod decode;
mod decoder;
mod encode;
mod encoder;
mod filler;
pub mod filler;
pub mod zigzag;
pub mod en {
pub use super::encode::*;
pub use super::encoder::*;
}
pub mod de {
pub use super::decode::*;
pub use super::decoder::*;
}
pub trait Flat<'b>: en::Encode + de::Decode<'b> {
fn flat(&self) -> Result<Vec<u8>, String> {
fn flat(&self) -> Result<Vec<u8>, en::Error> {
encode(self)
}
fn unflat(bytes: &'b [u8]) -> Result<Self, String> {
fn unflat(bytes: &'b [u8]) -> Result<Self, de::Error> {
decode(bytes)
}
}
pub fn encode<T>(value: &T) -> Result<Vec<u8>, String>
pub fn encode<T>(value: &T) -> Result<Vec<u8>, en::Error>
where
T: en::Encode,
{
@@ -37,7 +33,7 @@ where
Ok(e.buffer)
}
pub fn decode<'b, T>(bytes: &'b [u8]) -> Result<T, String>
pub fn decode<'b, T>(bytes: &'b [u8]) -> Result<T, de::Error>
where
T: de::Decode<'b>,
{