From c793a631f7df349fd9467f27109eea32732df941 Mon Sep 17 00:00:00 2001 From: linkmauve Date: Fri, 10 Jul 2026 20:02:38 +0200 Subject: [PATCH] fs: add safe impl From for File (#8266) This impl was missing to be able to create a tokio::fs::File directly from an OwnedFd, which can be done in a safe way. Going through RawFd required unsafe for the same operation. And same for Windows using a OwnedHandle instead. --- tokio/src/fs/file.rs | 15 ++++++++++++++- tokio/src/fs/mocks.rs | 4 ++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/tokio/src/fs/file.rs b/tokio/src/fs/file.rs index c23164356..3829b609d 100644 --- a/tokio/src/fs/file.rs +++ b/tokio/src/fs/file.rs @@ -897,6 +897,13 @@ impl fmt::Debug for File { } } +#[cfg(unix)] +impl From for File { + fn from(fd: std::os::fd::OwnedFd) -> Self { + Self::from_std(StdFile::from(fd)) + } +} + #[cfg(unix)] impl std::os::unix::io::AsRawFd for File { fn as_raw_fd(&self) -> std::os::unix::io::RawFd { @@ -923,7 +930,13 @@ impl std::os::unix::io::FromRawFd for File { } cfg_windows! { - use crate::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle, AsHandle, BorrowedHandle}; + use crate::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle, AsHandle, BorrowedHandle, OwnedHandle}; + + impl From for File { + fn from(handle: OwnedHandle) -> Self { + Self::from_std(StdFile::from(handle)) + } + } impl AsRawHandle for File { fn as_raw_handle(&self) -> RawHandle { diff --git a/tokio/src/fs/mocks.rs b/tokio/src/fs/mocks.rs index 138e12ac6..6743fab55 100644 --- a/tokio/src/fs/mocks.rs +++ b/tokio/src/fs/mocks.rs @@ -38,6 +38,10 @@ mock! { pub fn try_clone(&self) -> io::Result; } #[cfg(windows)] + impl From for File { + fn from(handle: std::os::windows::io::OwnedHandle) -> Self; + } + #[cfg(windows)] impl std::os::windows::io::AsRawHandle for File { fn as_raw_handle(&self) -> std::os::windows::io::RawHandle; }