From 703a33673de30572960eb3fe2c36a0f51083d226 Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Sun, 27 Mar 2022 15:41:13 -0700 Subject: [PATCH] Define a dedicated error type for `HandleOrNull` and `HandleOrInvalid`. Define a `NotHandle` type, that implements `std::error::Error`, and use it as the error type in `HandleOrNull` and `HandleOrInvalid`. --- library/std/src/os/windows/io/handle.rs | 26 +++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/library/std/src/os/windows/io/handle.rs b/library/std/src/os/windows/io/handle.rs index ee30cc8be6b..1fb448be5de 100644 --- a/library/std/src/os/windows/io/handle.rs +++ b/library/std/src/os/windows/io/handle.rs @@ -143,17 +143,17 @@ pub unsafe fn borrow_raw(handle: RawHandle) -> Self { } impl TryFrom for OwnedHandle { - type Error = (); + type Error = NotHandle; #[inline] - fn try_from(handle_or_null: HandleOrNull) -> Result { + fn try_from(handle_or_null: HandleOrNull) -> Result { let owned_handle = handle_or_null.0; if owned_handle.handle.is_null() { // Don't call `CloseHandle`; it'd be harmless, except that it could // overwrite the `GetLastError` error. forget(owned_handle); - Err(()) + Err(NotHandle(())) } else { Ok(owned_handle) } @@ -201,23 +201,37 @@ pub(crate) fn duplicate( } impl TryFrom for OwnedHandle { - type Error = (); + type Error = NotHandle; #[inline] - fn try_from(handle_or_invalid: HandleOrInvalid) -> Result { + fn try_from(handle_or_invalid: HandleOrInvalid) -> Result { let owned_handle = handle_or_invalid.0; if owned_handle.handle == c::INVALID_HANDLE_VALUE { // Don't call `CloseHandle`; it'd be harmless, except that it could // overwrite the `GetLastError` error. forget(owned_handle); - Err(()) + Err(NotHandle(())) } else { Ok(owned_handle) } } } +/// This is the error type used by [`HandleOrInvalid`] and +/// [`HandleOrNull`] when attempting to convert into a handle, +/// to indicate that the value is not a handle. +#[unstable(feature = "io_safety", issue = "87074")] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct NotHandle(()); + +#[unstable(feature = "io_safety", issue = "87074")] +impl fmt::Display for NotHandle { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + "the return value of a Windows API call indicated an error".fmt(fmt) + } +} + impl AsRawHandle for BorrowedHandle<'_> { #[inline] fn as_raw_handle(&self) -> RawHandle {