tokio/io/async_fd.rs
1use crate::io::{Interest, Ready};
2use crate::runtime::io::{ReadyEvent, Registration};
3use crate::runtime::scheduler;
4
5use mio::unix::SourceFd;
6use std::error::Error;
7use std::fmt;
8use std::io;
9use std::os::unix::io::{AsRawFd, RawFd};
10use std::task::{ready, Context, Poll};
11
12/// Associates an IO object backed by a Unix file descriptor with the tokio
13/// reactor, allowing for readiness to be polled. The file descriptor must be of
14/// a type that can be used with the OS polling facilities (ie, `poll`, `epoll`,
15/// `kqueue`, etc), such as a network socket or pipe, and the file descriptor
16/// must have the nonblocking mode set to true.
17///
18/// Creating an [`AsyncFd`] registers the file descriptor with the current tokio
19/// Reactor, allowing you to directly await the file descriptor being readable
20/// or writable. Once registered, the file descriptor remains registered until
21/// the [`AsyncFd`] is dropped.
22///
23/// The [`AsyncFd`] takes ownership of an arbitrary object to represent the IO
24/// object. It is intended that the inner object will handle closing the file
25/// descriptor when it is dropped, avoiding resource leaks and ensuring that the
26/// [`AsyncFd`] can clean up the registration before closing the file descriptor.
27/// The [`AsyncFd::into_inner`] function can be used to extract the inner object
28/// to retake control from the tokio IO reactor. The [`OwnedFd`] type is often
29/// used as the inner object, as it is the simplest type that closes the fd on
30/// drop.
31///
32/// The inner object is required to implement [`AsRawFd`]. This file descriptor
33/// must remain open and must not change while [`AsyncFd`] owns the inner
34/// object, i.e. the [`AsRawFd::as_raw_fd`] method on the inner type must always
35/// return the same valid file descriptor referring to the same underlying file
36/// description when called multiple times. Violating this requirement leads to
37/// undefined behavior.
38///
39/// Polling for readiness is done by calling the async functions [`readable`]
40/// and [`writable`]. These functions complete when the associated readiness
41/// condition is observed. Any number of tasks can query the same `AsyncFd` in
42/// parallel, on the same or different conditions.
43///
44/// On some platforms, the readiness detecting mechanism relies on
45/// edge-triggered notifications. This means that the OS will only notify Tokio
46/// when the file descriptor transitions from not-ready to ready. For this to
47/// work you should first try to read or write and only poll for readiness
48/// if that fails with an error of [`std::io::ErrorKind::WouldBlock`].
49///
50/// Tokio internally tracks when it has received a ready notification, and when
51/// readiness checking functions like [`readable`] and [`writable`] are called,
52/// if the readiness flag is set, these async functions will complete
53/// immediately. This however does mean that it is critical to ensure that this
54/// ready flag is cleared when (and only when) the file descriptor ceases to be
55/// ready. The [`AsyncFdReadyGuard`] returned from readiness checking functions
56/// serves this function; after calling a readiness-checking async function,
57/// you must use this [`AsyncFdReadyGuard`] to signal to tokio whether the file
58/// descriptor is no longer in a ready state.
59///
60/// ## Use with to a poll-based API
61///
62/// In some cases it may be desirable to use `AsyncFd` from APIs similar to
63/// [`TcpStream::poll_read_ready`]. The [`AsyncFd::poll_read_ready`] and
64/// [`AsyncFd::poll_write_ready`] functions are provided for this purpose.
65/// Because these functions don't create a future to hold their state, they have
66/// the limitation that only one task can wait on each direction (read or write)
67/// at a time.
68///
69/// # Examples
70///
71/// This example shows how to turn [`std::net::TcpStream`] asynchronous using
72/// `AsyncFd`. It implements the read/write operations both as an `async fn`
73/// and using the IO traits [`AsyncRead`] and [`AsyncWrite`].
74///
75/// ```no_run
76/// use std::io::{self, Read, Write};
77/// use std::net::TcpStream;
78/// use std::pin::Pin;
79/// use std::task::{ready, Context, Poll};
80/// use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
81/// use tokio::io::unix::AsyncFd;
82///
83/// pub struct AsyncTcpStream {
84/// inner: AsyncFd<TcpStream>,
85/// }
86///
87/// impl AsyncTcpStream {
88/// pub fn new(tcp: TcpStream) -> io::Result<Self> {
89/// tcp.set_nonblocking(true)?;
90/// // SAFETY: `TcpStream` owns a valid file descriptor and we do not
91/// // replace or close it while owned by `AsyncFd`.
92/// Ok(Self {
93/// inner: unsafe { AsyncFd::register(tcp)? },
94/// })
95/// }
96///
97/// pub async fn read(&self, out: &mut [u8]) -> io::Result<usize> {
98/// loop {
99/// let mut guard = self.inner.readable().await?;
100///
101/// match guard.try_io(|inner| inner.get_ref().read(out)) {
102/// Ok(result) => return result,
103/// Err(_would_block) => continue,
104/// }
105/// }
106/// }
107///
108/// pub async fn write(&self, buf: &[u8]) -> io::Result<usize> {
109/// loop {
110/// let mut guard = self.inner.writable().await?;
111///
112/// match guard.try_io(|inner| inner.get_ref().write(buf)) {
113/// Ok(result) => return result,
114/// Err(_would_block) => continue,
115/// }
116/// }
117/// }
118/// }
119///
120/// impl AsyncRead for AsyncTcpStream {
121/// fn poll_read(
122/// self: Pin<&mut Self>,
123/// cx: &mut Context<'_>,
124/// buf: &mut ReadBuf<'_>
125/// ) -> Poll<io::Result<()>> {
126/// loop {
127/// let mut guard = ready!(self.inner.poll_read_ready(cx))?;
128///
129/// let unfilled = buf.initialize_unfilled();
130/// match guard.try_io(|inner| inner.get_ref().read(unfilled)) {
131/// Ok(Ok(len)) => {
132/// buf.advance(len);
133/// return Poll::Ready(Ok(()));
134/// },
135/// Ok(Err(err)) => return Poll::Ready(Err(err)),
136/// Err(_would_block) => continue,
137/// }
138/// }
139/// }
140/// }
141///
142/// impl AsyncWrite for AsyncTcpStream {
143/// fn poll_write(
144/// self: Pin<&mut Self>,
145/// cx: &mut Context<'_>,
146/// buf: &[u8]
147/// ) -> Poll<io::Result<usize>> {
148/// loop {
149/// let mut guard = ready!(self.inner.poll_write_ready(cx))?;
150///
151/// match guard.try_io(|inner| inner.get_ref().write(buf)) {
152/// Ok(result) => return Poll::Ready(result),
153/// Err(_would_block) => continue,
154/// }
155/// }
156/// }
157///
158/// fn poll_flush(
159/// self: Pin<&mut Self>,
160/// cx: &mut Context<'_>,
161/// ) -> Poll<io::Result<()>> {
162/// // tcp flush is a no-op
163/// Poll::Ready(Ok(()))
164/// }
165///
166/// fn poll_shutdown(
167/// self: Pin<&mut Self>,
168/// cx: &mut Context<'_>,
169/// ) -> Poll<io::Result<()>> {
170/// self.inner.get_ref().shutdown(std::net::Shutdown::Write)?;
171/// Poll::Ready(Ok(()))
172/// }
173/// }
174/// ```
175///
176/// [`readable`]: method@Self::readable
177/// [`writable`]: method@Self::writable
178/// [`AsyncFdReadyGuard`]: struct@self::AsyncFdReadyGuard
179/// [`TcpStream::poll_read_ready`]: struct@crate::net::TcpStream
180/// [`AsyncRead`]: trait@crate::io::AsyncRead
181/// [`AsyncWrite`]: trait@crate::io::AsyncWrite
182/// [`OwnedFd`]: struct@std::os::fd::OwnedFd
183pub struct AsyncFd<T: AsRawFd> {
184 registration: Registration,
185 // The inner value is always present. the Option is required for `drop` and `into_inner`.
186 // In all other methods `unwrap` is valid, and will never panic.
187 inner: Option<T>,
188}
189
190/// Represents an IO-ready event detected on a particular file descriptor that
191/// has not yet been acknowledged. This is a `must_use` structure to help ensure
192/// that you do not forget to explicitly clear (or not clear) the event.
193///
194/// This type exposes an immutable reference to the underlying IO object.
195#[must_use = "You must explicitly choose whether to clear the readiness state by calling a method on ReadyGuard"]
196pub struct AsyncFdReadyGuard<'a, T: AsRawFd> {
197 async_fd: &'a AsyncFd<T>,
198 event: Option<ReadyEvent>,
199}
200
201/// Represents an IO-ready event detected on a particular file descriptor that
202/// has not yet been acknowledged. This is a `must_use` structure to help ensure
203/// that you do not forget to explicitly clear (or not clear) the event.
204///
205/// This type exposes a mutable reference to the underlying IO object.
206#[must_use = "You must explicitly choose whether to clear the readiness state by calling a method on ReadyGuard"]
207pub struct AsyncFdReadyMutGuard<'a, T: AsRawFd> {
208 async_fd: &'a mut AsyncFd<T>,
209 event: Option<ReadyEvent>,
210}
211
212impl<T: AsRawFd> AsyncFd<T> {
213 /// Creates an `AsyncFd` backed by (and taking ownership of) an object
214 /// implementing [`AsRawFd`].
215 ///
216 /// Only configures the [`Interest::READABLE`] and [`Interest::WRITABLE`] interests. For more
217 /// control, use [`AsyncFd::register_with_interest`].
218 ///
219 /// This method must be called in the context of a tokio runtime.
220 ///
221 /// In the case of failure, it returns an [`AsyncFdRegisterError`] that contains the original
222 /// object passed to this function.
223 ///
224 /// # Safety
225 ///
226 /// The file descriptor returned by [`inner.as_raw_fd()`](AsRawFd::as_raw_fd) must be a valid,
227 /// open file descriptor, and it must remain open and refer to the same underlying file
228 /// description for the entire lifetime of the `AsyncFd` (i.e., until the `AsyncFd` is
229 /// dropped, or [`AsyncFd::into_inner`] is called, or the `AsyncFd` is
230 /// [forgotten](std::mem::forget)). While owned by this `AsyncFd`, every call to
231 /// [`inner.as_raw_fd()`](AsRawFd::as_raw_fd) must return that same file descriptor.
232 ///
233 /// # Panics
234 ///
235 /// This function panics if there is no current reactor set, or if the `rt`
236 /// feature flag is not enabled.
237 #[inline]
238 #[track_caller]
239 pub unsafe fn register(inner: T) -> Result<Self, AsyncFdRegisterError<T>> {
240 // SAFETY: Upheld by the caller.
241 unsafe { Self::register_with_interest(inner, Interest::READABLE | Interest::WRITABLE) }
242 }
243
244 /// Creates an `AsyncFd` backed by (and taking ownership of) an object
245 /// implementing [`AsRawFd`], with a specific [`Interest`].
246 ///
247 /// This method must be called in the context of a tokio runtime.
248 ///
249 /// In the case of failure, it returns an [`AsyncFdRegisterError`] that contains the original
250 /// object passed to this function.
251 ///
252 /// # Safety
253 ///
254 /// The file descriptor returned by [`inner.as_raw_fd()`](AsRawFd::as_raw_fd) must be a valid,
255 /// open file descriptor, and it must remain open and refer to the same underlying file
256 /// description for the entire lifetime of the `AsyncFd` (i.e., until the `AsyncFd` is
257 /// dropped, or [`AsyncFd::into_inner`] is called, or the `AsyncFd` is
258 /// [forgotten](std::mem::forget)). While owned by this `AsyncFd`, every call to
259 /// [`inner.as_raw_fd()`](AsRawFd::as_raw_fd) must return that same file descriptor.
260 ///
261 /// # Panics
262 ///
263 /// This function panics if there is no current reactor set, or if the `rt`
264 /// feature flag is not enabled.
265 #[inline]
266 #[track_caller]
267 pub unsafe fn register_with_interest(
268 inner: T,
269 interest: Interest,
270 ) -> Result<Self, AsyncFdRegisterError<T>> {
271 let fd = inner.as_raw_fd();
272
273 match Registration::new_with_interest_and_handle(
274 &mut SourceFd(&fd),
275 interest,
276 scheduler::Handle::current(),
277 ) {
278 Ok(registration) => Ok(AsyncFd {
279 registration,
280 inner: Some(inner),
281 }),
282 Err(cause) => Err(AsyncFdRegisterError { inner, cause }),
283 }
284 }
285
286 /// Returns a shared reference to the backing object of this [`AsyncFd`].
287 #[inline]
288 pub fn get_ref(&self) -> &T {
289 self.inner.as_ref().unwrap()
290 }
291
292 /// Returns a mutable reference to the backing object of this `AsyncFd`.
293 ///
294 /// This may be used to bypass the readiness of the IO resource, so that you
295 /// can read or write to it even if the fd is not ready. Be aware that this
296 /// method must not be used to exchange the underlying IO resource for a
297 /// different one. Doing so is a violation of the safety requirements on
298 /// [`AsyncFd::register`].
299 #[inline]
300 pub fn get_mut(&mut self) -> &mut T {
301 self.inner.as_mut().unwrap()
302 }
303
304 fn take_inner(&mut self) -> Option<T> {
305 let inner = self.inner.take()?;
306 let fd = inner.as_raw_fd();
307
308 let _ = self.registration.deregister(&mut SourceFd(&fd));
309
310 Some(inner)
311 }
312
313 /// Deregisters this file descriptor and returns ownership of the backing
314 /// object.
315 pub fn into_inner(mut self) -> T {
316 self.take_inner().unwrap()
317 }
318
319 /// Polls for read readiness.
320 ///
321 /// If the file descriptor is not currently ready for reading, this method
322 /// will store a clone of the [`Waker`] from the provided [`Context`]. When the
323 /// file descriptor becomes ready for reading, [`Waker::wake`] will be called.
324 ///
325 /// Note that on multiple calls to [`poll_read_ready`] or
326 /// [`poll_read_ready_mut`], only the `Waker` from the `Context` passed to the
327 /// most recent call is scheduled to receive a wakeup. (However,
328 /// [`poll_write_ready`] retains a second, independent waker).
329 ///
330 /// This method is intended for cases where creating and pinning a future
331 /// via [`readable`] is not feasible. Where possible, using [`readable`] is
332 /// preferred, as this supports polling from multiple tasks at once.
333 ///
334 /// This method takes `&self`, so it is possible to call this method
335 /// concurrently with other methods on this struct. This method only
336 /// provides shared access to the inner IO resource when handling the
337 /// [`AsyncFdReadyGuard`].
338 ///
339 /// [`poll_read_ready`]: method@Self::poll_read_ready
340 /// [`poll_read_ready_mut`]: method@Self::poll_read_ready_mut
341 /// [`poll_write_ready`]: method@Self::poll_write_ready
342 /// [`readable`]: method@Self::readable
343 /// [`Context`]: struct@std::task::Context
344 /// [`Waker`]: struct@std::task::Waker
345 /// [`Waker::wake`]: method@std::task::Waker::wake
346 pub fn poll_read_ready<'a>(
347 &'a self,
348 cx: &mut Context<'_>,
349 ) -> Poll<io::Result<AsyncFdReadyGuard<'a, T>>> {
350 let event = ready!(self.registration.poll_read_ready(cx))?;
351
352 Poll::Ready(Ok(AsyncFdReadyGuard {
353 async_fd: self,
354 event: Some(event),
355 }))
356 }
357
358 /// Polls for read readiness.
359 ///
360 /// If the file descriptor is not currently ready for reading, this method
361 /// will store a clone of the [`Waker`] from the provided [`Context`]. When the
362 /// file descriptor becomes ready for reading, [`Waker::wake`] will be called.
363 ///
364 /// Note that on multiple calls to [`poll_read_ready`] or
365 /// [`poll_read_ready_mut`], only the `Waker` from the `Context` passed to the
366 /// most recent call is scheduled to receive a wakeup. (However,
367 /// [`poll_write_ready`] retains a second, independent waker).
368 ///
369 /// This method is intended for cases where creating and pinning a future
370 /// via [`readable`] is not feasible. Where possible, using [`readable`] is
371 /// preferred, as this supports polling from multiple tasks at once.
372 ///
373 /// This method takes `&mut self`, so it is possible to access the inner IO
374 /// resource mutably when handling the [`AsyncFdReadyMutGuard`].
375 ///
376 /// [`poll_read_ready`]: method@Self::poll_read_ready
377 /// [`poll_read_ready_mut`]: method@Self::poll_read_ready_mut
378 /// [`poll_write_ready`]: method@Self::poll_write_ready
379 /// [`readable`]: method@Self::readable
380 /// [`Context`]: struct@std::task::Context
381 /// [`Waker`]: struct@std::task::Waker
382 /// [`Waker::wake`]: method@std::task::Waker::wake
383 pub fn poll_read_ready_mut<'a>(
384 &'a mut self,
385 cx: &mut Context<'_>,
386 ) -> Poll<io::Result<AsyncFdReadyMutGuard<'a, T>>> {
387 let event = ready!(self.registration.poll_read_ready(cx))?;
388
389 Poll::Ready(Ok(AsyncFdReadyMutGuard {
390 async_fd: self,
391 event: Some(event),
392 }))
393 }
394
395 /// Polls for write readiness.
396 ///
397 /// If the file descriptor is not currently ready for writing, this method
398 /// will store a clone of the [`Waker`] from the provided [`Context`]. When the
399 /// file descriptor becomes ready for writing, [`Waker::wake`] will be called.
400 ///
401 /// Note that on multiple calls to [`poll_write_ready`] or
402 /// [`poll_write_ready_mut`], only the `Waker` from the `Context` passed to the
403 /// most recent call is scheduled to receive a wakeup. (However,
404 /// [`poll_read_ready`] retains a second, independent waker).
405 ///
406 /// This method is intended for cases where creating and pinning a future
407 /// via [`writable`] is not feasible. Where possible, using [`writable`] is
408 /// preferred, as this supports polling from multiple tasks at once.
409 ///
410 /// This method takes `&self`, so it is possible to call this method
411 /// concurrently with other methods on this struct. This method only
412 /// provides shared access to the inner IO resource when handling the
413 /// [`AsyncFdReadyGuard`].
414 ///
415 /// [`poll_read_ready`]: method@Self::poll_read_ready
416 /// [`poll_write_ready`]: method@Self::poll_write_ready
417 /// [`poll_write_ready_mut`]: method@Self::poll_write_ready_mut
418 /// [`writable`]: method@Self::readable
419 /// [`Context`]: struct@std::task::Context
420 /// [`Waker`]: struct@std::task::Waker
421 /// [`Waker::wake`]: method@std::task::Waker::wake
422 pub fn poll_write_ready<'a>(
423 &'a self,
424 cx: &mut Context<'_>,
425 ) -> Poll<io::Result<AsyncFdReadyGuard<'a, T>>> {
426 let event = ready!(self.registration.poll_write_ready(cx))?;
427
428 Poll::Ready(Ok(AsyncFdReadyGuard {
429 async_fd: self,
430 event: Some(event),
431 }))
432 }
433
434 /// Polls for write readiness.
435 ///
436 /// If the file descriptor is not currently ready for writing, this method
437 /// will store a clone of the [`Waker`] from the provided [`Context`]. When the
438 /// file descriptor becomes ready for writing, [`Waker::wake`] will be called.
439 ///
440 /// Note that on multiple calls to [`poll_write_ready`] or
441 /// [`poll_write_ready_mut`], only the `Waker` from the `Context` passed to the
442 /// most recent call is scheduled to receive a wakeup. (However,
443 /// [`poll_read_ready`] retains a second, independent waker).
444 ///
445 /// This method is intended for cases where creating and pinning a future
446 /// via [`writable`] is not feasible. Where possible, using [`writable`] is
447 /// preferred, as this supports polling from multiple tasks at once.
448 ///
449 /// This method takes `&mut self`, so it is possible to access the inner IO
450 /// resource mutably when handling the [`AsyncFdReadyMutGuard`].
451 ///
452 /// [`poll_read_ready`]: method@Self::poll_read_ready
453 /// [`poll_write_ready`]: method@Self::poll_write_ready
454 /// [`poll_write_ready_mut`]: method@Self::poll_write_ready_mut
455 /// [`writable`]: method@Self::readable
456 /// [`Context`]: struct@std::task::Context
457 /// [`Waker`]: struct@std::task::Waker
458 /// [`Waker::wake`]: method@std::task::Waker::wake
459 pub fn poll_write_ready_mut<'a>(
460 &'a mut self,
461 cx: &mut Context<'_>,
462 ) -> Poll<io::Result<AsyncFdReadyMutGuard<'a, T>>> {
463 let event = ready!(self.registration.poll_write_ready(cx))?;
464
465 Poll::Ready(Ok(AsyncFdReadyMutGuard {
466 async_fd: self,
467 event: Some(event),
468 }))
469 }
470
471 /// Waits for any of the requested ready states, returning a
472 /// [`AsyncFdReadyGuard`] that must be dropped to resume
473 /// polling for the requested ready states.
474 ///
475 /// The function may complete without the file descriptor being ready. This is a
476 /// false-positive and attempting an operation will return with
477 /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
478 /// [`Ready`] set, so you should always check the returned value and possibly
479 /// wait again if the requested states are not set.
480 ///
481 /// When an IO operation does return `io::ErrorKind::WouldBlock`, the readiness must be cleared.
482 /// When a combined interest is used, it is important to clear only the readiness
483 /// that is actually observed to block. For instance when the combined
484 /// interest `Interest::READABLE | Interest::WRITABLE` is used, and a read blocks, only
485 /// read readiness should be cleared using the [`AsyncFdReadyGuard::clear_ready_matching`] method:
486 /// `guard.clear_ready_matching(Ready::READABLE)`.
487 /// Also clearing the write readiness in this case would be incorrect. The [`AsyncFdReadyGuard::clear_ready`]
488 /// method clears all readiness flags.
489 ///
490 /// This method takes `&self`, so it is possible to call this method
491 /// concurrently with other methods on this struct. This method only
492 /// provides shared access to the inner IO resource when handling the
493 /// [`AsyncFdReadyGuard`].
494 ///
495 /// # Examples
496 ///
497 /// Concurrently read and write to a [`std::net::TcpStream`] on the same task without
498 /// splitting.
499 ///
500 /// ```no_run
501 /// use std::error::Error;
502 /// use std::io;
503 /// use std::io::{Read, Write};
504 /// use std::net::TcpStream;
505 /// use tokio::io::unix::AsyncFd;
506 /// use tokio::io::{Interest, Ready};
507 ///
508 /// #[tokio::main]
509 /// async fn main() -> Result<(), Box<dyn Error>> {
510 /// let stream = TcpStream::connect("127.0.0.1:8080")?;
511 /// stream.set_nonblocking(true)?;
512 /// // SAFETY: `TcpStream` owns a valid file descriptor and we do not
513 /// // replace or close it while owned by `AsyncFd`.
514 /// let stream = unsafe { AsyncFd::register(stream)? };
515 ///
516 /// loop {
517 /// let mut guard = stream
518 /// .ready(Interest::READABLE | Interest::WRITABLE)
519 /// .await?;
520 ///
521 /// if guard.ready().is_readable() {
522 /// let mut data = vec![0; 1024];
523 /// // Try to read data, this may still fail with `WouldBlock`
524 /// // if the readiness event is a false positive.
525 /// match stream.get_ref().read(&mut data) {
526 /// Ok(n) => {
527 /// println!("read {} bytes", n);
528 /// }
529 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
530 /// // a read has blocked, but a write might still succeed.
531 /// // clear only the read readiness.
532 /// guard.clear_ready_matching(Ready::READABLE);
533 /// continue;
534 /// }
535 /// Err(e) => {
536 /// return Err(e.into());
537 /// }
538 /// }
539 /// }
540 ///
541 /// if guard.ready().is_writable() {
542 /// // Try to write data, this may still fail with `WouldBlock`
543 /// // if the readiness event is a false positive.
544 /// match stream.get_ref().write(b"hello world") {
545 /// Ok(n) => {
546 /// println!("write {} bytes", n);
547 /// }
548 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
549 /// // a write has blocked, but a read might still succeed.
550 /// // clear only the write readiness.
551 /// guard.clear_ready_matching(Ready::WRITABLE);
552 /// continue;
553 /// }
554 /// Err(e) => {
555 /// return Err(e.into());
556 /// }
557 /// }
558 /// }
559 /// }
560 /// }
561 /// ```
562 pub async fn ready(&self, interest: Interest) -> io::Result<AsyncFdReadyGuard<'_, T>> {
563 let event = self.registration.readiness(interest).await?;
564
565 Ok(AsyncFdReadyGuard {
566 async_fd: self,
567 event: Some(event),
568 })
569 }
570
571 /// Waits for any of the requested ready states, returning a
572 /// [`AsyncFdReadyMutGuard`] that must be dropped to resume
573 /// polling for the requested ready states.
574 ///
575 /// The function may complete without the file descriptor being ready. This is a
576 /// false-positive and attempting an operation will return with
577 /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
578 /// [`Ready`] set, so you should always check the returned value and possibly
579 /// wait again if the requested states are not set.
580 ///
581 /// When an IO operation does return `io::ErrorKind::WouldBlock`, the readiness must be cleared.
582 /// When a combined interest is used, it is important to clear only the readiness
583 /// that is actually observed to block. For instance when the combined
584 /// interest `Interest::READABLE | Interest::WRITABLE` is used, and a read blocks, only
585 /// read readiness should be cleared using the [`AsyncFdReadyMutGuard::clear_ready_matching`] method:
586 /// `guard.clear_ready_matching(Ready::READABLE)`.
587 /// Also clearing the write readiness in this case would be incorrect.
588 /// The [`AsyncFdReadyMutGuard::clear_ready`] method clears all readiness flags.
589 ///
590 /// This method takes `&mut self`, so it is possible to access the inner IO
591 /// resource mutably when handling the [`AsyncFdReadyMutGuard`].
592 ///
593 /// # Examples
594 ///
595 /// Concurrently read and write to a [`std::net::TcpStream`] on the same task without
596 /// splitting.
597 ///
598 /// ```no_run
599 /// use std::error::Error;
600 /// use std::io;
601 /// use std::io::{Read, Write};
602 /// use std::net::TcpStream;
603 /// use tokio::io::unix::AsyncFd;
604 /// use tokio::io::{Interest, Ready};
605 ///
606 /// #[tokio::main]
607 /// async fn main() -> Result<(), Box<dyn Error>> {
608 /// let stream = TcpStream::connect("127.0.0.1:8080")?;
609 /// stream.set_nonblocking(true)?;
610 /// // SAFETY: `TcpStream` owns a valid file descriptor and we do not
611 /// // replace or close it while owned by `AsyncFd`.
612 /// let mut stream = unsafe { AsyncFd::register(stream)? };
613 ///
614 /// loop {
615 /// let mut guard = stream
616 /// .ready_mut(Interest::READABLE | Interest::WRITABLE)
617 /// .await?;
618 ///
619 /// if guard.ready().is_readable() {
620 /// let mut data = vec![0; 1024];
621 /// // Try to read data, this may still fail with `WouldBlock`
622 /// // if the readiness event is a false positive.
623 /// match guard.get_inner_mut().read(&mut data) {
624 /// Ok(n) => {
625 /// println!("read {} bytes", n);
626 /// }
627 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
628 /// // a read has blocked, but a write might still succeed.
629 /// // clear only the read readiness.
630 /// guard.clear_ready_matching(Ready::READABLE);
631 /// continue;
632 /// }
633 /// Err(e) => {
634 /// return Err(e.into());
635 /// }
636 /// }
637 /// }
638 ///
639 /// if guard.ready().is_writable() {
640 /// // Try to write data, this may still fail with `WouldBlock`
641 /// // if the readiness event is a false positive.
642 /// match guard.get_inner_mut().write(b"hello world") {
643 /// Ok(n) => {
644 /// println!("write {} bytes", n);
645 /// }
646 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
647 /// // a write has blocked, but a read might still succeed.
648 /// // clear only the write readiness.
649 /// guard.clear_ready_matching(Ready::WRITABLE);
650 /// continue;
651 /// }
652 /// Err(e) => {
653 /// return Err(e.into());
654 /// }
655 /// }
656 /// }
657 /// }
658 /// }
659 /// ```
660 pub async fn ready_mut(
661 &mut self,
662 interest: Interest,
663 ) -> io::Result<AsyncFdReadyMutGuard<'_, T>> {
664 let event = self.registration.readiness(interest).await?;
665
666 Ok(AsyncFdReadyMutGuard {
667 async_fd: self,
668 event: Some(event),
669 })
670 }
671
672 /// Waits for the file descriptor to become readable, returning a
673 /// [`AsyncFdReadyGuard`] that must be dropped to resume read-readiness
674 /// polling.
675 ///
676 /// This method takes `&self`, so it is possible to call this method
677 /// concurrently with other methods on this struct. This method only
678 /// provides shared access to the inner IO resource when handling the
679 /// [`AsyncFdReadyGuard`].
680 ///
681 /// # Cancel safety
682 ///
683 /// This method is cancel safe. Once a readiness event occurs, the method
684 /// will continue to return immediately until the readiness event is
685 /// consumed by an attempt to read or write that fails with `WouldBlock` or
686 /// `Poll::Pending`.
687 #[allow(clippy::needless_lifetimes)] // The lifetime improves rustdoc rendering.
688 pub async fn readable<'a>(&'a self) -> io::Result<AsyncFdReadyGuard<'a, T>> {
689 self.ready(Interest::READABLE).await
690 }
691
692 /// Waits for the file descriptor to become readable, returning a
693 /// [`AsyncFdReadyMutGuard`] that must be dropped to resume read-readiness
694 /// polling.
695 ///
696 /// This method takes `&mut self`, so it is possible to access the inner IO
697 /// resource mutably when handling the [`AsyncFdReadyMutGuard`].
698 ///
699 /// # Cancel safety
700 ///
701 /// This method is cancel safe. Once a readiness event occurs, the method
702 /// will continue to return immediately until the readiness event is
703 /// consumed by an attempt to read or write that fails with `WouldBlock` or
704 /// `Poll::Pending`.
705 #[allow(clippy::needless_lifetimes)] // The lifetime improves rustdoc rendering.
706 pub async fn readable_mut<'a>(&'a mut self) -> io::Result<AsyncFdReadyMutGuard<'a, T>> {
707 self.ready_mut(Interest::READABLE).await
708 }
709
710 /// Waits for the file descriptor to become writable, returning a
711 /// [`AsyncFdReadyGuard`] that must be dropped to resume write-readiness
712 /// polling.
713 ///
714 /// This method takes `&self`, so it is possible to call this method
715 /// concurrently with other methods on this struct. This method only
716 /// provides shared access to the inner IO resource when handling the
717 /// [`AsyncFdReadyGuard`].
718 ///
719 /// # Cancel safety
720 ///
721 /// This method is cancel safe. Once a readiness event occurs, the method
722 /// will continue to return immediately until the readiness event is
723 /// consumed by an attempt to read or write that fails with `WouldBlock` or
724 /// `Poll::Pending`.
725 #[allow(clippy::needless_lifetimes)] // The lifetime improves rustdoc rendering.
726 pub async fn writable<'a>(&'a self) -> io::Result<AsyncFdReadyGuard<'a, T>> {
727 self.ready(Interest::WRITABLE).await
728 }
729
730 /// Waits for the file descriptor to become writable, returning a
731 /// [`AsyncFdReadyMutGuard`] that must be dropped to resume write-readiness
732 /// polling.
733 ///
734 /// This method takes `&mut self`, so it is possible to access the inner IO
735 /// resource mutably when handling the [`AsyncFdReadyMutGuard`].
736 ///
737 /// # Cancel safety
738 ///
739 /// This method is cancel safe. Once a readiness event occurs, the method
740 /// will continue to return immediately until the readiness event is
741 /// consumed by an attempt to read or write that fails with `WouldBlock` or
742 /// `Poll::Pending`.
743 #[allow(clippy::needless_lifetimes)] // The lifetime improves rustdoc rendering.
744 pub async fn writable_mut<'a>(&'a mut self) -> io::Result<AsyncFdReadyMutGuard<'a, T>> {
745 self.ready_mut(Interest::WRITABLE).await
746 }
747
748 /// Reads or writes from the file descriptor using a user-provided IO operation.
749 ///
750 /// The `async_io` method is a convenience utility that waits for the file
751 /// descriptor to become ready, and then executes the provided IO operation.
752 /// Since file descriptors may be marked ready spuriously, the closure will
753 /// be called repeatedly until it returns something other than a
754 /// [`WouldBlock`] error. This is done using the following loop:
755 ///
756 /// ```no_run
757 /// # use std::io::{self, Result};
758 /// # struct Dox<T> { inner: T }
759 /// # impl<T> Dox<T> {
760 /// # async fn writable(&self) -> Result<&Self> {
761 /// # Ok(self)
762 /// # }
763 /// # fn try_io<R>(&self, _: impl FnMut(&T) -> Result<R>) -> Result<Result<R>> {
764 /// # panic!()
765 /// # }
766 /// async fn async_io<R>(&self, mut f: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {
767 /// loop {
768 /// // or `readable` if called with the read interest.
769 /// let guard = self.writable().await?;
770 ///
771 /// match guard.try_io(&mut f) {
772 /// Ok(result) => return result,
773 /// Err(_would_block) => continue,
774 /// }
775 /// }
776 /// }
777 /// # }
778 /// ```
779 ///
780 /// The closure should only return a [`WouldBlock`] error if it has performed
781 /// an IO operation on the file descriptor that failed due to the file descriptor not being
782 /// ready. Returning a [`WouldBlock`] error in any other situation will
783 /// incorrectly clear the readiness flag, which can cause the file descriptor to
784 /// behave incorrectly.
785 ///
786 /// The closure should not perform the IO operation using any of the methods
787 /// defined on the Tokio [`AsyncFd`] type, as this will mess with the
788 /// readiness flag and can cause the file descriptor to behave incorrectly.
789 ///
790 /// This method is not intended to be used with combined interests.
791 /// The closure should perform only one type of IO operation, so it should not
792 /// require more than one ready state. This method may panic or sleep forever
793 /// if it is called with a combined interest.
794 ///
795 /// # Examples
796 ///
797 /// This example sends some bytes on the inner [`std::net::UdpSocket`]. The `async_io`
798 /// method waits for readiness, and retries if the send operation does block. This example
799 /// is equivalent to the one given for [`try_io`].
800 ///
801 /// ```no_run
802 /// use tokio::io::{Interest, unix::AsyncFd};
803 ///
804 /// use std::io;
805 /// use std::net::UdpSocket;
806 ///
807 /// #[tokio::main]
808 /// async fn main() -> io::Result<()> {
809 /// let socket = UdpSocket::bind("0.0.0.0:8080")?;
810 /// socket.set_nonblocking(true)?;
811 /// // SAFETY: `UdpSocket` owns a valid file descriptor and we do not
812 /// // replace or close it while owned by `AsyncFd`.
813 /// let async_fd = unsafe { AsyncFd::register(socket)? };
814 ///
815 /// let written = async_fd
816 /// .async_io(Interest::WRITABLE, |inner| inner.send(&[1, 2]))
817 /// .await?;
818 ///
819 /// println!("wrote {written} bytes");
820 ///
821 /// Ok(())
822 /// }
823 /// ```
824 ///
825 /// [`try_io`]: AsyncFdReadyGuard::try_io
826 /// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
827 pub async fn async_io<R>(
828 &self,
829 interest: Interest,
830 mut f: impl FnMut(&T) -> io::Result<R>,
831 ) -> io::Result<R> {
832 self.registration
833 .async_io(interest, || f(self.get_ref()))
834 .await
835 }
836
837 /// Reads or writes from the file descriptor using a user-provided IO operation.
838 ///
839 /// The behavior is the same as [`async_io`], except that the closure can mutate the inner
840 /// value of the [`AsyncFd`].
841 ///
842 /// [`async_io`]: AsyncFd::async_io
843 pub async fn async_io_mut<R>(
844 &mut self,
845 interest: Interest,
846 mut f: impl FnMut(&mut T) -> io::Result<R>,
847 ) -> io::Result<R> {
848 self.registration
849 .async_io(interest, || f(self.inner.as_mut().unwrap()))
850 .await
851 }
852
853 /// Tries to read or write from the file descriptor using a user-provided IO operation.
854 ///
855 /// If the file descriptor is ready, the provided closure is called. The closure
856 /// should attempt to perform IO operation on the file descriptor by manually
857 /// calling the appropriate syscall. If the operation fails because the
858 /// file descriptor is not actually ready, then the closure should return a
859 /// `WouldBlock` error and the readiness flag is cleared. The return value
860 /// of the closure is then returned by `try_io`.
861 ///
862 /// If the file descriptor is not ready, then the closure is not called
863 /// and a `WouldBlock` error is returned.
864 ///
865 /// The closure should only return a `WouldBlock` error if it has performed
866 /// an IO operation on the file descriptor that failed due to the file descriptor not being
867 /// ready. Returning a `WouldBlock` error in any other situation will
868 /// incorrectly clear the readiness flag, which can cause the file descriptor to
869 /// behave incorrectly.
870 ///
871 /// The closure should not perform the IO operation using any of the methods
872 /// defined on the Tokio `AsyncFd` type, as this will mess with the
873 /// readiness flag and can cause the file descriptor to behave incorrectly.
874 ///
875 /// This method is not intended to be used with combined interests.
876 /// The closure should perform only one type of IO operation, so it should not
877 /// require more than one ready state. This method may panic or sleep forever
878 /// if it is called with a combined interest.
879 pub fn try_io<R>(
880 &self,
881 interest: Interest,
882 f: impl FnOnce(&T) -> io::Result<R>,
883 ) -> io::Result<R> {
884 self.registration
885 .try_io(interest, || f(self.inner.as_ref().unwrap()))
886 }
887
888 /// Tries to read or write from the file descriptor using a user-provided IO operation.
889 ///
890 /// The behavior is the same as [`try_io`], except that the closure can mutate the inner
891 /// value of the [`AsyncFd`].
892 ///
893 /// [`try_io`]: AsyncFd::try_io
894 pub fn try_io_mut<R>(
895 &mut self,
896 interest: Interest,
897 f: impl FnOnce(&mut T) -> io::Result<R>,
898 ) -> io::Result<R> {
899 self.registration
900 .try_io(interest, || f(self.inner.as_mut().unwrap()))
901 }
902
903 /// Deprecated. Use [`AsyncFd::register`] instead. See [#8539] for more information.
904 ///
905 /// [#8539]: https://github.com/tokio-rs/tokio/issues/8539
906 #[inline]
907 #[track_caller]
908 #[deprecated(note = "use `AsyncFd::register` instead")]
909 pub fn new(inner: T) -> io::Result<Self> {
910 unsafe { Ok(Self::register(inner)?) }
911 }
912
913 /// Deprecated. Use [`AsyncFd::register_with_interest`] instead. See [#8539] for more information.
914 ///
915 /// [#8539]: https://github.com/tokio-rs/tokio/issues/8539
916 #[inline]
917 #[track_caller]
918 #[deprecated(note = "use `AsyncFd::register_with_interest` instead")]
919 pub fn with_interest(inner: T, interest: Interest) -> io::Result<Self> {
920 unsafe { Ok(Self::register_with_interest(inner, interest)?) }
921 }
922
923 /// Deprecated. Use [`AsyncFd::register`] instead. See [#8539] for more information.
924 ///
925 /// [#8539]: https://github.com/tokio-rs/tokio/issues/8539
926 #[inline]
927 #[track_caller]
928 #[deprecated(note = "use `AsyncFd::register` instead")]
929 pub fn try_new(inner: T) -> Result<Self, AsyncFdRegisterError<T>> {
930 unsafe { Self::register(inner) }
931 }
932
933 /// Deprecated. Use [`AsyncFd::register_with_interest`] instead. See [#8539] for more information.
934 ///
935 /// [#8539]: https://github.com/tokio-rs/tokio/issues/8539
936 #[inline]
937 #[track_caller]
938 #[deprecated(note = "use `AsyncFd::register_with_interest` instead")]
939 pub fn try_with_interest(
940 inner: T,
941 interest: Interest,
942 ) -> Result<Self, AsyncFdRegisterError<T>> {
943 unsafe { Self::register_with_interest(inner, interest) }
944 }
945}
946
947impl<T: AsRawFd> AsRawFd for AsyncFd<T> {
948 fn as_raw_fd(&self) -> RawFd {
949 self.inner.as_ref().unwrap().as_raw_fd()
950 }
951}
952
953impl<T: AsRawFd> std::os::unix::io::AsFd for AsyncFd<T> {
954 fn as_fd(&self) -> std::os::unix::io::BorrowedFd<'_> {
955 // SAFETY: By the safety requirements of `AsyncFd::register` and
956 // `AsyncFd::register_with_interest`, the file descriptor returned by
957 // `as_raw_fd()` is valid and remains open for the lifetime of `self`.
958 unsafe { std::os::unix::io::BorrowedFd::borrow_raw(self.as_raw_fd()) }
959 }
960}
961
962impl<T: std::fmt::Debug + AsRawFd> std::fmt::Debug for AsyncFd<T> {
963 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
964 f.debug_struct("AsyncFd")
965 .field("inner", &self.inner)
966 .finish()
967 }
968}
969
970impl<T: AsRawFd> Drop for AsyncFd<T> {
971 fn drop(&mut self) {
972 let _ = self.take_inner();
973 }
974}
975
976impl<'a, Inner: AsRawFd> AsyncFdReadyGuard<'a, Inner> {
977 /// Indicates to tokio that the file descriptor is no longer ready. All
978 /// internal readiness flags will be cleared, and tokio will wait for the
979 /// next edge-triggered readiness notification from the OS.
980 ///
981 /// This function is commonly used with guards returned by [`AsyncFd::readable`] and
982 /// [`AsyncFd::writable`].
983 ///
984 /// It is critical that this function not be called unless your code
985 /// _actually observes_ that the file descriptor is _not_ ready. Do not call
986 /// it simply because, for example, a read succeeded; it should be called
987 /// when a read is observed to block.
988 ///
989 /// This method only clears readiness events that happened before the creation of this guard.
990 /// In other words, if the IO resource becomes ready between the creation of the guard and
991 /// this call to `clear_ready`, then the readiness is not actually cleared.
992 pub fn clear_ready(&mut self) {
993 if let Some(event) = self.event.take() {
994 self.async_fd.registration.clear_readiness(event);
995 }
996 }
997
998 /// Indicates to tokio that the file descriptor no longer has a specific readiness.
999 /// The internal readiness flag will be cleared, and tokio will wait for the
1000 /// next edge-triggered readiness notification from the OS.
1001 ///
1002 /// This function is useful in combination with the [`AsyncFd::ready`] method when a
1003 /// combined interest like `Interest::READABLE | Interest::WRITABLE` is used.
1004 ///
1005 /// It is critical that this function not be called unless your code
1006 /// _actually observes_ that the file descriptor is _not_ ready for the provided `Ready`.
1007 /// Do not call it simply because, for example, a read succeeded; it should be called
1008 /// when a read is observed to block. Only clear the specific readiness that is observed to
1009 /// block. For example when a read blocks when using a combined interest,
1010 /// only clear `Ready::READABLE`.
1011 ///
1012 /// This method only clears readiness events that happened before the creation of this guard.
1013 /// In other words, if the IO resource becomes ready between the creation of the guard and
1014 /// this call to `clear_ready_matching`, then the readiness is not actually cleared.
1015 ///
1016 /// # Examples
1017 ///
1018 /// Concurrently read and write to a [`std::net::TcpStream`] on the same task without
1019 /// splitting.
1020 ///
1021 /// ```no_run
1022 /// use std::error::Error;
1023 /// use std::io;
1024 /// use std::io::{Read, Write};
1025 /// use std::net::TcpStream;
1026 /// use tokio::io::unix::AsyncFd;
1027 /// use tokio::io::{Interest, Ready};
1028 ///
1029 /// #[tokio::main]
1030 /// async fn main() -> Result<(), Box<dyn Error>> {
1031 /// let stream = TcpStream::connect("127.0.0.1:8080")?;
1032 /// stream.set_nonblocking(true)?;
1033 /// // SAFETY: `TcpStream` owns a valid file descriptor and we do not
1034 /// // replace or close it while owned by `AsyncFd`.
1035 /// let stream = unsafe { AsyncFd::register(stream)? };
1036 ///
1037 /// loop {
1038 /// let mut guard = stream
1039 /// .ready(Interest::READABLE | Interest::WRITABLE)
1040 /// .await?;
1041 ///
1042 /// if guard.ready().is_readable() {
1043 /// let mut data = vec![0; 1024];
1044 /// // Try to read data, this may still fail with `WouldBlock`
1045 /// // if the readiness event is a false positive.
1046 /// match stream.get_ref().read(&mut data) {
1047 /// Ok(n) => {
1048 /// println!("read {} bytes", n);
1049 /// }
1050 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1051 /// // a read has blocked, but a write might still succeed.
1052 /// // clear only the read readiness.
1053 /// guard.clear_ready_matching(Ready::READABLE);
1054 /// continue;
1055 /// }
1056 /// Err(e) => {
1057 /// return Err(e.into());
1058 /// }
1059 /// }
1060 /// }
1061 ///
1062 /// if guard.ready().is_writable() {
1063 /// // Try to write data, this may still fail with `WouldBlock`
1064 /// // if the readiness event is a false positive.
1065 /// match stream.get_ref().write(b"hello world") {
1066 /// Ok(n) => {
1067 /// println!("write {} bytes", n);
1068 /// }
1069 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1070 /// // a write has blocked, but a read might still succeed.
1071 /// // clear only the write readiness.
1072 /// guard.clear_ready_matching(Ready::WRITABLE);
1073 /// continue;
1074 /// }
1075 /// Err(e) => {
1076 /// return Err(e.into());
1077 /// }
1078 /// }
1079 /// }
1080 /// }
1081 /// }
1082 /// ```
1083 pub fn clear_ready_matching(&mut self, ready: Ready) {
1084 if let Some(mut event) = self.event.take() {
1085 self.async_fd
1086 .registration
1087 .clear_readiness(event.with_ready(ready));
1088
1089 // the event is no longer ready for the readiness that was just cleared
1090 event.ready = event.ready - ready;
1091
1092 if !event.ready.is_empty() {
1093 self.event = Some(event);
1094 }
1095 }
1096 }
1097
1098 /// This method should be invoked when you intentionally want to keep the
1099 /// ready flag asserted.
1100 ///
1101 /// While this function is itself a no-op, it satisfies the `#[must_use]`
1102 /// constraint on the [`AsyncFdReadyGuard`] type.
1103 pub fn retain_ready(&mut self) {
1104 // no-op
1105 }
1106
1107 /// Get the [`Ready`] value associated with this guard.
1108 ///
1109 /// This method will return the empty readiness state if
1110 /// [`AsyncFdReadyGuard::clear_ready`] has been called on
1111 /// the guard.
1112 ///
1113 /// [`Ready`]: crate::io::Ready
1114 pub fn ready(&self) -> Ready {
1115 match &self.event {
1116 Some(event) => event.ready,
1117 None => Ready::EMPTY,
1118 }
1119 }
1120
1121 /// Performs the provided IO operation.
1122 ///
1123 /// If `f` returns a [`WouldBlock`] error, the readiness state associated
1124 /// with this file descriptor is cleared, and the method returns
1125 /// `Err(TryIoError::WouldBlock)`. You will typically need to poll the
1126 /// `AsyncFd` again when this happens.
1127 ///
1128 /// This method helps ensure that the readiness state of the underlying file
1129 /// descriptor remains in sync with the tokio-side readiness state, by
1130 /// clearing the tokio-side state only when a [`WouldBlock`] condition
1131 /// occurs. It is the responsibility of the caller to ensure that `f`
1132 /// returns [`WouldBlock`] only if the file descriptor that originated this
1133 /// `AsyncFdReadyGuard` no longer expresses the readiness state that was queried to
1134 /// create this `AsyncFdReadyGuard`.
1135 ///
1136 /// # Examples
1137 ///
1138 /// This example sends some bytes to the inner [`std::net::UdpSocket`]. Waiting
1139 /// for write-readiness and retrying when the send operation does block are explicit.
1140 /// This example can be written more succinctly using [`AsyncFd::async_io`].
1141 ///
1142 /// ```no_run
1143 /// use tokio::io::unix::AsyncFd;
1144 ///
1145 /// use std::io;
1146 /// use std::net::UdpSocket;
1147 ///
1148 /// #[tokio::main]
1149 /// async fn main() -> io::Result<()> {
1150 /// let socket = UdpSocket::bind("0.0.0.0:8080")?;
1151 /// socket.set_nonblocking(true)?;
1152 /// // SAFETY: `UdpSocket` owns a valid file descriptor and we do not
1153 /// // replace or close it while owned by `AsyncFd`.
1154 /// let async_fd = unsafe { AsyncFd::register(socket)? };
1155 ///
1156 /// let written = loop {
1157 /// let mut guard = async_fd.writable().await?;
1158 /// match guard.try_io(|inner| inner.get_ref().send(&[1, 2])) {
1159 /// Ok(result) => {
1160 /// break result?;
1161 /// }
1162 /// Err(_would_block) => {
1163 /// // try_io already cleared the file descriptor's readiness state
1164 /// continue;
1165 /// }
1166 /// }
1167 /// };
1168 ///
1169 /// println!("wrote {written} bytes");
1170 ///
1171 /// Ok(())
1172 /// }
1173 /// ```
1174 ///
1175 /// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
1176 // Alias for old name in 0.x
1177 #[cfg_attr(docsrs, doc(alias = "with_io"))]
1178 pub fn try_io<R>(
1179 &mut self,
1180 f: impl FnOnce(&'a AsyncFd<Inner>) -> io::Result<R>,
1181 ) -> Result<io::Result<R>, TryIoError> {
1182 let result = f(self.async_fd);
1183
1184 match result {
1185 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
1186 self.clear_ready();
1187 Err(TryIoError(()))
1188 }
1189 result => Ok(result),
1190 }
1191 }
1192
1193 /// Returns a shared reference to the inner [`AsyncFd`].
1194 pub fn get_ref(&self) -> &'a AsyncFd<Inner> {
1195 self.async_fd
1196 }
1197
1198 /// Returns a shared reference to the backing object of the inner [`AsyncFd`].
1199 pub fn get_inner(&self) -> &'a Inner {
1200 self.get_ref().get_ref()
1201 }
1202}
1203
1204impl<'a, Inner: AsRawFd> AsyncFdReadyMutGuard<'a, Inner> {
1205 /// Indicates to tokio that the file descriptor is no longer ready. All
1206 /// internal readiness flags will be cleared, and tokio will wait for the
1207 /// next edge-triggered readiness notification from the OS.
1208 ///
1209 /// This function is commonly used with guards returned by [`AsyncFd::readable_mut`] and
1210 /// [`AsyncFd::writable_mut`].
1211 ///
1212 /// It is critical that this function not be called unless your code
1213 /// _actually observes_ that the file descriptor is _not_ ready. Do not call
1214 /// it simply because, for example, a read succeeded; it should be called
1215 /// when a read is observed to block.
1216 ///
1217 /// This method only clears readiness events that happened before the creation of this guard.
1218 /// In other words, if the IO resource becomes ready between the creation of the guard and
1219 /// this call to `clear_ready`, then the readiness is not actually cleared.
1220 pub fn clear_ready(&mut self) {
1221 if let Some(event) = self.event.take() {
1222 self.async_fd.registration.clear_readiness(event);
1223 }
1224 }
1225
1226 /// Indicates to tokio that the file descriptor no longer has a specific readiness.
1227 /// The internal readiness flag will be cleared, and tokio will wait for the
1228 /// next edge-triggered readiness notification from the OS.
1229 ///
1230 /// This function is useful in combination with the [`AsyncFd::ready_mut`] method when a
1231 /// combined interest like `Interest::READABLE | Interest::WRITABLE` is used.
1232 ///
1233 /// It is critical that this function not be called unless your code
1234 /// _actually observes_ that the file descriptor is _not_ ready for the provided `Ready`.
1235 /// Do not call it simply because, for example, a read succeeded; it should be called
1236 /// when a read is observed to block. Only clear the specific readiness that is observed to
1237 /// block. For example when a read blocks when using a combined interest,
1238 /// only clear `Ready::READABLE`.
1239 ///
1240 /// This method only clears readiness events that happened before the creation of this guard.
1241 /// In other words, if the IO resource becomes ready between the creation of the guard and
1242 /// this call to `clear_ready_matching`, then the readiness is not actually cleared.
1243 ///
1244 /// # Examples
1245 ///
1246 /// Concurrently read and write to a [`std::net::TcpStream`] on the same task without
1247 /// splitting.
1248 ///
1249 /// ```no_run
1250 /// use std::error::Error;
1251 /// use std::io;
1252 /// use std::io::{Read, Write};
1253 /// use std::net::TcpStream;
1254 /// use tokio::io::unix::AsyncFd;
1255 /// use tokio::io::{Interest, Ready};
1256 ///
1257 /// #[tokio::main]
1258 /// async fn main() -> Result<(), Box<dyn Error>> {
1259 /// let stream = TcpStream::connect("127.0.0.1:8080")?;
1260 /// stream.set_nonblocking(true)?;
1261 /// // SAFETY: `TcpStream` owns a valid file descriptor and we do not
1262 /// // replace or close it while owned by `AsyncFd`.
1263 /// let mut stream = unsafe { AsyncFd::register(stream)? };
1264 ///
1265 /// loop {
1266 /// let mut guard = stream
1267 /// .ready_mut(Interest::READABLE | Interest::WRITABLE)
1268 /// .await?;
1269 ///
1270 /// if guard.ready().is_readable() {
1271 /// let mut data = vec![0; 1024];
1272 /// // Try to read data, this may still fail with `WouldBlock`
1273 /// // if the readiness event is a false positive.
1274 /// match guard.get_inner_mut().read(&mut data) {
1275 /// Ok(n) => {
1276 /// println!("read {} bytes", n);
1277 /// }
1278 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1279 /// // a read has blocked, but a write might still succeed.
1280 /// // clear only the read readiness.
1281 /// guard.clear_ready_matching(Ready::READABLE);
1282 /// continue;
1283 /// }
1284 /// Err(e) => {
1285 /// return Err(e.into());
1286 /// }
1287 /// }
1288 /// }
1289 ///
1290 /// if guard.ready().is_writable() {
1291 /// // Try to write data, this may still fail with `WouldBlock`
1292 /// // if the readiness event is a false positive.
1293 /// match guard.get_inner_mut().write(b"hello world") {
1294 /// Ok(n) => {
1295 /// println!("write {} bytes", n);
1296 /// }
1297 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1298 /// // a write has blocked, but a read might still succeed.
1299 /// // clear only the write readiness.
1300 /// guard.clear_ready_matching(Ready::WRITABLE);
1301 /// continue;
1302 /// }
1303 /// Err(e) => {
1304 /// return Err(e.into());
1305 /// }
1306 /// }
1307 /// }
1308 /// }
1309 /// }
1310 /// ```
1311 pub fn clear_ready_matching(&mut self, ready: Ready) {
1312 if let Some(mut event) = self.event.take() {
1313 self.async_fd
1314 .registration
1315 .clear_readiness(event.with_ready(ready));
1316
1317 // the event is no longer ready for the readiness that was just cleared
1318 event.ready = event.ready - ready;
1319
1320 if !event.ready.is_empty() {
1321 self.event = Some(event);
1322 }
1323 }
1324 }
1325
1326 /// This method should be invoked when you intentionally want to keep the
1327 /// ready flag asserted.
1328 ///
1329 /// While this function is itself a no-op, it satisfies the `#[must_use]`
1330 /// constraint on the [`AsyncFdReadyGuard`] type.
1331 pub fn retain_ready(&mut self) {
1332 // no-op
1333 }
1334
1335 /// Get the [`Ready`] value associated with this guard.
1336 ///
1337 /// This method will return the empty readiness state if
1338 /// [`AsyncFdReadyGuard::clear_ready`] has been called on
1339 /// the guard.
1340 ///
1341 /// [`Ready`]: super::Ready
1342 pub fn ready(&self) -> Ready {
1343 match &self.event {
1344 Some(event) => event.ready,
1345 None => Ready::EMPTY,
1346 }
1347 }
1348
1349 /// Performs the provided IO operation.
1350 ///
1351 /// If `f` returns a [`WouldBlock`] error, the readiness state associated
1352 /// with this file descriptor is cleared, and the method returns
1353 /// `Err(TryIoError::WouldBlock)`. You will typically need to poll the
1354 /// `AsyncFd` again when this happens.
1355 ///
1356 /// This method helps ensure that the readiness state of the underlying file
1357 /// descriptor remains in sync with the tokio-side readiness state, by
1358 /// clearing the tokio-side state only when a [`WouldBlock`] condition
1359 /// occurs. It is the responsibility of the caller to ensure that `f`
1360 /// returns [`WouldBlock`] only if the file descriptor that originated this
1361 /// `AsyncFdReadyGuard` no longer expresses the readiness state that was queried to
1362 /// create this `AsyncFdReadyGuard`.
1363 ///
1364 /// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
1365 pub fn try_io<R>(
1366 &mut self,
1367 f: impl FnOnce(&mut AsyncFd<Inner>) -> io::Result<R>,
1368 ) -> Result<io::Result<R>, TryIoError> {
1369 let result = f(self.async_fd);
1370
1371 match result {
1372 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
1373 self.clear_ready();
1374 Err(TryIoError(()))
1375 }
1376 result => Ok(result),
1377 }
1378 }
1379
1380 /// Returns a shared reference to the inner [`AsyncFd`].
1381 pub fn get_ref(&self) -> &AsyncFd<Inner> {
1382 self.async_fd
1383 }
1384
1385 /// Returns a mutable reference to the inner [`AsyncFd`].
1386 pub fn get_mut(&mut self) -> &mut AsyncFd<Inner> {
1387 self.async_fd
1388 }
1389
1390 /// Returns a shared reference to the backing object of the inner [`AsyncFd`].
1391 pub fn get_inner(&self) -> &Inner {
1392 self.get_ref().get_ref()
1393 }
1394
1395 /// Returns a mutable reference to the backing object of the inner [`AsyncFd`].
1396 ///
1397 /// This may be used to interact with the underlying file. Be aware that this
1398 /// method must not be used to exchange the underlying IO resource for a
1399 /// different one. Doing so is a violation of the safety requirements on
1400 /// [`AsyncFd::register`].
1401 pub fn get_inner_mut(&mut self) -> &mut Inner {
1402 self.get_mut().get_mut()
1403 }
1404}
1405
1406impl<'a, T: std::fmt::Debug + AsRawFd> std::fmt::Debug for AsyncFdReadyGuard<'a, T> {
1407 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1408 f.debug_struct("ReadyGuard")
1409 .field("async_fd", &self.async_fd)
1410 .finish()
1411 }
1412}
1413
1414impl<'a, T: std::fmt::Debug + AsRawFd> std::fmt::Debug for AsyncFdReadyMutGuard<'a, T> {
1415 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1416 f.debug_struct("MutReadyGuard")
1417 .field("async_fd", &self.async_fd)
1418 .finish()
1419 }
1420}
1421
1422/// The error type returned by [`try_io`].
1423///
1424/// This error indicates that the IO resource returned a [`WouldBlock`] error.
1425///
1426/// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
1427/// [`try_io`]: method@AsyncFdReadyGuard::try_io
1428#[derive(Debug)]
1429pub struct TryIoError(());
1430
1431/// Error returned by [`register`] or [`register_with_interest`].
1432///
1433/// [`register`]: AsyncFd::register
1434/// [`register_with_interest`]: AsyncFd::register_with_interest
1435pub struct AsyncFdRegisterError<T> {
1436 inner: T,
1437 cause: io::Error,
1438}
1439
1440/// Deprecated. Use [`AsyncFdRegisterError`] instead.
1441#[doc(hidden)]
1442#[deprecated(note = "use `AsyncFdRegisterError` instead")]
1443pub type AsyncFdTryNewError<T> = AsyncFdRegisterError<T>;
1444
1445impl<T> AsyncFdRegisterError<T> {
1446 /// Returns the original object passed to [`register`] or [`register_with_interest`]
1447 /// alongside the error that caused these functions to fail.
1448 ///
1449 /// [`register`]: AsyncFd::register
1450 /// [`register_with_interest`]: AsyncFd::register_with_interest
1451 pub fn into_parts(self) -> (T, io::Error) {
1452 (self.inner, self.cause)
1453 }
1454}
1455
1456impl<T> fmt::Display for AsyncFdRegisterError<T> {
1457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458 fmt::Display::fmt(&self.cause, f)
1459 }
1460}
1461
1462impl<T> fmt::Debug for AsyncFdRegisterError<T> {
1463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1464 fmt::Debug::fmt(&self.cause, f)
1465 }
1466}
1467
1468impl<T> Error for AsyncFdRegisterError<T> {
1469 fn source(&self) -> Option<&(dyn Error + 'static)> {
1470 Some(&self.cause)
1471 }
1472}
1473
1474impl<T> From<AsyncFdRegisterError<T>> for io::Error {
1475 fn from(value: AsyncFdRegisterError<T>) -> Self {
1476 value.cause
1477 }
1478}