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

Assert in crc8::validate that buffer size is a multiple of 3 #13

Merged
merged 2 commits into from
Sep 1, 2020
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

This project follows [semantic versioning](https://semver.org/).

## [Unreleased]

## Changed

* Panic in `crc8::validate` if buffer size is not a multiple of 3
([#13](https://github.com/Sensirion/sensirion-i2c-rs/pull/13)

## [0.1.0] (2020-08-21)

* Initial version which implements the CRC-8 algorithm commonly used by
Expand Down
10 changes: 6 additions & 4 deletions src/crc8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ pub fn calculate(data: &[u8]) -> u8 {
/// is the checksum byte of the previous two bytes
/// If the checksum is wrong, return `Err`.
///
/// Note: This method will consider every third byte a checksum byte. If the buffer size is not a
/// multiple of 3, then not all data will be validated.
/// # Panics
///
/// This method will consider every third byte a checksum byte. If the buffer size is not a
/// multiple of 3, then it will panic.
pub fn validate(buf: &[u8]) -> Result<(), ()> {
debug_assert!(buf.len() % 3 == 0, "Buffer must be a multiple of 3");
assert!(buf.len() % 3 == 0, "Buffer must be a multiple of 3");
for chunk in buf.chunks(3) {
if chunk.len() == 3 && calculate(&[chunk[0], chunk[1]]) != chunk[2] {
if calculate(&[chunk[0], chunk[1]]) != chunk[2] {
return Err(());
}
}
Expand Down