Skip to main content

std/os/windows/io/
handle.rs

1//! Owned and borrowed OS handles.
2
3#![stable(feature = "io_safety", since = "1.63.0")]
4
5use super::raw::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle};
6use crate::marker::PhantomData;
7use crate::mem::ManuallyDrop;
8use crate::sys::{AsInner, FromInner, IntoInner, cvt};
9use crate::{fmt, fs, io, ptr, sys};
10
11/// A borrowed handle.
12///
13/// This has a lifetime parameter to tie it to the lifetime of something that
14/// owns the handle.
15///
16/// This uses `repr(transparent)` and has the representation of a host handle,
17/// so it can be used in FFI in places where a handle is passed as an argument,
18/// it is not captured or consumed.
19///
20/// Note that it *may* have the value `-1`, which in `BorrowedHandle` always
21/// represents a valid handle value, such as [the current process handle], and
22/// not `INVALID_HANDLE_VALUE`, despite the two having the same value. See
23/// [here] for the full story.
24///
25/// And, it *may* have the value `NULL` (0), which can occur when consoles are
26/// detached from processes, or when `windows_subsystem` is used.
27///
28/// This type's `.to_owned()` implementation returns another `BorrowedHandle`
29/// rather than an `OwnedHandle`. It just makes a trivial copy of the raw
30/// handle, which is then borrowed under the same lifetime.
31///
32/// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
33/// [the current process handle]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess#remarks
34#[derive(Copy, Clone)]
35#[repr(transparent)]
36#[stable(feature = "io_safety", since = "1.63.0")]
37pub struct BorrowedHandle<'handle> {
38    handle: RawHandle,
39    _phantom: PhantomData<&'handle OwnedHandle>,
40}
41
42/// An owned handle.
43///
44/// This closes the handle on drop.
45///
46/// Note that it *may* have the value `-1`, which in `OwnedHandle` always
47/// represents a valid handle value, such as [the current process handle], and
48/// not `INVALID_HANDLE_VALUE`, despite the two having the same value. See
49/// [here] for the full story.
50///
51/// And, it *may* have the value `NULL` (0), which can occur when consoles are
52/// detached from processes, or when `windows_subsystem` is used.
53///
54/// `OwnedHandle` uses [`CloseHandle`] to close its handle on drop. As such,
55/// it must not be used with handles to open registry keys which need to be
56/// closed with [`RegCloseKey`] instead.
57///
58/// [`CloseHandle`]: https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle
59/// [`RegCloseKey`]: https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey
60///
61/// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
62/// [the current process handle]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess#remarks
63#[repr(transparent)]
64#[stable(feature = "io_safety", since = "1.63.0")]
65pub struct OwnedHandle {
66    handle: RawHandle,
67}
68
69/// FFI type for handles in return values or out parameters, where `NULL` is used
70/// as a sentry value to indicate errors, such as in the return value of `CreateThread`. This uses
71/// `repr(transparent)` and has the representation of a host handle, so that it can be used in such
72/// FFI declarations.
73///
74/// The only thing you can usefully do with a `HandleOrNull` is to convert it into an
75/// `OwnedHandle` using its [`TryFrom`] implementation; this conversion takes care of the check for
76/// `NULL`. This ensures that such FFI calls cannot start using the handle without
77/// checking for `NULL` first.
78///
79/// This type may hold any handle value that [`OwnedHandle`] may hold. As with `OwnedHandle`, when
80/// it holds `-1`, that value is interpreted as a valid handle value, such as
81/// [the current process handle], and not `INVALID_HANDLE_VALUE`.
82///
83/// If this holds a non-null handle, it will close the handle on drop.
84///
85/// [the current process handle]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess#remarks
86#[repr(transparent)]
87#[stable(feature = "io_safety", since = "1.63.0")]
88#[derive(Debug)]
89pub struct HandleOrNull(RawHandle);
90
91/// FFI type for handles in return values or out parameters, where `INVALID_HANDLE_VALUE` is used
92/// as a sentry value to indicate errors, such as in the return value of `CreateFileW`. This uses
93/// `repr(transparent)` and has the representation of a host handle, so that it can be used in such
94/// FFI declarations.
95///
96/// The only thing you can usefully do with a `HandleOrInvalid` is to convert it into an
97/// `OwnedHandle` using its [`TryFrom`] implementation; this conversion takes care of the check for
98/// `INVALID_HANDLE_VALUE`. This ensures that such FFI calls cannot start using the handle without
99/// checking for `INVALID_HANDLE_VALUE` first.
100///
101/// This type may hold any handle value that [`OwnedHandle`] may hold, except that when it holds
102/// `-1`, that value is interpreted to mean `INVALID_HANDLE_VALUE`.
103///
104/// If holds a handle other than `INVALID_HANDLE_VALUE`, it will close the handle on drop.
105#[repr(transparent)]
106#[stable(feature = "io_safety", since = "1.63.0")]
107#[derive(Debug)]
108pub struct HandleOrInvalid(RawHandle);
109
110// The Windows [`HANDLE`] type may be transferred across and shared between
111// thread boundaries (despite containing a `*mut void`, which in general isn't
112// `Send` or `Sync`).
113//
114// [`HANDLE`]: std::os::windows::raw::HANDLE
115#[stable(feature = "io_safety", since = "1.63.0")]
116unsafe impl Send for OwnedHandle {}
117#[stable(feature = "io_safety", since = "1.63.0")]
118unsafe impl Send for HandleOrNull {}
119#[stable(feature = "io_safety", since = "1.63.0")]
120unsafe impl Send for HandleOrInvalid {}
121#[stable(feature = "io_safety", since = "1.63.0")]
122unsafe impl Send for BorrowedHandle<'_> {}
123#[stable(feature = "io_safety", since = "1.63.0")]
124unsafe impl Sync for OwnedHandle {}
125#[stable(feature = "io_safety", since = "1.63.0")]
126unsafe impl Sync for HandleOrNull {}
127#[stable(feature = "io_safety", since = "1.63.0")]
128unsafe impl Sync for HandleOrInvalid {}
129#[stable(feature = "io_safety", since = "1.63.0")]
130unsafe impl Sync for BorrowedHandle<'_> {}
131
132impl BorrowedHandle<'_> {
133    /// Returns a `BorrowedHandle` holding the given raw handle.
134    ///
135    /// # Safety
136    ///
137    /// The resource pointed to by `handle` must be a valid open handle, it
138    /// must remain open for the duration of the returned `BorrowedHandle`.
139    ///
140    /// Note that it *may* have the value `INVALID_HANDLE_VALUE` (-1), which is
141    /// sometimes a valid handle value. See [here] for the full story.
142    ///
143    /// And, it *may* have the value `NULL` (0), which can occur when consoles are
144    /// detached from processes, or when `windows_subsystem` is used.
145    ///
146    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
147    #[inline]
148    #[rustc_const_stable(feature = "io_safety", since = "1.63.0")]
149    #[stable(feature = "io_safety", since = "1.63.0")]
150    pub const unsafe fn borrow_raw(handle: RawHandle) -> Self {
151        Self { handle, _phantom: PhantomData }
152    }
153}
154
155#[stable(feature = "io_safety", since = "1.63.0")]
156impl TryFrom<HandleOrNull> for OwnedHandle {
157    type Error = NullHandleError;
158
159    #[inline]
160    fn try_from(handle_or_null: HandleOrNull) -> Result<Self, NullHandleError> {
161        let handle_or_null = ManuallyDrop::new(handle_or_null);
162        if handle_or_null.is_valid() {
163            // SAFETY: The handle is not null.
164            Ok(unsafe { OwnedHandle::from_raw_handle(handle_or_null.0) })
165        } else {
166            Err(NullHandleError(()))
167        }
168    }
169}
170
171#[stable(feature = "io_safety", since = "1.63.0")]
172impl Drop for HandleOrNull {
173    #[inline]
174    fn drop(&mut self) {
175        if self.is_valid() {
176            unsafe {
177                let _ = sys::c::CloseHandle(self.0);
178            }
179        }
180    }
181}
182
183impl OwnedHandle {
184    /// Creates a new `OwnedHandle` instance that shares the same underlying
185    /// object as the existing `OwnedHandle` instance.
186    #[stable(feature = "io_safety", since = "1.63.0")]
187    pub fn try_clone(&self) -> io::Result<Self> {
188        self.as_handle().try_clone_to_owned()
189    }
190}
191
192impl BorrowedHandle<'_> {
193    /// Creates a new `OwnedHandle` instance that shares the same underlying
194    /// object as the existing `BorrowedHandle` instance.
195    #[stable(feature = "io_safety", since = "1.63.0")]
196    pub fn try_clone_to_owned(&self) -> io::Result<OwnedHandle> {
197        self.duplicate(0, false, sys::c::DUPLICATE_SAME_ACCESS)
198    }
199
200    pub(crate) fn duplicate(
201        &self,
202        access: u32,
203        inherit: bool,
204        options: u32,
205    ) -> io::Result<OwnedHandle> {
206        let handle = self.as_raw_handle();
207
208        // `Stdin`, `Stdout`, and `Stderr` can all hold null handles, such as
209        // in a process with a detached console. `DuplicateHandle` would fail
210        // if we passed it a null handle, but we can treat null as a valid
211        // handle which doesn't do any I/O, and allow it to be duplicated.
212        if handle.is_null() {
213            return unsafe { Ok(OwnedHandle::from_raw_handle(handle)) };
214        }
215
216        let mut ret = ptr::null_mut();
217        cvt(unsafe {
218            let cur_proc = sys::c::GetCurrentProcess();
219            sys::c::DuplicateHandle(
220                cur_proc,
221                handle,
222                cur_proc,
223                &mut ret,
224                access,
225                inherit as sys::c::BOOL,
226                options,
227            )
228        })?;
229        unsafe { Ok(OwnedHandle::from_raw_handle(ret)) }
230    }
231}
232
233#[stable(feature = "io_safety", since = "1.63.0")]
234impl TryFrom<HandleOrInvalid> for OwnedHandle {
235    type Error = InvalidHandleError;
236
237    #[inline]
238    fn try_from(handle_or_invalid: HandleOrInvalid) -> Result<Self, InvalidHandleError> {
239        let handle_or_invalid = ManuallyDrop::new(handle_or_invalid);
240        if handle_or_invalid.is_valid() {
241            // SAFETY: The handle is not invalid.
242            Ok(unsafe { OwnedHandle::from_raw_handle(handle_or_invalid.0) })
243        } else {
244            Err(InvalidHandleError(()))
245        }
246    }
247}
248
249#[stable(feature = "io_safety", since = "1.63.0")]
250impl Drop for HandleOrInvalid {
251    #[inline]
252    fn drop(&mut self) {
253        if self.is_valid() {
254            unsafe {
255                let _ = sys::c::CloseHandle(self.0);
256            }
257        }
258    }
259}
260
261/// This is the error type used by [`HandleOrNull`] when attempting to convert
262/// into a handle, to indicate that the value is null.
263// The empty field prevents constructing this, and allows extending it in the future.
264#[stable(feature = "io_safety", since = "1.63.0")]
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub struct NullHandleError(());
267
268#[stable(feature = "io_safety", since = "1.63.0")]
269impl fmt::Display for NullHandleError {
270    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
271        "A HandleOrNull could not be converted to a handle because it was null".fmt(fmt)
272    }
273}
274
275#[stable(feature = "io_safety", since = "1.63.0")]
276impl crate::error::Error for NullHandleError {}
277
278/// This is the error type used by [`HandleOrInvalid`] when attempting to
279/// convert into a handle, to indicate that the value is
280/// `INVALID_HANDLE_VALUE`.
281// The empty field prevents constructing this, and allows extending it in the future.
282#[stable(feature = "io_safety", since = "1.63.0")]
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct InvalidHandleError(());
285
286#[stable(feature = "io_safety", since = "1.63.0")]
287impl fmt::Display for InvalidHandleError {
288    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
289        "A HandleOrInvalid could not be converted to a handle because it was INVALID_HANDLE_VALUE"
290            .fmt(fmt)
291    }
292}
293
294#[stable(feature = "io_safety", since = "1.63.0")]
295impl crate::error::Error for InvalidHandleError {}
296
297#[stable(feature = "io_safety", since = "1.63.0")]
298impl AsRawHandle for BorrowedHandle<'_> {
299    #[inline]
300    fn as_raw_handle(&self) -> RawHandle {
301        self.handle
302    }
303}
304
305#[stable(feature = "io_safety", since = "1.63.0")]
306impl AsRawHandle for OwnedHandle {
307    #[inline]
308    fn as_raw_handle(&self) -> RawHandle {
309        self.handle
310    }
311}
312
313#[stable(feature = "io_safety", since = "1.63.0")]
314impl IntoRawHandle for OwnedHandle {
315    #[inline]
316    fn into_raw_handle(self) -> RawHandle {
317        ManuallyDrop::new(self).handle
318    }
319}
320
321#[stable(feature = "io_safety", since = "1.63.0")]
322impl FromRawHandle for OwnedHandle {
323    #[inline]
324    unsafe fn from_raw_handle(handle: RawHandle) -> Self {
325        Self { handle }
326    }
327}
328
329impl HandleOrNull {
330    /// Constructs a new instance of `Self` from the given `RawHandle` returned
331    /// from a Windows API that uses null to indicate failure, such as
332    /// `CreateThread`.
333    ///
334    /// Use `HandleOrInvalid` instead of `HandleOrNull` for APIs that
335    /// use `INVALID_HANDLE_VALUE` to indicate failure.
336    ///
337    /// # Safety
338    ///
339    /// The passed `handle` value must either satisfy the safety requirements
340    /// of [`FromRawHandle::from_raw_handle`], or be null. Note that not all
341    /// Windows APIs use null for errors; see [here] for the full story.
342    ///
343    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
344    #[stable(feature = "io_safety", since = "1.63.0")]
345    #[inline]
346    pub unsafe fn from_raw_handle(handle: RawHandle) -> Self {
347        Self(handle)
348    }
349
350    fn is_valid(&self) -> bool {
351        !self.0.is_null()
352    }
353}
354
355impl HandleOrInvalid {
356    /// Constructs a new instance of `Self` from the given `RawHandle` returned
357    /// from a Windows API that uses `INVALID_HANDLE_VALUE` to indicate
358    /// failure, such as `CreateFileW`.
359    ///
360    /// Use `HandleOrNull` instead of `HandleOrInvalid` for APIs that
361    /// use null to indicate failure.
362    ///
363    /// # Safety
364    ///
365    /// The passed `handle` value must either satisfy the safety requirements
366    /// of [`FromRawHandle::from_raw_handle`], or be
367    /// `INVALID_HANDLE_VALUE` (-1). Note that not all Windows APIs use
368    /// `INVALID_HANDLE_VALUE` for errors; see [here] for the full story.
369    ///
370    /// [here]: https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
371    #[stable(feature = "io_safety", since = "1.63.0")]
372    #[inline]
373    pub unsafe fn from_raw_handle(handle: RawHandle) -> Self {
374        Self(handle)
375    }
376
377    fn is_valid(&self) -> bool {
378        self.0 != sys::c::INVALID_HANDLE_VALUE
379    }
380}
381
382#[stable(feature = "io_safety", since = "1.63.0")]
383impl Drop for OwnedHandle {
384    #[inline]
385    fn drop(&mut self) {
386        unsafe {
387            let _ = sys::c::CloseHandle(self.handle);
388        }
389    }
390}
391
392#[stable(feature = "io_safety", since = "1.63.0")]
393impl fmt::Debug for BorrowedHandle<'_> {
394    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395        f.debug_struct("BorrowedHandle").field("handle", &self.handle).finish()
396    }
397}
398
399#[stable(feature = "io_safety", since = "1.63.0")]
400impl fmt::Debug for OwnedHandle {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        f.debug_struct("OwnedHandle").field("handle", &self.handle).finish()
403    }
404}
405
406macro_rules! impl_is_terminal {
407    ($($t:ty),*$(,)?) => {$(
408        #[stable(feature = "is_terminal", since = "1.70.0")]
409        impl io::IsTerminal for $t {
410            #[inline]
411            fn is_terminal(&self) -> bool {
412                crate::sys::io::is_terminal(self)
413            }
414        }
415    )*}
416}
417
418impl_is_terminal!(BorrowedHandle<'_>, OwnedHandle);
419
420/// A trait to borrow the handle from an underlying object.
421#[stable(feature = "io_safety", since = "1.63.0")]
422pub trait AsHandle {
423    /// Borrows the handle.
424    ///
425    /// # Example
426    ///
427    #[cfg_attr(windows, doc = "```no_run")]
428    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
429    /// use std::fs::File;
430    /// # use std::io;
431    /// use std::os::windows::io::{AsHandle, BorrowedHandle};
432    ///
433    /// let mut f = File::open("foo.txt")?;
434    /// let borrowed_handle: BorrowedHandle<'_> = f.as_handle();
435    /// # Ok::<(), io::Error>(())
436    /// ```
437    #[stable(feature = "io_safety", since = "1.63.0")]
438    fn as_handle(&self) -> BorrowedHandle<'_>;
439}
440
441#[stable(feature = "io_safety", since = "1.63.0")]
442impl<T: AsHandle + ?Sized> AsHandle for &T {
443    #[inline]
444    fn as_handle(&self) -> BorrowedHandle<'_> {
445        T::as_handle(self)
446    }
447}
448
449#[stable(feature = "io_safety", since = "1.63.0")]
450impl<T: AsHandle + ?Sized> AsHandle for &mut T {
451    #[inline]
452    fn as_handle(&self) -> BorrowedHandle<'_> {
453        T::as_handle(self)
454    }
455}
456
457#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
458/// This impl allows implementing traits that require `AsHandle` on Arc.
459/// ```
460/// # #[cfg(windows)] mod group_cfg {
461/// # use std::os::windows::io::AsHandle;
462/// use std::fs::File;
463/// use std::sync::Arc;
464///
465/// trait MyTrait: AsHandle {}
466/// impl MyTrait for Arc<File> {}
467/// impl MyTrait for Box<File> {}
468/// # }
469/// ```
470impl<T: AsHandle + ?Sized> AsHandle for crate::sync::Arc<T> {
471    #[inline]
472    fn as_handle(&self) -> BorrowedHandle<'_> {
473        (**self).as_handle()
474    }
475}
476
477#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
478impl<T: AsHandle + ?Sized> AsHandle for crate::rc::Rc<T> {
479    #[inline]
480    fn as_handle(&self) -> BorrowedHandle<'_> {
481        (**self).as_handle()
482    }
483}
484
485#[unstable(feature = "unique_rc_arc", issue = "112566")]
486impl<T: AsHandle + ?Sized> AsHandle for crate::rc::UniqueRc<T> {
487    #[inline]
488    fn as_handle(&self) -> BorrowedHandle<'_> {
489        (**self).as_handle()
490    }
491}
492
493#[stable(feature = "as_windows_ptrs", since = "1.71.0")]
494impl<T: AsHandle + ?Sized> AsHandle for Box<T> {
495    #[inline]
496    fn as_handle(&self) -> BorrowedHandle<'_> {
497        (**self).as_handle()
498    }
499}
500
501#[stable(feature = "io_safety", since = "1.63.0")]
502impl AsHandle for BorrowedHandle<'_> {
503    #[inline]
504    fn as_handle(&self) -> BorrowedHandle<'_> {
505        *self
506    }
507}
508
509#[stable(feature = "io_safety", since = "1.63.0")]
510impl AsHandle for OwnedHandle {
511    #[inline]
512    fn as_handle(&self) -> BorrowedHandle<'_> {
513        // Safety: `OwnedHandle` and `BorrowedHandle` have the same validity
514        // invariants, and the `BorrowedHandle` is bounded by the lifetime
515        // of `&self`.
516        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
517    }
518}
519
520#[stable(feature = "io_safety", since = "1.63.0")]
521impl AsHandle for fs::File {
522    #[inline]
523    fn as_handle(&self) -> BorrowedHandle<'_> {
524        self.as_inner().as_handle()
525    }
526}
527
528#[stable(feature = "io_safety", since = "1.63.0")]
529impl From<fs::File> for OwnedHandle {
530    /// Takes ownership of a [`File`](fs::File)'s underlying file handle.
531    #[inline]
532    fn from(file: fs::File) -> OwnedHandle {
533        file.into_inner().into_inner().into_inner()
534    }
535}
536
537#[stable(feature = "io_safety", since = "1.63.0")]
538impl From<OwnedHandle> for fs::File {
539    /// Returns a [`File`](fs::File) that takes ownership of the given handle.
540    #[inline]
541    fn from(owned: OwnedHandle) -> Self {
542        Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned)))
543    }
544}
545
546#[stable(feature = "io_safety", since = "1.63.0")]
547impl AsHandle for io::Stdin {
548    #[inline]
549    fn as_handle(&self) -> BorrowedHandle<'_> {
550        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
551    }
552}
553
554#[stable(feature = "io_safety", since = "1.63.0")]
555impl<'a> AsHandle for io::StdinLock<'a> {
556    #[inline]
557    fn as_handle(&self) -> BorrowedHandle<'_> {
558        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
559    }
560}
561
562#[stable(feature = "io_safety", since = "1.63.0")]
563impl AsHandle for io::Stdout {
564    #[inline]
565    fn as_handle(&self) -> BorrowedHandle<'_> {
566        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
567    }
568}
569
570#[stable(feature = "io_safety", since = "1.63.0")]
571impl<'a> AsHandle for io::StdoutLock<'a> {
572    #[inline]
573    fn as_handle(&self) -> BorrowedHandle<'_> {
574        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
575    }
576}
577
578#[stable(feature = "io_safety", since = "1.63.0")]
579impl AsHandle for io::Stderr {
580    #[inline]
581    fn as_handle(&self) -> BorrowedHandle<'_> {
582        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
583    }
584}
585
586#[stable(feature = "io_safety", since = "1.63.0")]
587impl<'a> AsHandle for io::StderrLock<'a> {
588    #[inline]
589    fn as_handle(&self) -> BorrowedHandle<'_> {
590        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
591    }
592}
593
594#[stable(feature = "io_safety", since = "1.63.0")]
595impl AsHandle for crate::process::ChildStdin {
596    #[inline]
597    fn as_handle(&self) -> BorrowedHandle<'_> {
598        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
599    }
600}
601
602#[stable(feature = "io_safety", since = "1.63.0")]
603impl From<crate::process::ChildStdin> for OwnedHandle {
604    /// Takes ownership of a [`ChildStdin`](crate::process::ChildStdin)'s file handle.
605    #[inline]
606    fn from(child_stdin: crate::process::ChildStdin) -> OwnedHandle {
607        unsafe { OwnedHandle::from_raw_handle(child_stdin.into_raw_handle()) }
608    }
609}
610
611#[stable(feature = "io_safety", since = "1.63.0")]
612impl AsHandle for crate::process::ChildStdout {
613    #[inline]
614    fn as_handle(&self) -> BorrowedHandle<'_> {
615        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
616    }
617}
618
619#[stable(feature = "io_safety", since = "1.63.0")]
620impl From<crate::process::ChildStdout> for OwnedHandle {
621    /// Takes ownership of a [`ChildStdout`](crate::process::ChildStdout)'s file handle.
622    #[inline]
623    fn from(child_stdout: crate::process::ChildStdout) -> OwnedHandle {
624        unsafe { OwnedHandle::from_raw_handle(child_stdout.into_raw_handle()) }
625    }
626}
627
628#[stable(feature = "io_safety", since = "1.63.0")]
629impl AsHandle for crate::process::ChildStderr {
630    #[inline]
631    fn as_handle(&self) -> BorrowedHandle<'_> {
632        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
633    }
634}
635
636#[stable(feature = "io_safety", since = "1.63.0")]
637impl From<crate::process::ChildStderr> for OwnedHandle {
638    /// Takes ownership of a [`ChildStderr`](crate::process::ChildStderr)'s file handle.
639    #[inline]
640    fn from(child_stderr: crate::process::ChildStderr) -> OwnedHandle {
641        unsafe { OwnedHandle::from_raw_handle(child_stderr.into_raw_handle()) }
642    }
643}
644
645#[stable(feature = "io_safety", since = "1.63.0")]
646impl<T> AsHandle for crate::thread::JoinHandle<T> {
647    #[inline]
648    fn as_handle(&self) -> BorrowedHandle<'_> {
649        unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
650    }
651}
652
653#[stable(feature = "io_safety", since = "1.63.0")]
654impl<T> From<crate::thread::JoinHandle<T>> for OwnedHandle {
655    #[inline]
656    fn from(join_handle: crate::thread::JoinHandle<T>) -> OwnedHandle {
657        join_handle.into_inner().into_handle().into_inner()
658    }
659}
660
661#[stable(feature = "anonymous_pipe", since = "1.87.0")]
662impl AsHandle for io::PipeReader {
663    fn as_handle(&self) -> BorrowedHandle<'_> {
664        self.0.as_handle()
665    }
666}
667
668#[stable(feature = "anonymous_pipe", since = "1.87.0")]
669impl From<io::PipeReader> for OwnedHandle {
670    fn from(pipe: io::PipeReader) -> Self {
671        pipe.into_inner().into_inner()
672    }
673}
674
675#[stable(feature = "anonymous_pipe", since = "1.87.0")]
676impl AsHandle for io::PipeWriter {
677    fn as_handle(&self) -> BorrowedHandle<'_> {
678        self.0.as_handle()
679    }
680}
681
682#[stable(feature = "anonymous_pipe", since = "1.87.0")]
683impl From<io::PipeWriter> for OwnedHandle {
684    fn from(pipe: io::PipeWriter) -> Self {
685        pipe.into_inner().into_inner()
686    }
687}
688
689#[stable(feature = "anonymous_pipe", since = "1.87.0")]
690impl From<OwnedHandle> for io::PipeReader {
691    fn from(owned_handle: OwnedHandle) -> Self {
692        Self::from_inner(FromInner::from_inner(owned_handle))
693    }
694}
695
696#[stable(feature = "anonymous_pipe", since = "1.87.0")]
697impl From<OwnedHandle> for io::PipeWriter {
698    fn from(owned_handle: OwnedHandle) -> Self {
699        Self::from_inner(FromInner::from_inner(owned_handle))
700    }
701}