From 6b5c7918803aed37d73d1e3be3eaa5e44e2fe0af Mon Sep 17 00:00:00 2001 From: Avril Date: Sun, 23 Oct 2022 05:34:17 +0100 Subject: [PATCH] Added fd-aliasing for Un/ManagedFD MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fortune for mapped-file's current commit: Great blessing − 大吉 --- Cargo.toml | 2 +- src/file/managed.rs | 17 ++++++++++++++--- src/file/memory.rs | 2 +- src/file/unmanaged.rs | 8 ++++++++ 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 264e722..0808cff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "mapped-file" description = "Construct a memory mapping over any file object" keywords = ["unix", "mmap", "generic", "file", "fd"] -version = "0.0.2" +version = "0.0.3" edition = "2021" repository="https://github.com/notflan/mapped-file" license="MIT" diff --git a/src/file/managed.rs b/src/file/managed.rs index e645d7c..2b1071b 100644 --- a/src/file/managed.rs +++ b/src/file/managed.rs @@ -24,6 +24,8 @@ impl Clone for ManagedFD { } } +//TODO: io::Read/io::Write impls for ManagedFD + impl ManagedFD { #[inline] @@ -32,6 +34,18 @@ impl ManagedFD Self(UnmanagedFD::new_unchecked(fd)) } + /// Duplicate a file-descriptor, aliasing the open resource for the lifetime of the returned `ManagedFD`.. + #[inline] + pub fn alias(file: &(impl AsRawFd + ?Sized)) -> io::Result + { + let r = unsafe { libc::dup(file.as_raw_fd()) }; + if let Some(r) = UnmanagedFD::new_raw(r) { + Ok(Self(r)) + } else { + Err(io::Error::last_os_error()) + } + } + #[inline] pub const fn take_raw(fd: RawFd) -> Self { @@ -101,6 +115,3 @@ impl From for std::fs::File } } } - - -//TODO: implement the rest of ManagedFD from `memfd` module in `utf8encode` diff --git a/src/file/memory.rs b/src/file/memory.rs index a02283c..8702a8c 100644 --- a/src/file/memory.rs +++ b/src/file/memory.rs @@ -234,4 +234,4 @@ impl From for std::fs::File } } -//TODO: implement `memfd` from `utf8encode`. +//TODO: io::Read/io::Write impls for MemoryFile diff --git a/src/file/unmanaged.rs b/src/file/unmanaged.rs index c6c7279..cff643b 100644 --- a/src/file/unmanaged.rs +++ b/src/file/unmanaged.rs @@ -79,4 +79,12 @@ impl AsRawFd for UnmanagedFD } } +impl From for ManagedFD { + #[inline] + fn from(from: UnmanagedFD) -> Self { + Self::take(unsafe { UnmanagedFD::new_unchecked( c_try!(libc::dup(from.get()) => if |x| x < 0; "dup(): failed to duplicate file descriptor {}", from.get()) ) }) + + } +} + //TODO: implement a full version of the temporary struct `UnmanagedFD` from `utf8encode`