diff options
| author | Josh Stone <jistone@redhat.com> | 2024-09-24 13:33:31 -0700 |
|---|---|---|
| committer | Josh Stone <jistone@redhat.com> | 2024-09-24 13:33:31 -0700 |
| commit | 1e9a50dde8fe417348a9e4c74787975527502ec3 (patch) | |
| tree | 24a60042938bdbac627ff87234b91a092950f688 /library/std/src/io/buffered/bufreader/buffer.rs | |
| parent | ee129b12ede79fd8cf7e398cf955941b62e58974 (diff) | |
| download | rust-1e9a50dde8fe417348a9e4c74787975527502ec3.tar.gz rust-1e9a50dde8fe417348a9e4c74787975527502ec3.zip | |
Pre-allocate buffers in `File::open_buffered` and `create_buffered`
Diffstat (limited to 'library/std/src/io/buffered/bufreader/buffer.rs')
| -rw-r--r-- | library/std/src/io/buffered/bufreader/buffer.rs | 12 |
1 files changed, 11 insertions, 1 deletions
diff --git a/library/std/src/io/buffered/bufreader/buffer.rs b/library/std/src/io/buffered/bufreader/buffer.rs index 1bf84d8bef3..3df7e3971da 100644 --- a/library/std/src/io/buffered/bufreader/buffer.rs +++ b/library/std/src/io/buffered/bufreader/buffer.rs @@ -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 { @@ -37,6 +37,16 @@ impl Buffer { } #[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 // that region is initialized because those are all invariants of this type. |
