Pre-allocate buffers in File::open_buffered and create_buffered · qinheping/verify-rust-std@15d69c9 (original) (raw)

`@@ -10,7 +10,7 @@

`

10

10

`//! without encountering any runtime bounds checks.

`

11

11

``

12

12

`use crate::cmp;

`

13

``

`-

use crate::io::{self, BorrowedBuf, Read};

`

``

13

`+

use crate::io::{self, BorrowedBuf, ErrorKind, Read};

`

14

14

`use crate::mem::MaybeUninit;

`

15

15

``

16

16

`pub struct Buffer {

`

`@@ -36,6 +36,16 @@ impl Buffer {

`

36

36

`Self { buf, pos: 0, filled: 0, initialized: 0 }

`

37

37

`}

`

38

38

``

``

39

`+

#[inline]

`

``

40

`+

pub fn try_with_capacity(capacity: usize) -> io::Result {

`

``

41

`+

match Box::try_new_uninit_slice(capacity) {

`

``

42

`+

Ok(buf) => Ok(Self { buf, pos: 0, filled: 0, initialized: 0 }),

`

``

43

`+

Err(_) => {

`

``

44

`+

Err(io::const_io_error!(ErrorKind::OutOfMemory, "failed to allocate read buffer"))

`

``

45

`+

}

`

``

46

`+

}

`

``

47

`+

}

`

``

48

+

39

49

`#[inline]

`

40

50

`pub fn buffer(&self) -> &[u8] {

`

41

51

`// SAFETY: self.pos and self.cap are valid, and self.cap => self.pos, and

`