]> git.lizzy.rs Git - rust.git/commitdiff
`impl<T: AsRawFd> for {Arc,Box}<T>`
authorJoshua Nelson <jnelson@cloudflare.com>
Thu, 26 May 2022 20:10:46 +0000 (15:10 -0500)
committerJoshua Nelson <jnelson@cloudflare.com>
Wed, 22 Jun 2022 04:03:55 +0000 (23:03 -0500)
This allows implementing traits that require a raw FD on Arc and Box.

Previously, you'd have to add the function to the trait itself:

```rust
trait MyTrait {
    fn as_raw_fd(&self) -> RawFd;
}

impl<T: MyTrait> MyTrait for Arc<T> {
    fn as_raw_fd(&self) -> RawFd {
        (**self).as_raw_fd()
    }
}
```

library/std/src/os/fd/raw.rs

index 47ee88d97fb9349fba80eb4ab47cfbc5e6895720..7b6d2402aa9dbf840afbb8809fd115faa3021695 100644 (file)
@@ -222,3 +222,35 @@ fn as_raw_fd(&self) -> RawFd {
         libc::STDERR_FILENO
     }
 }
+
+#[stable(feature = "asraw_ptrs", since = "1.63.0")]
+/// This blanket impl allows implementing custom traits that require `AsRawFd` on Arc.
+/// ```
+/// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
+/// # #[cfg(target_os = "wasi")]
+/// # use std::os::wasi::io::AsRawFd;
+/// # #[cfg(unix)]
+/// # use std::os::unix::io::AsRawFd;
+/// use std::net::UdpSocket;
+/// use std::sync::Arc;
+/// trait MyTrait: AsRawFd {
+/// }
+/// impl MyTrait for Arc<UdpSocket> {}
+/// impl MyTrait for Box<UdpSocket> {}
+/// # }
+/// ```
+#[stable(feature = "asrawfd_ptrs", since = "1.63.0")]
+impl<T: AsRawFd> AsRawFd for crate::sync::Arc<T> {
+    #[inline]
+    fn as_raw_fd(&self) -> RawFd {
+        (**self).as_raw_fd()
+    }
+}
+
+#[stable(feature = "asraw_ptrs", since = "1.63.0")]
+impl<T: AsRawFd> AsRawFd for Box<T> {
+    #[inline]
+    fn as_raw_fd(&self) -> RawFd {
+        (**self).as_raw_fd()
+    }
+}