1#![unstable(reason = "not public", issue = "none", feature = "fd")]
2
3#[cfg(test)]
4mod tests;
5
6cfg_select! {
7 target_os = "vxworks" => {
8 }
11 any(
12 all(target_os = "linux", not(target_env = "musl")),
13 target_os = "android",
14 target_os = "hurd"
15 ) => {
16 use libc::{off64_t, pread64, pwrite64};
19 }
20 _ => {
21 use libc::{off_t as off64_t, pread as pread64, pwrite as pwrite64};
22 }
23}
24
25use crate::cmp;
26use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read};
27use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
28#[cfg(all(target_os = "android", target_pointer_width = "64"))]
29use crate::sys::pal::weak::syscall;
30#[cfg(any(
31 all(target_os = "android", target_pointer_width = "32"),
32 all(target_vendor = "apple", not(all(target_os = "macos", target_arch = "aarch64")))
33))]
34use crate::sys::pal::weak::weak;
35use crate::sys::{AsInner, FromInner, IntoInner, cvt};
36
37#[derive(#[automatically_derived]impl ::core::fmt::Debug for FileDesc {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "FileDesc",
&&self.0)
}
}Debug)]
38pub struct FileDesc(OwnedFd);
39
40const READ_LIMIT: usize = cfg_select! {
52 any(target_vendor = "apple", target_os = "nto", target_os = "qnx") => libc::c_int::MAX as usize,
53 _ => libc::ssize_t::MAX as usize,
54};
55
56#[cfg(any(
57 target_os = "dragonfly",
58 target_os = "freebsd",
59 target_os = "netbsd",
60 target_os = "openbsd",
61 target_vendor = "apple",
62 target_os = "cygwin",
63))]
64const fn max_iov() -> usize {
65 libc::IOV_MAX as usize
66}
67
68#[cfg(any(
69 target_os = "android",
70 target_os = "emscripten",
71 target_os = "linux",
72 target_os = "nto",
73 target_os = "qnx",
74))]
75const fn max_iov() -> usize {
76 libc::UIO_MAXIOV as usize
77}
78
79#[cfg(not(any(
80 target_os = "android",
81 target_os = "dragonfly",
82 target_os = "emscripten",
83 target_os = "espidf",
84 target_os = "freebsd",
85 target_os = "linux",
86 target_os = "netbsd",
87 target_os = "nuttx",
88 target_os = "nto",
89 target_os = "qnx",
90 target_os = "openbsd",
91 target_os = "horizon",
92 target_os = "vita",
93 target_vendor = "apple",
94 target_os = "cygwin",
95)))]
96const fn max_iov() -> usize {
97 16 }
99
100impl FileDesc {
101 #[inline]
102 pub fn try_clone(&self) -> io::Result<Self> {
103 self.duplicate()
104 }
105
106 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
107 let ret = cvt(unsafe {
108 libc::read(
109 self.as_raw_fd(),
110 buf.as_mut_ptr() as *mut libc::c_void,
111 cmp::min(buf.len(), READ_LIMIT),
112 )
113 })?;
114 Ok(ret as usize)
115 }
116
117 #[cfg(not(any(
118 target_os = "espidf",
119 target_os = "horizon",
120 target_os = "vita",
121 target_os = "nuttx"
122 )))]
123 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
124 let ret = cvt(unsafe {
125 libc::readv(
126 self.as_raw_fd(),
127 bufs.as_mut_ptr() as *mut libc::iovec as *const libc::iovec,
128 cmp::min(bufs.len(), max_iov()) as libc::c_int,
129 )
130 })?;
131 Ok(ret as usize)
132 }
133
134 #[cfg(any(
135 target_os = "espidf",
136 target_os = "horizon",
137 target_os = "vita",
138 target_os = "nuttx"
139 ))]
140 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
141 io::default_read_vectored(|b| self.read(b), bufs)
142 }
143
144 #[inline]
145 pub fn is_read_vectored(&self) -> bool {
146 truecfg!(not(any(
147 target_os = "espidf",
148 target_os = "horizon",
149 target_os = "vita",
150 target_os = "nuttx",
151 target_os = "wasi",
152 )))
153 }
154
155 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
156 let mut me = self;
157 (&mut me).read_to_end(buf)
158 }
159
160 #[cfg(not(target_os = "vxworks"))]
161 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
162 cvt(unsafe {
163 pread64(
164 self.as_raw_fd(),
165 buf.as_mut_ptr() as *mut libc::c_void,
166 cmp::min(buf.len(), READ_LIMIT),
167 offset as off64_t, )
169 })
170 .map(|n| n as usize)
171 }
172
173 #[cfg(target_os = "vxworks")]
174 pub fn read_at(&self, _buf: &mut [u8], _offset: u64) -> io::Result<usize> {
175 Err(io::Error::UNSUPPORTED_PLATFORM)
176 }
177
178 pub fn read_buf(&self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
179 let ret = cvt(unsafe {
181 libc::read(
182 self.as_raw_fd(),
183 cursor.as_mut().as_mut_ptr().cast::<libc::c_void>(),
184 cmp::min(cursor.capacity(), READ_LIMIT),
185 )
186 })?;
187
188 unsafe {
190 cursor.advance(ret as usize);
191 }
192 Ok(())
193 }
194
195 #[cfg(not(target_os = "vxworks"))]
196 pub fn read_buf_at(&self, mut cursor: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
197 let ret = cvt(unsafe {
199 pread64(
200 self.as_raw_fd(),
201 cursor.as_mut().as_mut_ptr().cast::<libc::c_void>(),
202 cmp::min(cursor.capacity(), READ_LIMIT),
203 offset as off64_t, )
205 })?;
206
207 unsafe {
209 cursor.advance(ret as usize);
210 }
211 Ok(())
212 }
213
214 #[cfg(target_os = "vxworks")]
215 pub fn read_buf_at(&self, _cursor: BorrowedCursor<'_, u8>, _offset: u64) -> io::Result<()> {
216 Err(io::Error::UNSUPPORTED_PLATFORM)
217 }
218
219 #[cfg(any(
220 target_os = "aix",
221 target_os = "dragonfly", target_os = "emscripten",
223 target_os = "freebsd",
224 target_os = "fuchsia",
225 target_os = "hurd",
226 target_os = "illumos",
227 target_os = "linux",
228 target_os = "netbsd",
229 target_os = "openbsd", target_os = "l4re",
231 all(target_os = "macos", target_arch = "aarch64"),
232 ))]
233 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
234 let ret = cvt(unsafe {
235 libc::preadv(
236 self.as_raw_fd(),
237 bufs.as_mut_ptr() as *mut libc::iovec as *const libc::iovec,
238 cmp::min(bufs.len(), max_iov()) as libc::c_int,
239 offset as _,
240 )
241 })?;
242 Ok(ret as usize)
243 }
244
245 #[cfg(not(any(
246 target_os = "aix",
247 target_os = "android",
248 target_os = "dragonfly",
249 target_os = "emscripten",
250 target_os = "freebsd",
251 target_os = "fuchsia",
252 target_os = "hurd",
253 target_os = "illumos",
254 target_os = "linux",
255 target_os = "netbsd",
256 target_os = "openbsd",
257 target_vendor = "apple",
258 target_os = "l4re",
259 )))]
260 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
261 io::default_read_vectored(|b| self.read_at(b, offset), bufs)
262 }
263
264 #[cfg(all(target_os = "android", target_pointer_width = "64"))]
271 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
272 syscall!(
273 fn preadv(
274 fd: libc::c_int,
275 iovec: *const libc::iovec,
276 n_iovec: libc::c_int,
277 offset: off64_t,
278 ) -> isize;
279 );
280
281 let ret = cvt(unsafe {
282 preadv(
283 self.as_raw_fd(),
284 bufs.as_mut_ptr() as *mut libc::iovec as *const libc::iovec,
285 cmp::min(bufs.len(), max_iov()) as libc::c_int,
286 offset as _,
287 )
288 })?;
289 Ok(ret as usize)
290 }
291
292 #[cfg(all(target_os = "android", target_pointer_width = "32"))]
293 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
294 weak!(
295 fn preadv64(
296 fd: libc::c_int,
297 iovec: *const libc::iovec,
298 n_iovec: libc::c_int,
299 offset: off64_t,
300 ) -> isize;
301 );
302
303 match preadv64.get() {
304 Some(preadv) => {
305 let ret = cvt(unsafe {
306 preadv(
307 self.as_raw_fd(),
308 bufs.as_mut_ptr() as *mut libc::iovec as *const libc::iovec,
309 cmp::min(bufs.len(), max_iov()) as libc::c_int,
310 offset as _,
311 )
312 })?;
313 Ok(ret as usize)
314 }
315 None => io::default_read_vectored(|b| self.read_at(b, offset), bufs),
316 }
317 }
318
319 #[cfg(all(target_vendor = "apple", not(all(target_os = "macos", target_arch = "aarch64"))))]
330 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
331 weak!(
332 fn preadv(
333 fd: libc::c_int,
334 iovec: *const libc::iovec,
335 n_iovec: libc::c_int,
336 offset: off64_t,
337 ) -> isize;
338 );
339
340 match preadv.get() {
341 Some(preadv) => {
342 let ret = cvt(unsafe {
343 preadv(
344 self.as_raw_fd(),
345 bufs.as_mut_ptr() as *mut libc::iovec as *const libc::iovec,
346 cmp::min(bufs.len(), max_iov()) as libc::c_int,
347 offset as _,
348 )
349 })?;
350 Ok(ret as usize)
351 }
352 None => io::default_read_vectored(|b| self.read_at(b, offset), bufs),
353 }
354 }
355
356 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
357 let ret = cvt(unsafe {
358 libc::write(
359 self.as_raw_fd(),
360 buf.as_ptr() as *const libc::c_void,
361 cmp::min(buf.len(), READ_LIMIT),
362 )
363 })?;
364 Ok(ret as usize)
365 }
366
367 #[cfg(not(any(
368 target_os = "espidf",
369 target_os = "horizon",
370 target_os = "vita",
371 target_os = "nuttx"
372 )))]
373 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
374 let ret = cvt(unsafe {
375 libc::writev(
376 self.as_raw_fd(),
377 bufs.as_ptr() as *const libc::iovec,
378 cmp::min(bufs.len(), max_iov()) as libc::c_int,
379 )
380 })?;
381 Ok(ret as usize)
382 }
383
384 #[cfg(any(
385 target_os = "espidf",
386 target_os = "horizon",
387 target_os = "vita",
388 target_os = "nuttx"
389 ))]
390 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
391 io::default_write_vectored(|b| self.write(b), bufs)
392 }
393
394 #[inline]
395 pub fn is_write_vectored(&self) -> bool {
396 truecfg!(not(any(
397 target_os = "espidf",
398 target_os = "horizon",
399 target_os = "vita",
400 target_os = "nuttx",
401 target_os = "wasi",
402 )))
403 }
404
405 #[cfg(not(target_os = "vxworks"))]
406 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
407 unsafe {
408 cvt(pwrite64(
409 self.as_raw_fd(),
410 buf.as_ptr() as *const libc::c_void,
411 cmp::min(buf.len(), READ_LIMIT),
412 offset as off64_t,
413 ))
414 .map(|n| n as usize)
415 }
416 }
417
418 #[cfg(target_os = "vxworks")]
419 pub fn write_at(&self, _buf: &[u8], _offset: u64) -> io::Result<usize> {
420 Err(io::Error::UNSUPPORTED_PLATFORM)
421 }
422
423 #[cfg(any(
424 target_os = "aix",
425 target_os = "dragonfly", target_os = "emscripten",
427 target_os = "freebsd",
428 target_os = "fuchsia",
429 target_os = "hurd",
430 target_os = "illumos",
431 target_os = "linux",
432 target_os = "netbsd",
433 target_os = "openbsd", all(target_os = "macos", target_arch = "aarch64"),
435 ))]
436 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
437 let ret = cvt(unsafe {
438 libc::pwritev(
439 self.as_raw_fd(),
440 bufs.as_ptr() as *const libc::iovec,
441 cmp::min(bufs.len(), max_iov()) as libc::c_int,
442 offset as _,
443 )
444 })?;
445 Ok(ret as usize)
446 }
447
448 #[cfg(not(any(
449 target_os = "aix",
450 target_os = "android",
451 target_os = "dragonfly",
452 target_os = "emscripten",
453 target_os = "freebsd",
454 target_os = "fuchsia",
455 target_os = "hurd",
456 target_os = "illumos",
457 target_os = "linux",
458 target_os = "netbsd",
459 target_os = "openbsd",
460 target_vendor = "apple",
461 )))]
462 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
463 io::default_write_vectored(|b| self.write_at(b, offset), bufs)
464 }
465
466 #[cfg(all(target_os = "android", target_pointer_width = "64"))]
473 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
474 syscall!(
475 fn pwritev(
476 fd: libc::c_int,
477 iovec: *const libc::iovec,
478 n_iovec: libc::c_int,
479 offset: off64_t,
480 ) -> isize;
481 );
482
483 let ret = cvt(unsafe {
484 pwritev(
485 self.as_raw_fd(),
486 bufs.as_ptr() as *const libc::iovec,
487 cmp::min(bufs.len(), max_iov()) as libc::c_int,
488 offset as _,
489 )
490 })?;
491 Ok(ret as usize)
492 }
493
494 #[cfg(all(target_os = "android", target_pointer_width = "32"))]
495 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
496 weak!(
497 fn pwritev64(
498 fd: libc::c_int,
499 iovec: *const libc::iovec,
500 n_iovec: libc::c_int,
501 offset: off64_t,
502 ) -> isize;
503 );
504
505 match pwritev64.get() {
506 Some(pwritev) => {
507 let ret = cvt(unsafe {
508 pwritev(
509 self.as_raw_fd(),
510 bufs.as_ptr() as *const libc::iovec,
511 cmp::min(bufs.len(), max_iov()) as libc::c_int,
512 offset as _,
513 )
514 })?;
515 Ok(ret as usize)
516 }
517 None => io::default_write_vectored(|b| self.write_at(b, offset), bufs),
518 }
519 }
520
521 #[cfg(all(target_vendor = "apple", not(all(target_os = "macos", target_arch = "aarch64")),))]
532 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
533 weak!(
534 fn pwritev(
535 fd: libc::c_int,
536 iovec: *const libc::iovec,
537 n_iovec: libc::c_int,
538 offset: off64_t,
539 ) -> isize;
540 );
541
542 match pwritev.get() {
543 Some(pwritev) => {
544 let ret = cvt(unsafe {
545 pwritev(
546 self.as_raw_fd(),
547 bufs.as_ptr() as *const libc::iovec,
548 cmp::min(bufs.len(), max_iov()) as libc::c_int,
549 offset as _,
550 )
551 })?;
552 Ok(ret as usize)
553 }
554 None => io::default_write_vectored(|b| self.write_at(b, offset), bufs),
555 }
556 }
557
558 #[cfg(not(any(
559 target_env = "newlib",
560 target_os = "solaris",
561 target_os = "illumos",
562 target_os = "emscripten",
563 target_os = "fuchsia",
564 target_os = "l4re",
565 target_os = "linux",
566 target_os = "cygwin",
567 target_os = "haiku",
568 target_os = "redox",
569 target_os = "vxworks",
570 target_os = "nto",
571 target_os = "qnx",
572 target_os = "wasi",
573 )))]
574 pub fn set_cloexec(&self) -> io::Result<()> {
575 unsafe {
576 cvt(libc::ioctl(self.as_raw_fd(), libc::FIOCLEX))?;
577 Ok(())
578 }
579 }
580 #[cfg(any(
581 all(
582 target_env = "newlib",
583 not(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))
584 ),
585 target_os = "solaris",
586 target_os = "illumos",
587 target_os = "emscripten",
588 target_os = "fuchsia",
589 target_os = "l4re",
590 target_os = "linux",
591 target_os = "cygwin",
592 target_os = "haiku",
593 target_os = "redox",
594 target_os = "vxworks",
595 target_os = "nto",
596 target_os = "qnx",
597 target_os = "wasi",
598 ))]
599 pub fn set_cloexec(&self) -> io::Result<()> {
600 unsafe {
601 let previous = cvt(libc::fcntl(self.as_raw_fd(), libc::F_GETFD))?;
602 let new = previous | libc::FD_CLOEXEC;
603 if new != previous {
604 cvt(libc::fcntl(self.as_raw_fd(), libc::F_SETFD, new))?;
605 }
606 Ok(())
607 }
608 }
609 #[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))]
610 pub fn set_cloexec(&self) -> io::Result<()> {
611 Ok(())
614 }
615
616 #[cfg(target_os = "linux")]
617 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
618 unsafe {
619 let v = nonblocking as libc::c_int;
620 cvt(libc::ioctl(self.as_raw_fd(), libc::FIONBIO, &v))?;
621 Ok(())
622 }
623 }
624
625 #[cfg(not(target_os = "linux"))]
626 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
627 unsafe {
628 let previous = cvt(libc::fcntl(self.as_raw_fd(), libc::F_GETFL))?;
629 let new = if nonblocking {
630 previous | libc::O_NONBLOCK
631 } else {
632 previous & !libc::O_NONBLOCK
633 };
634 if new != previous {
635 cvt(libc::fcntl(self.as_raw_fd(), libc::F_SETFL, new))?;
636 }
637 Ok(())
638 }
639 }
640
641 #[inline]
642 pub fn duplicate(&self) -> io::Result<FileDesc> {
643 Ok(Self(self.0.try_clone()?))
644 }
645}
646
647impl<'a> Read for &'a FileDesc {
648 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
649 (**self).read(buf)
650 }
651
652 fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
653 (**self).read_buf(cursor)
654 }
655
656 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
657 (**self).read_vectored(bufs)
658 }
659
660 #[inline]
661 fn is_read_vectored(&self) -> bool {
662 (**self).is_read_vectored()
663 }
664}
665
666impl AsInner<OwnedFd> for FileDesc {
667 #[inline]
668 fn as_inner(&self) -> &OwnedFd {
669 &self.0
670 }
671}
672
673impl IntoInner<OwnedFd> for FileDesc {
674 fn into_inner(self) -> OwnedFd {
675 self.0
676 }
677}
678
679impl FromInner<OwnedFd> for FileDesc {
680 fn from_inner(owned_fd: OwnedFd) -> Self {
681 Self(owned_fd)
682 }
683}
684
685impl AsFd for FileDesc {
686 fn as_fd(&self) -> BorrowedFd<'_> {
687 self.0.as_fd()
688 }
689}
690
691impl AsRawFd for FileDesc {
692 #[inline]
693 fn as_raw_fd(&self) -> RawFd {
694 self.0.as_raw_fd()
695 }
696}
697
698impl IntoRawFd for FileDesc {
699 fn into_raw_fd(self) -> RawFd {
700 self.0.into_raw_fd()
701 }
702}
703
704impl FromRawFd for FileDesc {
705 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
706 Self(unsafe { FromRawFd::from_raw_fd(raw_fd) })
707 }
708}