Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

impl From<TryReserveError> for io::Error #121403

Merged
merged 2 commits into from
Mar 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
TryReserveError to ErrorKind::OutOfMemory
  • Loading branch information
kornelski committed Feb 21, 2024
commit e49cd1c578227e450f0a703b08fa429e3931c228
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());
}