1
Fork 0

Pre-allocate buffers in File::open_buffered and create_buffered

This commit is contained in:
Josh Stone 2024-09-24 13:33:31 -07:00
parent ee129b12ed
commit 1e9a50dde8
5 changed files with 38 additions and 3 deletions

View file

@ -10,7 +10,7 @@
//! without encountering any runtime bounds checks.
use crate::cmp;
use crate::io::{self, BorrowedBuf, Read};
use crate::io::{self, BorrowedBuf, ErrorKind, Read};
use crate::mem::MaybeUninit;
pub struct Buffer {
@ -36,6 +36,16 @@ impl Buffer {
Self { buf, pos: 0, filled: 0, initialized: 0 }
}
#[inline]
pub fn try_with_capacity(capacity: usize) -> io::Result<Self> {
match Box::try_new_uninit_slice(capacity) {
Ok(buf) => Ok(Self { buf, pos: 0, filled: 0, initialized: 0 }),
Err(_) => {
Err(io::const_io_error!(ErrorKind::OutOfMemory, "failed to allocate read buffer"))
}
}
}
#[inline]
pub fn buffer(&self) -> &[u8] {
// SAFETY: self.pos and self.cap are valid, and self.cap => self.pos, and