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: Checksum check on decoder #14

Merged
merged 2 commits into from
Apr 4, 2024
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: 5 additions & 2 deletions src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::message::{ProtocolMessage, HEADER};
pub enum ParseError {
InvalidStartByte,
IncompleteData,
ChecksumError,
ChecksumError(ProtocolMessage),
}

#[derive(Debug)]
Expand Down Expand Up @@ -89,9 +89,12 @@ impl Decoder {
self.buffer.push(byte);
if self.buffer.len() == 2 {
self.message.checksum = u16::from_le_bytes([self.buffer[0], self.buffer[1]]);
self.reset();
let message = self.message.clone();
self.message = ProtocolMessage::new();
self.reset();
if !message.has_valid_crc() {
return DecoderResult::Error(ParseError::ChecksumError(message));
}
return DecoderResult::Success(message);
}
return DecoderResult::InProgress;
Expand Down
17 changes: 17 additions & 0 deletions tests/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ fn test_simple_deserialization() {
panic!("Failed to use decoder with valid message");
};

// Retry with a wrong receipt CRC
for byte in &buffer[0..buffer.len() - 2] {
dbg!(byte, &decoder.state);
assert!(matches!(
decoder.parse_byte(byte.clone()),
DecoderResult::InProgress
));
}
assert!(matches!(
decoder.parse_byte(buffer[buffer.len() - 2]),
DecoderResult::InProgress
));
assert!(matches!(
decoder.parse_byte(0x01), // force a crc error
DecoderResult::Error(ParseError::ChecksumError(_))
));

// Wrong CRC test
let buffer: Vec<u8> = vec![
0x42, 0x52, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x05, 0x00, 0xa1, 0x01,
Expand Down
Loading