From 31f4c76963e95f9e89b49a4cbd8bb4359298c3e7 Mon Sep 17 00:00:00 2001 From: Hadrien G Date: Mon, 11 Nov 2019 20:29:14 +0100 Subject: [PATCH] Add a unit test for AlignedWriter and AlignedReader --- src/align/io.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/src/align/io.rs b/src/align/io.rs index 8e29d8b..ad943a4 100644 --- a/src/align/io.rs +++ b/src/align/io.rs @@ -239,4 +239,70 @@ impl<'bytes> AlignedReader<'bytes> { } -// TODO: Add some tests +#[cfg(test)] +mod tests { + use crate::align::AlignedBytes; + use super::{AlignedReader, AlignedWriter}; + + #[test] + fn round_trip() { + // We'll write the following binary data down + let u1 = 0x42u8; + let u2 = 0x12345678_9abcdef0_u64; + let u3s = [0x13579bdf_u32, 0x2468ace0_u32]; + type UMax = u64; + let max_align = std::mem::align_of::(); + + // Build a writer for it + let mut bytes = Vec::new(); + let mut writer = AlignedWriter::new(&mut bytes, max_align); + + // Write it down + unsafe { + writer.write(&u1).unwrap(); + writer.write(&u2).unwrap(); + writer.write_slice(&u3s[..]).unwrap(); + } + + // Check written bytes counter + let written = writer.written_so_far(); + std::mem::drop(writer); + assert_eq!(written, bytes.len(), + "Number of reported written bytes is wrong"); + assert_eq!(written, 1 + 7 + 8 + 4 + 4, + "Reported written bytes does not match written data"); + + // Check written data + assert_eq!(bytes[0], u1, + "8-bit number was written wrong"); + assert_eq!(bytes[1..8], [0, 0, 0, 0, 0, 0, 0], + "Padding for 64-bit number was written wrong"); + assert_eq!(bytes[8..16], u2.to_ne_bytes(), + "64-bit number was written wrong"); + assert_eq!(bytes[16..20], u3s[0].to_ne_bytes(), + "First 32-bit number was written wrong"); + assert_eq!(bytes[20..24], u3s[1].to_ne_bytes(), + "Second 32-bit number was written wrong"); + + // Prepare to read back the data + let mut aligned_bytes = AlignedBytes::::new(&mut bytes[..]); + let mut reader = AlignedReader::new(&mut aligned_bytes, max_align); + + // Read back the data + unsafe { + assert_eq!(reader.read::().unwrap().as_ref(), &u1, + "8-bit number was read wrong"); + assert_eq!(reader.read::().unwrap().as_ref(), &u2, + "64-bit number was read wrong"); + let slice_ptr = reader.read_slice::(u3s.len()).unwrap(); + let slice = std::slice::from_raw_parts(slice_ptr.as_ptr(), + u3s.len()); + assert_eq!(slice, &u3s, + "32-bit numbers were read wrong"); + } + + // Make sure that we consumed all the bytes + assert_eq!(reader.remaining(), &[], + "No bytes should remain"); + } +}