Skip to content

Commit

Permalink
TryReserveError to ErrorKind::OutOfMemory
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Feb 21, 2024
1 parent 1d447a9 commit e49cd1c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions library/std/src/io/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,18 @@ impl From<alloc::ffi::NulError> for Error {
}
}

#[stable(feature = "io_error_from_try_reserve", since = "CURRENT_RUSTC_VERSION")]
impl From<alloc::collections::TryReserveError> for Error {
/// Converts `TryReserveError` to an error with [`ErrorKind::OutOfMemory`].
///
/// `TryReserveError` won't be available as the error `source()`,
/// but this may change in the future.
fn from(_: alloc::collections::TryReserveError) -> Error {
// ErrorData::Custom allocates, which isn't great for handling OOM errors.
ErrorKind::OutOfMemory.into()
}
}

// Only derive debug in tests, to make sure it
// doesn't accidentally get printed.
#[cfg_attr(test, derive(Debug))]
Expand Down
10 changes: 10 additions & 0 deletions library/std/src/io/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,3 +692,13 @@ fn read_buf_full_read() {

assert_eq!(BufReader::new(FullRead).fill_buf().unwrap().len(), DEFAULT_BUF_SIZE);
}

#[test]
// 64-bit only to be sure the allocator will fail fast on an impossible to satsify size
#[cfg(target_pointer_width = "64")]
fn try_oom_error() {
let mut v = Vec::<u8>::new();
let reserve_err = v.try_reserve(isize::MAX as usize - 1).unwrap_err();
let io_err = io::Error::from(reserve_err);
assert_eq!(io::ErrorKind::OutOfMemory, io_err.kind());
}

0 comments on commit e49cd1c

Please sign in to comment.