Skip to content

Commit

Permalink
Add specific error for Crc errors. (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
CBJamo authored and jamesmunns committed Aug 31, 2023
1 parent a9ca950 commit b58972c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/de/flavors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ pub mod crc {
if crc == prev_crc {
Ok(remainder)
} else {
Err(Error::DeserializeBadEncoding)
Err(Error::DeserializeBadCrc)
}
}
e @ Err(_) => e,
Expand Down
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub enum Error {
DeserializeBadEnum,
/// The original data was not well encoded
DeserializeBadEncoding,
/// Bad CRC while deserializing
DeserializeBadCrc,
/// Serde Serialization Error
SerdeSerCustom,
/// Serde Deserialization Error
Expand Down Expand Up @@ -60,6 +62,7 @@ impl Display for Error {
DeserializeBadOption => "Found an Option discriminant that wasn't 0 or 1",
DeserializeBadEnum => "Found an enum discriminant that was > u32::max_value()",
DeserializeBadEncoding => "The original data was not well encoded",
DeserializeBadCrc => "Bad CRC while deserializing",
SerdeSerCustom => "Serde Serialization Error",
SerdeDeCustom => "Serde Deserialization Error",
CollectStrError => "Error while processing `collect_str` during serialization",
Expand Down
21 changes: 21 additions & 0 deletions tests/crc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,24 @@ fn test_crc_8() {
let remaining_bytes = [];
assert_eq!(res, (expected_bytes, remaining_bytes.as_slice()));
}

#[test]
#[cfg(feature = "use-crc")]
fn test_crc_error() {
use crc::{Crc, CRC_32_ISCSI};

let data: &[u8] = &[0x01, 0x00, 0x20, 0x30];
let buffer = &mut [0u8; 32];
let crc = Crc::<u32>::new(&CRC_32_ISCSI);
let digest = crc.digest();
let res = postcard::to_slice_crc32(data, buffer, digest).unwrap();

// intentionally corrupt the crc
let last = res.len() - 1;
res[last] = 0;

let digest = crc.digest();
let res = postcard::take_from_bytes_crc32::<[u8; 5]>(&res, digest);

assert_eq!(res, Err(postcard::Error::DeserializeBadCrc));
}

0 comments on commit b58972c

Please sign in to comment.