Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better handling of EOF in read_exact_bytes #201

Merged
merged 2 commits into from
May 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions crates/zune-core/src/bytestream/reader/std_readers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,29 @@ impl<T: io::BufRead + io::Seek> ZByteReaderTrait for T {
}
#[inline(always)]
fn read_exact_bytes(&mut self, buf: &mut [u8]) -> Result<(), ZByteIoError> {
match self.read(buf) {
Ok(bytes) => {
if bytes != buf.len() {
// if a read succeeds but doesn't satisfy the buffer, it means it may be EOF
// so we seek back to where we started because some paths may aggressively read
// forward and ZCursor maintains the position.
let mut bytes_read = 0;

while bytes_read < buf.len() {
match self.read(&mut buf[bytes_read..]) {
Ok(0) => {
// if a read returns zero bytes read, it means it encountered an EOF so we seek
// back to where we started because some paths may aggressively read forward and
// ZCursor maintains the position.

// NB: (cae) This adds a branch on every read, and will slow down every function
// resting on it. Sorry
self.seek(SeekFrom::Current(-(bytes as i64)))
self.seek(SeekFrom::Current(-(bytes_read as i64)))
.map_err(ZByteIoError::from)?;
return Err(ZByteIoError::NotEnoughBytes(bytes, buf.len()));
return Err(ZByteIoError::NotEnoughBytes(bytes_read, buf.len()));
}
Ok(bytes) => {
bytes_read += bytes;
}
Ok(())
}
Err(e) => Err(ZByteIoError::from(e))
}
Err(e) => return Err(ZByteIoError::from(e))
}
}

Ok(())
}

#[inline]
Expand Down
Loading