Skip to content

Commit

Permalink
Merge pull request #23 from anti-social/fix-skipping-garbage
Browse files Browse the repository at this point in the history
Fix endless loop when skipping garbage
  • Loading branch information
tact1m4n3 authored Apr 25, 2024
2 parents ed6f51d + f11b6e5 commit 03f0ec9
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ impl PacketReader {
break;
}
}
continue;
if reader.is_empty() {
break None;
} else {
continue;
}
}
ReadState::WaitingForLen => {
if let Some(len_byte) = reader.next() {
Expand Down Expand Up @@ -336,6 +340,10 @@ impl<'a> BytesReader<'a> {
self.idx
}

fn is_empty(&self) -> bool {
self.idx == self.buf.len()
}

fn next(&mut self) -> Option<u8> {
if self.idx < self.buf.len() {
let val = self.buf[self.idx];
Expand Down Expand Up @@ -379,6 +387,30 @@ mod tests {
assert_eq!(reader.consumed(), 5);
}

#[test]
fn test_packet_reader_waiting_for_sync_byte() {
let mut reader = PacketReader::new();
let typ = PacketType::RcChannelsPacked;

// Garbage
assert!(reader.push_bytes(&[0, 1, 2, 3]).0.is_none());
// More garbage
assert!(reader.push_bytes(&[254, 255]).0.is_none());
// Sync
assert!(reader.push_bytes(&[PacketAddress::Handset as u8]).0.is_none());
// Len
assert!(reader.push_bytes(&[24]).0.is_none());
// Type
assert!(reader.push_bytes(&[typ as u8]).0.is_none());
// Payload
assert!(reader.push_bytes(&[0; 22]).0.is_none());
// Checksum
assert!(matches!(
reader.push_bytes(&[239]).0.map(|raw_packet| Packet::parse(raw_packet)).expect("packet expected"),
Ok(Packet::RcChannels(RcChannels(channels))) if channels == [0; 16]
));
}

#[test]
fn test_parse_next_packet() {
let mut reader = PacketReader::new();
Expand Down

0 comments on commit 03f0ec9

Please sign in to comment.