Fix read_exact and read_buf_exact for &[u8] and io:Cursor

This commit is contained in:
Benoît du Garreau 2024-05-14 16:16:33 +02:00
parent 31026b7fe3
commit cfb04795a1
2 changed files with 23 additions and 10 deletions

View File

@ -328,7 +328,7 @@ where
fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
let prev_written = cursor.written();
Read::read_buf(&mut self.fill_buf()?, cursor.reborrow())?;
Read::read_buf(&mut self.remaining_slice(), cursor.reborrow())?;
self.pos += (cursor.written() - prev_written) as u64;
@ -352,17 +352,24 @@ where
}
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
let n = buf.len();
Read::read_exact(&mut self.remaining_slice(), buf)?;
self.pos += n as u64;
Ok(())
let result = Read::read_exact(&mut self.remaining_slice(), buf);
match result {
Ok(_) => self.pos += buf.len() as u64,
// The only posible error condition is EOF
Err(_) => self.pos = self.inner.as_ref().len() as u64,
}
result
}
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
let n = cursor.capacity();
Read::read_buf_exact(&mut self.remaining_slice(), cursor)?;
self.pos += n as u64;
Ok(())
fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
let prev_written = cursor.written();
let result = Read::read_buf_exact(&mut self.remaining_slice(), cursor.reborrow());
self.pos += (cursor.written() - prev_written) as u64;
result
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {

View File

@ -287,6 +287,9 @@ impl Read for &[u8] {
#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
if buf.len() > self.len() {
// `read_exact` makes no promise about the content of `buf` if it
// fails so don't bother about that.
*self = &self[self.len()..];
return Err(io::Error::READ_EXACT_EOF);
}
let (a, b) = self.split_at(buf.len());
@ -307,6 +310,9 @@ impl Read for &[u8] {
#[inline]
fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
if cursor.capacity() > self.len() {
// Append everything we can to the cursor.
cursor.append(*self);
*self = &self[self.len()..];
return Err(io::Error::READ_EXACT_EOF);
}
let (a, b) = self.split_at(cursor.capacity());