Skip to content

Commit

Permalink
Add a unit test for AlignedWriter and AlignedReader
Browse files Browse the repository at this point in the history
  • Loading branch information
HadrienG2 committed Nov 11, 2019
1 parent c5ce626 commit 31f4c76
Showing 1 changed file with 67 additions and 1 deletion.
68 changes: 67 additions & 1 deletion src/align/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<UMax>();

// 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::<UMax>::new(&mut bytes[..]);
let mut reader = AlignedReader::new(&mut aligned_bytes, max_align);

// Read back the data
unsafe {
assert_eq!(reader.read::<u8>().unwrap().as_ref(), &u1,
"8-bit number was read wrong");
assert_eq!(reader.read::<u64>().unwrap().as_ref(), &u2,
"64-bit number was read wrong");
let slice_ptr = reader.read_slice::<u32>(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");
}
}

0 comments on commit 31f4c76

Please sign in to comment.