From 2b50419947185eb62f142e4e7a78b95af63bb6a1 Mon Sep 17 00:00:00 2001 From: Zachary Dremann Date: Fri, 15 May 2020 16:56:36 -0400 Subject: [PATCH 1/2] Add some simple crc32 reader tests --- src/crc32.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/crc32.rs b/src/crc32.rs index d84af9a1..0bc60f5d 100644 --- a/src/crc32.rs +++ b/src/crc32.rs @@ -50,3 +50,40 @@ impl Read for Crc32Reader Ok(count) } } + +#[cfg(test)] +mod tests +{ + use super::*; + use std::io::Read; + use std::io::Cursor; + + #[test] + fn test_empty_reader() + { + let data: &[u8] = b""; + let mut buf = [0; 1]; + + let mut reader = Crc32Reader::new(data, 0); + assert_eq!(reader.read(&mut buf).unwrap(), 0); + + let mut reader = Crc32Reader::new(data, 1); + assert!(reader.read(&mut buf).unwrap_err().to_string().contains("Invalid checksum")); + } + + #[test] + fn test_byte_by_byte() + { + let data: &[u8] = b"1234"; + let mut buf = [0; 1]; + + let mut reader = Crc32Reader::new(data, 0x9be3e0a3); + assert_eq!(reader.read(&mut buf).unwrap(), 1); + assert_eq!(reader.read(&mut buf).unwrap(), 1); + assert_eq!(reader.read(&mut buf).unwrap(), 1); + assert_eq!(reader.read(&mut buf).unwrap(), 1); + assert_eq!(reader.read(&mut buf).unwrap(), 0); + // Can keep reading 0 bytes after the end + assert_eq!(reader.read(&mut buf).unwrap(), 0); + } +} From b3c836d9c32efa120cdd5366280f940d3c3b985c Mon Sep 17 00:00:00 2001 From: Zachary Dremann Date: Fri, 15 May 2020 17:05:26 -0400 Subject: [PATCH 2/2] Ensure crc32 checksum is checked only at the end of the reader The caller can pass in an empty slice for reading, which should return `Ok(0)`, not raise an error about an invalid checksum prematurely --- src/crc32.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/crc32.rs b/src/crc32.rs index 0bc60f5d..ed0101e6 100644 --- a/src/crc32.rs +++ b/src/crc32.rs @@ -42,7 +42,7 @@ impl Read for Crc32Reader { let count = match self.inner.read(buf) { - Ok(0) if !self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) }, + Ok(0) if !buf.is_empty() && !self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) }, Ok(n) => n, Err(e) => return Err(e), }; @@ -52,7 +52,7 @@ impl Read for Crc32Reader } #[cfg(test)] -mod tests +mod test { use super::*; use std::io::Read; @@ -86,4 +86,15 @@ mod tests // Can keep reading 0 bytes after the end assert_eq!(reader.read(&mut buf).unwrap(), 0); } + + #[test] + fn test_zero_read() + { + let data: &[u8] = b"1234"; + let mut buf = [0; 5]; + + let mut reader = Crc32Reader::new(data, 0x9be3e0a3); + assert_eq!(reader.read(&mut buf[..0]).unwrap(), 0); + assert_eq!(reader.read(&mut buf).unwrap(), 4); + } }