Skip to content

Commit

Permalink
Ensure TakeSeek::seek uses correct stream end position
Browse files Browse the repository at this point in the history
The purpose of `TakeSeek` is to be a binrw-compatible version of
`std::io::Take`, and the purpose of `std::io::Take` is only to
truncate the stream to a certain number of bytes, not to extend the
stream if a limit beyond the length of the inner stream is given.
Thus, `TakeSeek` also needs to pay attention to the true end of the
inner stream and use that as the `SeekFrom::End(0)` position if it
is less than the limit.

Refs jam1garner#291.
  • Loading branch information
csnover committed Dec 1, 2024
1 parent e47ec2a commit ab810c5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
19 changes: 11 additions & 8 deletions binrw/src/io/take_seek.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,18 @@ impl<T: Read> Read for TakeSeek<T> {
impl<T: Seek> Seek for TakeSeek<T> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
let pos = match pos {
SeekFrom::End(end) => match self.end.checked_add_signed(end) {
Some(pos) => SeekFrom::Start(pos),
None => {
return Err(super::Error::new(
super::ErrorKind::InvalidInput,
"invalid seek to a negative or overflowing position",
))
SeekFrom::End(end) => {
let inner_end = self.inner.seek(SeekFrom::End(0))?;
match self.end.min(inner_end).checked_add_signed(end) {
Some(pos) => SeekFrom::Start(pos),
None => {
return Err(super::Error::new(
super::ErrorKind::InvalidInput,
"invalid seek to a negative or overflowing position",
))
}
}
},
}
pos => pos,
};
self.pos = self.inner.seek(pos)?;
Expand Down
9 changes: 9 additions & 0 deletions binrw/tests/io/take_seek.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use binrw::io::{Cursor, Read, Seek, SeekFrom, TakeSeekExt};
#[test]
fn take_seek() {
let data = &mut Cursor::new(b"hello world".to_vec());
let data_size = u64::try_from(data.get_ref().len()).unwrap();
let mut buf = [0; 5];
let mut take = data.take_seek(6);

Expand Down Expand Up @@ -99,6 +100,14 @@ fn take_seek() {
take.seek(SeekFrom::End(-5))
.expect_err("out-of-range `SeekFrom::End` backward seek should fail");

take.set_limit(data_size + 1);
take.seek(SeekFrom::End(-1)).unwrap();
assert_eq!(
take.read(&mut buf).unwrap(),
1,
"`SeekFrom::End` did not bound to the true end of the stream"
);

take.seek(SeekFrom::Start(0)).unwrap();
take.set_limit(10);
assert_eq!(
Expand Down

0 comments on commit ab810c5

Please sign in to comment.