Skip to main content

std/os/fd/
raw.rs

1//! Raw Unix-like file descriptors.
2
3#![stable(feature = "rust1", since = "1.0.0")]
4
5#[cfg(target_os = "hermit")]
6use hermit_abi as libc;
7#[cfg(target_os = "motor")]
8use moto_rt::libc;
9
10#[cfg(target_os = "motor")]
11use super::owned::OwnedFd;
12use crate::alloc::Allocator;
13#[cfg(not(target_os = "trusty"))]
14use crate::fs;
15use crate::io;
16use crate::macros::rustdoc_skip_body;
17#[cfg(target_os = "hermit")]
18use crate::os::hermit::io::OwnedFd;
19#[cfg(all(not(target_os = "hermit"), not(target_os = "motor")))]
20use crate::os::raw;
21#[cfg(all(doc, not(any(target_family = "wasm", target_env = "sgx", target_os = "l4re"))))]
22use crate::os::unix::io::AsFd;
23#[cfg(unix)]
24use crate::os::unix::io::OwnedFd;
25#[cfg(target_os = "wasi")]
26use crate::os::wasi::io::OwnedFd;
27#[cfg(not(target_os = "trusty"))]
28use crate::sys::{AsInner, FromInner, IntoInner};
29
30/// Raw file descriptors.
31#[stable(feature = "rust1", since = "1.0.0")]
32#[cfg(all(not(target_os = "hermit"), not(target_os = "motor")))]
33pub type RawFd = raw::c_int;
34#[stable(feature = "rust1", since = "1.0.0")]
35#[cfg(any(target_os = "hermit", target_os = "motor"))]
36pub type RawFd = i32;
37
38/// A trait to extract the raw file descriptor from an underlying object.
39///
40/// This is only available on unix and WASI platforms and must be imported in
41/// order to call the method. Windows platforms have a corresponding
42/// `AsRawHandle` and `AsRawSocket` set of traits.
43#[stable(feature = "rust1", since = "1.0.0")]
44pub trait AsRawFd {
45    /// Extracts the raw file descriptor.
46    ///
47    /// This function is typically used to **borrow** an owned file descriptor.
48    /// When used in this way, this method does **not** pass ownership of the
49    /// raw file descriptor to the caller, and the file descriptor is only
50    /// guaranteed to be valid while the original object has not yet been
51    /// destroyed.
52    ///
53    /// However, borrowing is not strictly required. See [`AsFd::as_fd`]
54    /// for an API which strictly borrows a file descriptor.
55    ///
56    /// # Example
57    ///
58    /// ```no_run
59    /// use std::fs::File;
60    /// # use std::io;
61    /// #[cfg(any(unix, target_os = "wasi"))]
62    /// use std::os::fd::{AsRawFd, RawFd};
63    ///
64    /// let mut f = File::open("foo.txt")?;
65    /// // Note that `raw_fd` is only valid as long as `f` exists.
66    /// #[cfg(any(unix, target_os = "wasi"))]
67    /// let raw_fd: RawFd = f.as_raw_fd();
68    /// # Ok::<(), io::Error>(())
69    /// ```
70    #[stable(feature = "rust1", since = "1.0.0")]
71    fn as_raw_fd(&self) -> RawFd;
72}
73
74/// A trait to express the ability to construct an object from a raw file
75/// descriptor.
76#[stable(feature = "from_raw_os", since = "1.1.0")]
77pub trait FromRawFd {
78    /// Constructs a new instance of `Self` from the given raw file
79    /// descriptor.
80    ///
81    /// This function is typically used to **consume ownership** of the
82    /// specified file descriptor. When used in this way, the returned object
83    /// will take responsibility for closing it when the object goes out of
84    /// scope.
85    ///
86    /// However, consuming ownership is not strictly required. Use a
87    /// [`From<OwnedFd>::from`] implementation for an API which strictly
88    /// consumes ownership.
89    ///
90    /// # Safety
91    ///
92    /// The `fd` passed in must be an [owned file descriptor][io-safety];
93    /// in particular, it must be open.
94    ///
95    /// [io-safety]: io#io-safety
96    ///
97    /// # Example
98    ///
99    /// ```no_run
100    /// use std::fs::File;
101    /// # use std::io;
102    /// #[cfg(any(unix, target_os = "wasi"))]
103    /// use std::os::fd::{FromRawFd, IntoRawFd, RawFd};
104    ///
105    /// let f = File::open("foo.txt")?;
106    /// # #[cfg(any(unix, target_os = "wasi"))]
107    /// let raw_fd: RawFd = f.into_raw_fd();
108    /// // SAFETY: no other functions should call `from_raw_fd`, so there
109    /// // is only one owner for the file descriptor.
110    /// # #[cfg(any(unix, target_os = "wasi"))]
111    /// let f = unsafe { File::from_raw_fd(raw_fd) };
112    /// # Ok::<(), io::Error>(())
113    /// ```
114    #[stable(feature = "from_raw_os", since = "1.1.0")]
115    unsafe fn from_raw_fd(fd: RawFd) -> Self;
116}
117
118/// A trait to express the ability to consume an object and acquire ownership of
119/// its raw file descriptor.
120#[stable(feature = "into_raw_os", since = "1.4.0")]
121pub trait IntoRawFd {
122    /// Consumes this object, returning the raw underlying file descriptor.
123    ///
124    /// This function is typically used to **transfer ownership** of the underlying
125    /// file descriptor to the caller. When used in this way, callers are then the unique
126    /// owners of the file descriptor and must close it once it's no longer needed.
127    ///
128    /// However, transferring ownership is not strictly required. Use a
129    /// [`Into<OwnedFd>::into`] implementation for an API which strictly
130    /// transfers ownership.
131    ///
132    /// # Example
133    ///
134    /// ```no_run
135    /// use std::fs::File;
136    /// # use std::io;
137    /// #[cfg(any(unix, target_os = "wasi"))]
138    /// use std::os::fd::{IntoRawFd, RawFd};
139    ///
140    /// let f = File::open("foo.txt")?;
141    /// #[cfg(any(unix, target_os = "wasi"))]
142    /// let raw_fd: RawFd = f.into_raw_fd();
143    /// # Ok::<(), io::Error>(())
144    /// ```
145    #[must_use = "losing the raw file descriptor may leak resources"]
146    #[stable(feature = "into_raw_os", since = "1.4.0")]
147    fn into_raw_fd(self) -> RawFd;
148}
149
150#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
151impl AsRawFd for RawFd {
152    #[inline]
153    fn as_raw_fd(&self) -> RawFd {
154        *self
155    }
156}
157#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
158impl IntoRawFd for RawFd {
159    #[inline]
160    fn into_raw_fd(self) -> RawFd {
161        self
162    }
163}
164#[stable(feature = "raw_fd_reflexive_traits", since = "1.48.0")]
165impl FromRawFd for RawFd {
166    #[inline]
167    unsafe fn from_raw_fd(fd: RawFd) -> RawFd {
168        fd
169    }
170}
171
172#[stable(feature = "rust1", since = "1.0.0")]
173#[cfg(not(target_os = "trusty"))]
174impl AsRawFd for fs::File {
175    #[inline]
176    #[rustdoc_skip_body]
177    fn as_raw_fd(&self) -> RawFd {
178        self.as_inner().as_raw_fd()
179    }
180}
181#[stable(feature = "from_raw_os", since = "1.1.0")]
182#[cfg(not(target_os = "trusty"))]
183impl FromRawFd for fs::File {
184    #[inline]
185    #[rustdoc_skip_body]
186    unsafe fn from_raw_fd(fd: RawFd) -> fs::File {
187        unsafe { fs::File::from(OwnedFd::from_raw_fd(fd)) }
188    }
189}
190#[stable(feature = "into_raw_os", since = "1.4.0")]
191#[cfg(not(target_os = "trusty"))]
192impl IntoRawFd for fs::File {
193    #[inline]
194    #[rustdoc_skip_body]
195    fn into_raw_fd(self) -> RawFd {
196        self.into_inner().into_inner().into_raw_fd()
197    }
198}
199
200#[stable(feature = "asraw_stdio", since = "1.21.0")]
201#[cfg(not(target_os = "trusty"))]
202impl AsRawFd for io::Stdin {
203    #[inline]
204    fn as_raw_fd(&self) -> RawFd {
205        libc::STDIN_FILENO
206    }
207}
208
209#[stable(feature = "asraw_stdio", since = "1.21.0")]
210impl AsRawFd for io::Stdout {
211    #[inline]
212    fn as_raw_fd(&self) -> RawFd {
213        libc::STDOUT_FILENO
214    }
215}
216
217#[stable(feature = "asraw_stdio", since = "1.21.0")]
218impl AsRawFd for io::Stderr {
219    #[inline]
220    fn as_raw_fd(&self) -> RawFd {
221        libc::STDERR_FILENO
222    }
223}
224
225#[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
226#[cfg(not(target_os = "trusty"))]
227impl<'a> AsRawFd for io::StdinLock<'a> {
228    #[inline]
229    fn as_raw_fd(&self) -> RawFd {
230        libc::STDIN_FILENO
231    }
232}
233
234#[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
235impl<'a> AsRawFd for io::StdoutLock<'a> {
236    #[inline]
237    fn as_raw_fd(&self) -> RawFd {
238        libc::STDOUT_FILENO
239    }
240}
241
242#[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
243impl<'a> AsRawFd for io::StderrLock<'a> {
244    #[inline]
245    fn as_raw_fd(&self) -> RawFd {
246        libc::STDERR_FILENO
247    }
248}
249
250/// This impl allows implementing traits that require `AsRawFd` on Arc.
251/// ```
252/// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
253/// # #[cfg(target_os = "wasi")]
254/// # use std::os::wasi::io::AsRawFd;
255/// # #[cfg(unix)]
256/// # use std::os::unix::io::AsRawFd;
257/// use std::net::UdpSocket;
258/// use std::sync::Arc;
259/// trait MyTrait: AsRawFd {
260/// }
261/// impl MyTrait for Arc<UdpSocket> {}
262/// impl MyTrait for Box<UdpSocket> {}
263/// # }
264/// ```
265#[stable(feature = "asrawfd_ptrs", since = "1.63.0")]
266impl<T: AsRawFd> AsRawFd for crate::sync::Arc<T> {
267    #[inline]
268    fn as_raw_fd(&self) -> RawFd {
269        (**self).as_raw_fd()
270    }
271}
272
273#[stable(feature = "asfd_rc", since = "1.69.0")]
274impl<T: AsRawFd> AsRawFd for crate::rc::Rc<T> {
275    #[inline]
276    fn as_raw_fd(&self) -> RawFd {
277        (**self).as_raw_fd()
278    }
279}
280
281#[unstable(feature = "unique_rc_arc", issue = "112566")]
282impl<T: AsRawFd + ?Sized> AsRawFd for crate::rc::UniqueRc<T> {
283    #[inline]
284    fn as_raw_fd(&self) -> RawFd {
285        (**self).as_raw_fd()
286    }
287}
288
289#[stable(feature = "asrawfd_ptrs", since = "1.63.0")]
290impl<T: AsRawFd, A: Allocator> AsRawFd for Box<T, A> {
291    #[inline]
292    fn as_raw_fd(&self) -> RawFd {
293        (**self).as_raw_fd()
294    }
295}
296
297#[stable(feature = "anonymous_pipe", since = "1.87.0")]
298#[cfg(not(target_os = "trusty"))]
299impl AsRawFd for io::PipeReader {
300    #[rustdoc_skip_body]
301    fn as_raw_fd(&self) -> RawFd {
302        self.0.as_raw_fd()
303    }
304}
305
306#[stable(feature = "anonymous_pipe", since = "1.87.0")]
307#[cfg(not(target_os = "trusty"))]
308impl FromRawFd for io::PipeReader {
309    #[rustdoc_skip_body]
310    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
311        Self::from_inner(unsafe { FromRawFd::from_raw_fd(raw_fd) })
312    }
313}
314
315#[stable(feature = "anonymous_pipe", since = "1.87.0")]
316#[cfg(not(target_os = "trusty"))]
317impl IntoRawFd for io::PipeReader {
318    #[rustdoc_skip_body]
319    fn into_raw_fd(self) -> RawFd {
320        self.0.into_raw_fd()
321    }
322}
323
324#[stable(feature = "anonymous_pipe", since = "1.87.0")]
325#[cfg(not(target_os = "trusty"))]
326impl AsRawFd for io::PipeWriter {
327    #[rustdoc_skip_body]
328    fn as_raw_fd(&self) -> RawFd {
329        self.0.as_raw_fd()
330    }
331}
332
333#[stable(feature = "anonymous_pipe", since = "1.87.0")]
334#[cfg(not(target_os = "trusty"))]
335impl FromRawFd for io::PipeWriter {
336    #[rustdoc_skip_body]
337    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
338        Self::from_inner(unsafe { FromRawFd::from_raw_fd(raw_fd) })
339    }
340}
341
342#[stable(feature = "anonymous_pipe", since = "1.87.0")]
343#[cfg(not(target_os = "trusty"))]
344impl IntoRawFd for io::PipeWriter {
345    #[rustdoc_skip_body]
346    fn into_raw_fd(self) -> RawFd {
347        self.0.into_raw_fd()
348    }
349}