use fs_core::error::Error;
mod common;
#[test]
fn a_read_at_a_wild_offset_is_a_short_read_not_a_panic() {
let bytes = [0xABu8; 8];
for offset in [u64::MAX, u64::MAX - 7, 1 << 40, 9] {
let mut buf = [0u8; 8];
match common::read_into(&bytes, offset, &mut buf).expect_err("past the end") {
Error::ShortRead {
offset: o,
want,
got,
} => {
assert_eq!((o, want), (offset, 8));
assert_eq!(got, 0, "nothing is available at {offset}");
}
other => panic!("expected ShortRead at {offset}, got {other:?}"),
}
assert_eq!(buf, [0u8; 8], "a refused read leaves the buffer alone");
}
}
#[test]
fn a_length_that_overflows_when_added_to_the_offset_is_refused() {
let bytes = [0xABu8; 8];
let mut buf = vec![0u8; 16];
let offset = u64::MAX - 8;
match common::read_into(&bytes, offset, &mut buf).expect_err("cannot fit") {
Error::ShortRead { want, got, .. } => assert_eq!((want, got), (16, 0)),
other => panic!("expected ShortRead, got {other:?}"),
}
}
#[test]
fn a_write_at_a_wild_offset_is_refused_rather_than_panicking() {
let mut bytes = [0u8; 8];
for offset in [u64::MAX, u64::MAX - 7, 1 << 40, 9] {
match common::write_from(&mut bytes, offset, &[1u8; 8]).expect_err("past the end") {
Error::ShortRead {
offset: o, want, ..
} => assert_eq!((o, want), (offset, 8)),
other => panic!("expected ShortRead at {offset}, got {other:?}"),
}
}
assert_eq!(bytes, [0u8; 8], "no refused write reached the buffer");
common::write_from(&mut bytes, 4, &[9u8; 4]).expect("inside the buffer");
assert_eq!(bytes, [0, 0, 0, 0, 9, 9, 9, 9]);
}
#[test]
fn a_read_beginning_inside_the_buffer_that_overruns_it_copies_nothing() {
let bytes = [0xABu8; 8];
for (offset, available) in [(0u64, 8usize), (1, 7), (7, 1)] {
let mut buf = [0u8; 16];
match common::read_into(&bytes, offset, &mut buf).expect_err("overruns the end") {
Error::ShortRead {
offset: o,
want,
got,
} => {
assert_eq!((o, want), (offset, 16));
assert_eq!(
got, 0,
"{available} bytes were available from {offset}, and none of them \
were copied -- got counts the buffer, not the source"
);
}
other => panic!("expected ShortRead at {offset}, got {other:?}"),
}
assert_eq!(buf, [0u8; 16], "a refused read leaves the buffer alone");
}
}
#[test]
fn a_write_beginning_inside_the_buffer_that_overruns_it_writes_nothing() {
for offset in [0u64, 1, 7] {
let mut bytes = [0u8; 8];
match common::write_from(&mut bytes, offset, &[1u8; 16]).expect_err("overruns the end") {
Error::ShortRead {
offset: o,
want,
got,
} => {
assert_eq!((o, want), (offset, 16));
assert_eq!(got, 0, "a refused write transfers nothing");
}
other => panic!("expected ShortRead at {offset}, got {other:?}"),
}
assert_eq!(bytes, [0u8; 8], "no refused write reached the buffer");
}
}