Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add reason enum to use instead of string value for error messages #127

Merged
merged 2 commits into from
Feb 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 65 additions & 28 deletions src/serde_bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,28 +59,50 @@ pub trait DeBin: Sized {
fn de_bin(offset: &mut usize, bytes: &[u8]) -> Result<Self, DeBinErr>;
}

/// The error message when failing to deserialize from raw bytes.
#[derive(Clone)]
#[non_exhaustive]
pub enum DeBinErrReason {
Length {
/// Expected Length
expected_length: usize,
/// Actual Length
actual_length: usize,
},
}

/// The error message when failing to deserialize.
#[derive(Clone)]
pub struct DeBinErr {
/// Offset
pub o: usize,
pub l: usize,
pub s: usize,
pub msg: DeBinErrReason,
}

impl DeBinErr {
pub fn new(o: usize, l: usize, s: usize) -> Self {
Self { o, l, s }
/// Helper for constructing [`DeBinErr`]
pub fn new(offset: usize, expected_length: usize, actual_length: usize) -> Self {
Self {
o: offset,
msg: DeBinErrReason::Length {
expected_length,
actual_length,
},
}
}
}

impl core::fmt::Debug for DeBinErr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"Bin deserialize error at:{} wanted:{} bytes but max size is {}",
self.o, self.l, self.s
)
match self.msg {
DeBinErrReason::Length {
expected_length: l,
actual_length: s,
} => write!(
f,
"Bin deserialize error at:{} wanted:{} bytes but max size is {}",
self.o, l, s
),
}
}
}

Expand All @@ -103,20 +125,23 @@ macro_rules! impl_ser_de_bin_for {

impl DeBin for $ty {
fn de_bin(o: &mut usize, d: &[u8]) -> Result<$ty, DeBinErr> {
let l = core::mem::size_of::<$ty>();
if *o + l > d.len() {
let expected_length = core::mem::size_of::<$ty>();
if *o + expected_length > d.len() {
return Err(DeBinErr {
o: *o,
l,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length,
actual_length: d.len(),
},
});
}

// We just checked that the correct amount of bytes are available,
// and there are no invalid bit patterns for these primitives. This
// unwrap should be impossible to hit.
let ret: $ty = <$ty>::from_le_bytes(d[*o..(*o + l)].try_into().unwrap());
*o += l;
let ret: $ty =
<$ty>::from_le_bytes(d[*o..(*o + expected_length)].try_into().unwrap());
*o += expected_length;
Ok(ret)
}
}
Expand Down Expand Up @@ -152,8 +177,10 @@ impl DeBin for usize {
None => {
return Err(DeBinErr {
o: *o,
l,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length: l,
actual_length: d.len(),
},
});
}
};
Expand All @@ -168,8 +195,10 @@ impl DeBin for u8 {
if *o + 1 > d.len() {
return Err(DeBinErr {
o: *o,
l: 1,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length: 1,
actual_length: d.len(),
},
});
}
let m = d[*o];
Expand All @@ -195,8 +224,10 @@ impl DeBin for bool {
if *o + 1 > d.len() {
return Err(DeBinErr {
o: *o,
l: 1,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length: 1,
actual_length: d.len(),
},
});
}
let m = d[*o];
Expand All @@ -223,17 +254,21 @@ impl DeBin for String {
if *o + len > d.len() {
return Err(DeBinErr {
o: *o,
l: 1,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length: 1,
actual_length: d.len(),
},
});
}
let r = match core::str::from_utf8(&d[*o..(*o + len)]) {
Ok(r) => r.to_owned(),
Err(_) => {
return Err(DeBinErr {
o: *o,
l: len,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length: len,
actual_length: d.len(),
},
})
}
};
Expand Down Expand Up @@ -374,8 +409,10 @@ where
if *o + 1 > d.len() {
return Err(DeBinErr {
o: *o,
l: 1,
s: d.len(),
msg: DeBinErrReason::Length {
expected_length: 1,
actual_length: d.len(),
},
});
}
let m = d[*o];
Expand Down
60 changes: 46 additions & 14 deletions src/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub trait DeJson: Sized {
}

/// A JSON parsed token.
#[derive(PartialEq, Debug, Default)]
#[derive(PartialEq, Debug, Default, Clone)]
#[non_exhaustive]
pub enum DeJsonTok {
Str,
Expand Down Expand Up @@ -142,23 +142,55 @@ pub struct DeJsonState {
pub col: usize,
}

/// The error message when failing to deserialize a JSON string.
#[derive(Clone)]
#[non_exhaustive]
pub enum DeJsonErrReason {
UnexpectedKey(String),
UnexpectedToken(DeJsonTok, String),
MissingKey(String),
NoSuchEnum(String),
OutOfRange(String),
WrongType(String),
CannotParse(String),
}

/// The error message when failing to deserialize a JSON string.
#[derive(Clone)]
pub struct DeJsonErr {
pub msg: String,
pub line: usize,
pub col: usize,
pub msg: DeJsonErrReason,
}

impl core::fmt::Debug for DeJsonErrReason {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::UnexpectedKey(name) => write!(f, "Unexpected key {}", name),
Self::MissingKey(name) => write!(f, "Key not found {}", name),
Self::NoSuchEnum(name) => write!(f, "Enum not defined {}", name),
Self::UnexpectedToken(token, name) => {
write!(f, "Unexpected token {:?} expected {} ", token, name)
}
Self::OutOfRange(value) => write!(f, "Value out of range {} ", value),
Self::WrongType(found) => write!(f, "Token wrong type {} ", found),
Self::CannotParse(unparseable) => write!(f, "Cannot parse {} ", unparseable),
}
}
}

impl core::fmt::Debug for DeJsonErr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let DeJsonErr {
line,
col: column,
msg: reason,
} = self;
write!(
f,
"Json Deserialize error: {}, line:{} col:{}",
self.msg,
self.line + 1,
self.col + 1
"Json Deserialize error: {:?}, line:{} col:{}",
reason,
line + 1,
column + 1
)
}
}
Expand Down Expand Up @@ -188,55 +220,55 @@ impl DeJsonState {

pub fn err_exp(&self, name: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Unexpected key {}", name),
msg: DeJsonErrReason::UnexpectedKey(name.to_string()),
line: self.line,
col: self.col,
}
}

pub fn err_nf(&self, name: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Key not found {}", name),
msg: DeJsonErrReason::MissingKey(name.to_string()),
line: self.line,
col: self.col,
}
}

pub fn err_enum(&self, name: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Enum not defined {}", name),
msg: DeJsonErrReason::NoSuchEnum(name.to_string()),
line: self.line,
col: self.col,
}
}

pub fn err_token(&self, what: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Unexpected token {:?} expected {} ", self.tok, what),
msg: DeJsonErrReason::UnexpectedToken(self.tok.clone(), what.to_string()),
line: self.line,
col: self.col,
}
}

pub fn err_range(&self, what: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Value out of range {} ", what),
msg: DeJsonErrReason::OutOfRange(what.to_string()),
line: self.line,
col: self.col,
}
}

pub fn err_type(&self, what: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Token wrong type {} ", what),
msg: DeJsonErrReason::WrongType(what.to_string()),
line: self.line,
col: self.col,
}
}

pub fn err_parse(&self, what: &str) -> DeJsonErr {
DeJsonErr {
msg: format!("Cannot parse {} ", what),
msg: DeJsonErrReason::CannotParse(what.to_string()),
line: self.line,
col: self.col,
}
Expand Down
Loading
Loading