async_io/lib.rs
1//! Async I/O and timers.
2//!
3//! This crate provides two tools:
4//!
5//! * [`Async`], an adapter for standard networking types (and [many other] types) to use in
6//! async programs.
7//! * [`Timer`], a future or stream that emits timed events.
8//!
9//! For concrete async networking types built on top of this crate, see [`async-net`].
10//!
11//! [many other]: https://github.com/smol-rs/async-io/tree/master/examples
12//! [`async-net`]: https://docs.rs/async-net
13//!
14//! # Implementation
15//!
16//! The first time [`Async`] or [`Timer`] is used, a thread named "async-io" will be spawned.
17//! The purpose of this thread is to wait for I/O events reported by the operating system, and then
18//! wake appropriate futures blocked on I/O or timers when they can be resumed.
19//!
20//! To wait for the next I/O event, the "async-io" thread uses [epoll] on Linux/Android/illumos,
21//! [kqueue] on macOS/iOS/BSD, and [event ports] on illumos/Solaris. That
22//! functionality is provided by the [`polling`] crate.
23//!
24//! However, note that you can also process I/O events and wake futures on any thread using the
25//! [`block_on()`] function. The "async-io" thread is therefore just a fallback mechanism
26//! processing I/O events in case no other threads are.
27//!
28//! [epoll]: https://en.wikipedia.org/wiki/Epoll
29//! [kqueue]: https://en.wikipedia.org/wiki/Kqueue
30//! [event ports]: https://illumos.org/man/port_create
31//! [`polling`]: https://docs.rs/polling
32//!
33//! # Examples
34//!
35//! Connect to `example.com:80`, or time out after 10 seconds.
36//!
37//! ```
38//! use async_io::{Async, Timer};
39//! use futures_lite::{future::FutureExt, io};
40//!
41//! use std::net::{TcpStream, ToSocketAddrs};
42//! use std::time::Duration;
43//!
44//! # futures_lite::future::block_on(async {
45//! let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
46//!
47//! let stream = Async::<TcpStream>::connect(addr).or(async {
48//! Timer::after(Duration::from_secs(10)).await;
49//! Err(io::ErrorKind::TimedOut.into())
50//! })
51//! .await?;
52//! # std::io::Result::Ok(()) });
53//! ```
54
55#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
56#![doc(
57 html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
58)]
59#![doc(
60 html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
61)]
62
63use std::future::{poll_fn, Future};
64use std::io::{self, IoSlice, IoSliceMut, Read, Write};
65use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket};
66use std::pin::{pin, Pin};
67use std::sync::Arc;
68use std::task::{ready, Context, Poll, Waker};
69use std::time::{Duration, Instant};
70
71#[cfg(unix)]
72use std::{
73 os::unix::io::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd},
74 os::unix::net::{SocketAddr as UnixSocketAddr, UnixDatagram, UnixListener, UnixStream},
75 path::Path,
76};
77
78use futures_io::{AsyncRead, AsyncWrite};
79use futures_lite::stream::{self, Stream};
80
81use rustix::io as rio;
82use rustix::net as rn;
83use rustix::net::addr::SocketAddrArg;
84
85use crate::reactor::{Reactor, Registration, Source};
86
87mod driver;
88mod reactor;
89
90pub mod os;
91
92pub use driver::block_on;
93pub use reactor::{Readable, ReadableOwned, Writable, WritableOwned};
94
95/// A future or stream that emits timed events.
96///
97/// Timers are futures that output a single [`Instant`] when they fire.
98///
99/// Timers are also streams that can output [`Instant`]s periodically.
100///
101/// # Precision
102///
103/// There is a limit on the maximum precision that a `Timer` can provide. This limit is
104/// dependent on the current platform. Because of this limit, the timer may sleep for longer than the
105/// requested duration. It will never sleep for less.
106///
107/// # Examples
108///
109/// Sleep for 1 second:
110///
111/// ```
112/// use async_io::Timer;
113/// use std::time::Duration;
114///
115/// # futures_lite::future::block_on(async {
116/// Timer::after(Duration::from_secs(1)).await;
117/// # });
118/// ```
119///
120/// Timeout after 1 second:
121///
122/// ```
123/// use async_io::Timer;
124/// use futures_lite::FutureExt;
125/// use std::time::Duration;
126///
127/// # futures_lite::future::block_on(async {
128/// let addrs = async_net::resolve("google.com:80")
129/// .or(async {
130/// Timer::after(Duration::from_secs(1)).await;
131/// Err(std::io::ErrorKind::TimedOut.into())
132/// })
133/// .await?;
134/// # std::io::Result::Ok(()) });
135/// ```
136#[doc(alias = "sleep")]
137#[doc(alias = "timeout")]
138#[derive(Debug)]
139pub struct Timer {
140 /// This timer's ID and last waker that polled it.
141 ///
142 /// When this field is set to `None`, this timer is not registered in the reactor.
143 id_and_waker: Option<(usize, Waker)>,
144
145 /// The next instant at which this timer fires.
146 ///
147 /// If this timer is a blank timer, this value is None. If the timer
148 /// must be set, this value contains the next instant at which the
149 /// timer must fire.
150 when: Option<Instant>,
151
152 /// The period.
153 period: Duration,
154}
155
156impl Timer {
157 /// Creates a timer that will never fire.
158 ///
159 /// # Examples
160 ///
161 /// This function may also be useful for creating a function with an optional timeout.
162 ///
163 /// ```
164 /// # futures_lite::future::block_on(async {
165 /// use async_io::Timer;
166 /// use futures_lite::prelude::*;
167 /// use std::time::Duration;
168 ///
169 /// async fn run_with_timeout(timeout: Option<Duration>) {
170 /// let timer = timeout
171 /// .map(|timeout| Timer::after(timeout))
172 /// .unwrap_or_else(Timer::never);
173 ///
174 /// run_lengthy_operation().or(timer).await;
175 /// }
176 /// # // Note that since a Timer as a Future returns an Instant,
177 /// # // this function needs to return an Instant to be used
178 /// # // in "or".
179 /// # async fn run_lengthy_operation() -> std::time::Instant {
180 /// # std::time::Instant::now()
181 /// # }
182 ///
183 /// // Times out after 5 seconds.
184 /// run_with_timeout(Some(Duration::from_secs(5))).await;
185 /// // Does not time out.
186 /// run_with_timeout(None).await;
187 /// # });
188 /// ```
189 pub fn never() -> Timer {
190 Timer {
191 id_and_waker: None,
192 when: None,
193 period: Duration::MAX,
194 }
195 }
196
197 /// Creates a timer that emits an event once after the given duration of time.
198 ///
199 /// # Examples
200 ///
201 /// ```
202 /// use async_io::Timer;
203 /// use std::time::Duration;
204 ///
205 /// # futures_lite::future::block_on(async {
206 /// Timer::after(Duration::from_secs(1)).await;
207 /// # });
208 /// ```
209 pub fn after(duration: Duration) -> Timer {
210 Instant::now()
211 .checked_add(duration)
212 .map_or_else(Timer::never, Timer::at)
213 }
214
215 /// Creates a timer that emits an event once at the given time instant.
216 ///
217 /// # Examples
218 ///
219 /// ```
220 /// use async_io::Timer;
221 /// use std::time::{Duration, Instant};
222 ///
223 /// # futures_lite::future::block_on(async {
224 /// let now = Instant::now();
225 /// let when = now + Duration::from_secs(1);
226 /// Timer::at(when).await;
227 /// # });
228 /// ```
229 pub fn at(instant: Instant) -> Timer {
230 Timer::interval_at(instant, Duration::MAX)
231 }
232
233 /// Creates a timer that emits events periodically.
234 ///
235 /// # Examples
236 ///
237 /// ```
238 /// use async_io::Timer;
239 /// use futures_lite::StreamExt;
240 /// use std::time::{Duration, Instant};
241 ///
242 /// # futures_lite::future::block_on(async {
243 /// let period = Duration::from_secs(1);
244 /// Timer::interval(period).next().await;
245 /// # });
246 /// ```
247 pub fn interval(period: Duration) -> Timer {
248 Instant::now()
249 .checked_add(period)
250 .map_or_else(Timer::never, |at| Timer::interval_at(at, period))
251 }
252
253 /// Creates a timer that emits events periodically, starting at `start`.
254 ///
255 /// # Examples
256 ///
257 /// ```
258 /// use async_io::Timer;
259 /// use futures_lite::StreamExt;
260 /// use std::time::{Duration, Instant};
261 ///
262 /// # futures_lite::future::block_on(async {
263 /// let start = Instant::now();
264 /// let period = Duration::from_secs(1);
265 /// Timer::interval_at(start, period).next().await;
266 /// # });
267 /// ```
268 pub fn interval_at(start: Instant, period: Duration) -> Timer {
269 Timer {
270 id_and_waker: None,
271 when: Some(start),
272 period,
273 }
274 }
275
276 /// Indicates whether or not this timer will ever fire.
277 ///
278 /// [`never()`] will never fire, and timers created with [`after()`] or [`at()`] will fire
279 /// if the duration is not too large.
280 ///
281 /// [`never()`]: Timer::never()
282 /// [`after()`]: Timer::after()
283 /// [`at()`]: Timer::at()
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// # futures_lite::future::block_on(async {
289 /// use async_io::Timer;
290 /// use futures_lite::prelude::*;
291 /// use std::time::Duration;
292 ///
293 /// // `never` will never fire.
294 /// assert!(!Timer::never().will_fire());
295 ///
296 /// // `after` will fire if the duration is not too large.
297 /// assert!(Timer::after(Duration::from_secs(1)).will_fire());
298 /// assert!(!Timer::after(Duration::MAX).will_fire());
299 ///
300 /// // However, once an `after` timer has fired, it will never fire again.
301 /// let mut t = Timer::after(Duration::from_secs(1));
302 /// assert!(t.will_fire());
303 /// (&mut t).await;
304 /// assert!(!t.will_fire());
305 ///
306 /// // Interval timers will fire periodically.
307 /// let mut t = Timer::interval(Duration::from_secs(1));
308 /// assert!(t.will_fire());
309 /// t.next().await;
310 /// assert!(t.will_fire());
311 /// # });
312 /// ```
313 #[inline]
314 pub fn will_fire(&self) -> bool {
315 self.when.is_some()
316 }
317
318 /// Sets the timer to emit an event once after the given duration of time.
319 ///
320 /// Note that resetting a timer is different from creating a new timer because
321 /// [`set_after()`][`Timer::set_after()`] does not remove the waker associated with the task
322 /// that is polling the timer.
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// use async_io::Timer;
328 /// use std::time::Duration;
329 ///
330 /// # futures_lite::future::block_on(async {
331 /// let mut t = Timer::after(Duration::from_secs(1));
332 /// t.set_after(Duration::from_millis(100));
333 /// # });
334 /// ```
335 pub fn set_after(&mut self, duration: Duration) {
336 match Instant::now().checked_add(duration) {
337 Some(instant) => self.set_at(instant),
338 None => {
339 // Overflow to never going off.
340 self.clear();
341 }
342 }
343 }
344
345 /// Sets the timer to emit an event once at the given time instant.
346 ///
347 /// Note that resetting a timer is different from creating a new timer because
348 /// [`set_at()`][`Timer::set_at()`] does not remove the waker associated with the task
349 /// that is polling the timer.
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// use async_io::Timer;
355 /// use std::time::{Duration, Instant};
356 ///
357 /// # futures_lite::future::block_on(async {
358 /// let mut t = Timer::after(Duration::from_secs(1));
359 ///
360 /// let now = Instant::now();
361 /// let when = now + Duration::from_secs(1);
362 /// t.set_at(when);
363 /// # });
364 /// ```
365 pub fn set_at(&mut self, instant: Instant) {
366 self.clear();
367
368 // Update the timeout.
369 self.when = Some(instant);
370
371 if let Some((id, waker)) = self.id_and_waker.as_mut() {
372 // Re-register the timer with the new timeout.
373 *id = Reactor::get().insert_timer(instant, waker);
374 }
375 }
376
377 /// Sets the timer to emit events periodically.
378 ///
379 /// Note that resetting a timer is different from creating a new timer because
380 /// [`set_interval()`][`Timer::set_interval()`] does not remove the waker associated with the
381 /// task that is polling the timer.
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use async_io::Timer;
387 /// use futures_lite::StreamExt;
388 /// use std::time::{Duration, Instant};
389 ///
390 /// # futures_lite::future::block_on(async {
391 /// let mut t = Timer::after(Duration::from_secs(1));
392 ///
393 /// let period = Duration::from_secs(2);
394 /// t.set_interval(period);
395 /// # });
396 /// ```
397 pub fn set_interval(&mut self, period: Duration) {
398 match Instant::now().checked_add(period) {
399 Some(instant) => self.set_interval_at(instant, period),
400 None => {
401 // Overflow to never going off.
402 self.clear();
403 }
404 }
405 }
406
407 /// Sets the timer to emit events periodically, starting at `start`.
408 ///
409 /// Note that resetting a timer is different from creating a new timer because
410 /// [`set_interval_at()`][`Timer::set_interval_at()`] does not remove the waker associated with
411 /// the task that is polling the timer.
412 ///
413 /// # Examples
414 ///
415 /// ```
416 /// use async_io::Timer;
417 /// use futures_lite::StreamExt;
418 /// use std::time::{Duration, Instant};
419 ///
420 /// # futures_lite::future::block_on(async {
421 /// let mut t = Timer::after(Duration::from_secs(1));
422 ///
423 /// let start = Instant::now();
424 /// let period = Duration::from_secs(2);
425 /// t.set_interval_at(start, period);
426 /// # });
427 /// ```
428 pub fn set_interval_at(&mut self, start: Instant, period: Duration) {
429 self.clear();
430
431 self.when = Some(start);
432 self.period = period;
433
434 if let Some((id, waker)) = self.id_and_waker.as_mut() {
435 // Re-register the timer with the new timeout.
436 *id = Reactor::get().insert_timer(start, waker);
437 }
438 }
439
440 /// Clear any timeouts set on this timer. It will never fire again until a new interval or instant is set.
441 pub fn clear(&mut self) {
442 if let (Some(when), Some((id, _))) = (self.when, self.id_and_waker.as_ref()) {
443 // Deregister the timer from the reactor.
444 Reactor::get().remove_timer(when, *id);
445 }
446 self.when = None;
447 }
448}
449
450impl Drop for Timer {
451 fn drop(&mut self) {
452 if let (Some(when), Some((id, _))) = (self.when, self.id_and_waker.take()) {
453 // Deregister the timer from the reactor.
454 Reactor::get().remove_timer(when, id);
455 }
456 }
457}
458
459impl Future for Timer {
460 type Output = Instant;
461
462 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
463 match self.poll_next(cx) {
464 Poll::Ready(Some(when)) => Poll::Ready(when),
465 Poll::Pending => Poll::Pending,
466 Poll::Ready(None) => unreachable!(),
467 }
468 }
469}
470
471impl Stream for Timer {
472 type Item = Instant;
473
474 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
475 let this = self.get_mut();
476
477 if let Some(ref mut when) = this.when {
478 // Check if the timer has already fired.
479 if Instant::now() >= *when {
480 if let Some((id, _)) = this.id_and_waker.take() {
481 // Deregister the timer from the reactor.
482 Reactor::get().remove_timer(*when, id);
483 }
484 let result_time = *when;
485 if let Some(next) = (*when).checked_add(this.period) {
486 *when = next;
487 // Register the timer in the reactor.
488 let id = Reactor::get().insert_timer(next, cx.waker());
489 this.id_and_waker = Some((id, cx.waker().clone()));
490 } else {
491 this.when = None;
492 }
493 return Poll::Ready(Some(result_time));
494 } else {
495 match &this.id_and_waker {
496 None => {
497 // Register the timer in the reactor.
498 let id = Reactor::get().insert_timer(*when, cx.waker());
499 this.id_and_waker = Some((id, cx.waker().clone()));
500 }
501 Some((id, w)) if !w.will_wake(cx.waker()) => {
502 // Deregister the timer from the reactor to remove the old waker.
503 Reactor::get().remove_timer(*when, *id);
504
505 // Register the timer in the reactor with the new waker.
506 let id = Reactor::get().insert_timer(*when, cx.waker());
507 this.id_and_waker = Some((id, cx.waker().clone()));
508 }
509 Some(_) => {}
510 }
511 }
512 }
513
514 Poll::Pending
515 }
516}
517
518/// Async adapter for I/O types.
519///
520/// This type puts an I/O handle into non-blocking mode, registers it in
521/// [epoll]/[kqueue]/[event ports], and then provides an async interface for it.
522///
523/// [epoll]: https://en.wikipedia.org/wiki/Epoll
524/// [kqueue]: https://en.wikipedia.org/wiki/Kqueue
525/// [event ports]: https://illumos.org/man/port_create
526///
527/// # Caveats
528///
529/// [`Async`] is a low-level primitive, and as such it comes with some caveats.
530///
531/// For higher-level primitives built on top of [`Async`], look into [`async-net`] or
532/// [`async-process`] (on Unix).
533///
534/// The most notable caveat is that it is unsafe to access the inner I/O source mutably
535/// using this primitive. Traits likes [`AsyncRead`] and [`AsyncWrite`] are not implemented by
536/// default unless it is guaranteed that the resource won't be invalidated by reading or writing.
537/// See the [`IoSafe`] trait for more information.
538///
539/// [`async-net`]: https://github.com/smol-rs/async-net
540/// [`async-process`]: https://github.com/smol-rs/async-process
541/// [`AsyncRead`]: https://docs.rs/futures-io/latest/futures_io/trait.AsyncRead.html
542/// [`AsyncWrite`]: https://docs.rs/futures-io/latest/futures_io/trait.AsyncWrite.html
543///
544/// ### Supported types
545///
546/// [`Async`] supports all networking types, as well as some OS-specific file descriptors like
547/// [timerfd] and [inotify].
548///
549/// However, do not use [`Async`] with types like [`File`][`std::fs::File`],
550/// [`Stdin`][`std::io::Stdin`], [`Stdout`][`std::io::Stdout`], or [`Stderr`][`std::io::Stderr`]
551/// because all operating systems have issues with them when put in non-blocking mode.
552///
553/// [timerfd]: https://github.com/smol-rs/async-io/blob/master/examples/linux-timerfd.rs
554/// [inotify]: https://github.com/smol-rs/async-io/blob/master/examples/linux-inotify.rs
555///
556/// ### Concurrent I/O
557///
558/// Note that [`&Async<T>`][`Async`] implements [`AsyncRead`] and [`AsyncWrite`] if `&T`
559/// implements those traits, which means tasks can concurrently read and write using shared
560/// references.
561///
562/// But there is a catch: only one task can read a time, and only one task can write at a time. It
563/// is okay to have two tasks where one is reading and the other is writing at the same time, but
564/// it is not okay to have two tasks reading at the same time or writing at the same time. If you
565/// try to do that, conflicting tasks will just keep waking each other in turn, thus wasting CPU
566/// time.
567///
568/// Besides [`AsyncRead`] and [`AsyncWrite`], this caveat also applies to
569/// [`poll_readable()`][`Async::poll_readable()`] and
570/// [`poll_writable()`][`Async::poll_writable()`].
571///
572/// However, any number of tasks can be concurrently calling other methods like
573/// [`readable()`][`Async::readable()`] or [`read_with()`][`Async::read_with()`].
574///
575/// ### Closing
576///
577/// Closing the write side of [`Async`] with [`close()`][`futures_lite::AsyncWriteExt::close()`]
578/// simply flushes. If you want to shutdown a TCP or Unix socket, use
579/// [`Shutdown`][`std::net::Shutdown`].
580///
581/// # Examples
582///
583/// Connect to a server and echo incoming messages back to the server:
584///
585/// ```no_run
586/// use async_io::Async;
587/// use futures_lite::io;
588/// use std::net::TcpStream;
589///
590/// # futures_lite::future::block_on(async {
591/// // Connect to a local server.
592/// let stream = Async::<TcpStream>::connect(([127, 0, 0, 1], 8000)).await?;
593///
594/// // Echo all messages from the read side of the stream into the write side.
595/// io::copy(&stream, &stream).await?;
596/// # std::io::Result::Ok(()) });
597/// ```
598///
599/// You can use either predefined async methods or wrap blocking I/O operations in
600/// [`Async::read_with()`], [`Async::read_with_mut()`], [`Async::write_with()`], and
601/// [`Async::write_with_mut()`]:
602///
603/// ```no_run
604/// use async_io::Async;
605/// use std::net::TcpListener;
606///
607/// # futures_lite::future::block_on(async {
608/// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
609///
610/// // These two lines are equivalent:
611/// let (stream, addr) = listener.accept().await?;
612/// let (stream, addr) = listener.read_with(|inner| inner.accept()).await?;
613/// # std::io::Result::Ok(()) });
614/// ```
615#[derive(Debug)]
616pub struct Async<T> {
617 /// A source registered in the reactor.
618 source: Arc<Source>,
619
620 /// The inner I/O handle.
621 io: Option<T>,
622}
623
624impl<T> Unpin for Async<T> {}
625
626#[cfg(unix)]
627impl<T: AsFd> Async<T> {
628 /// Creates an async I/O handle.
629 ///
630 /// This method will put the handle in non-blocking mode and register it in
631 /// [epoll]/[kqueue]/[event ports].
632 ///
633 /// The handle must implement `AsFd`.
634 ///
635 /// [epoll]: https://en.wikipedia.org/wiki/Epoll
636 /// [kqueue]: https://en.wikipedia.org/wiki/Kqueue
637 /// [event ports]: https://illumos.org/man/port_create
638 ///
639 /// # Examples
640 ///
641 /// ```
642 /// use async_io::Async;
643 /// use std::net::{SocketAddr, TcpListener};
644 ///
645 /// # futures_lite::future::block_on(async {
646 /// let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))?;
647 /// let listener = Async::new(listener)?;
648 /// # std::io::Result::Ok(()) });
649 /// ```
650 pub fn new(io: T) -> io::Result<Async<T>> {
651 // Put the file descriptor in non-blocking mode.
652 set_nonblocking(io.as_fd())?;
653
654 Self::new_nonblocking(io)
655 }
656
657 /// Creates an async I/O handle without setting it to non-blocking mode.
658 ///
659 /// This method will register the handle in [epoll]/[kqueue]/[event ports].
660 ///
661 /// The handle must implement `AsFd`.
662 ///
663 /// [epoll]: https://en.wikipedia.org/wiki/Epoll
664 /// [kqueue]: https://en.wikipedia.org/wiki/Kqueue
665 /// [event ports]: https://illumos.org/man/port_create
666 ///
667 /// # Caveats
668 ///
669 /// The caller should ensure that the handle is set to non-blocking mode or that it is okay if
670 /// it is not set. If not set to non-blocking mode, I/O operations may block the current thread
671 /// and cause a deadlock in an asynchronous context.
672 pub fn new_nonblocking(io: T) -> io::Result<Async<T>> {
673 // SAFETY: It is impossible to drop the I/O source while it is registered through
674 // this type.
675 let registration = unsafe { Registration::new(io.as_fd()) };
676
677 Ok(Async {
678 source: Reactor::get().insert_io(registration)?,
679 io: Some(io),
680 })
681 }
682}
683
684#[cfg(unix)]
685impl<T: AsRawFd> AsRawFd for Async<T> {
686 fn as_raw_fd(&self) -> RawFd {
687 self.get_ref().as_raw_fd()
688 }
689}
690
691#[cfg(unix)]
692impl<T: AsFd> AsFd for Async<T> {
693 fn as_fd(&self) -> BorrowedFd<'_> {
694 self.get_ref().as_fd()
695 }
696}
697
698#[cfg(unix)]
699impl<T: AsFd + From<OwnedFd>> TryFrom<OwnedFd> for Async<T> {
700 type Error = io::Error;
701
702 fn try_from(value: OwnedFd) -> Result<Self, Self::Error> {
703 Async::new(value.into())
704 }
705}
706
707#[cfg(unix)]
708impl<T: Into<OwnedFd>> TryFrom<Async<T>> for OwnedFd {
709 type Error = io::Error;
710
711 fn try_from(value: Async<T>) -> Result<Self, Self::Error> {
712 value.into_inner().map(Into::into)
713 }
714}
715
716impl<T> Async<T> {
717 /// Gets a reference to the inner I/O handle.
718 ///
719 /// # Examples
720 ///
721 /// ```
722 /// use async_io::Async;
723 /// use std::net::TcpListener;
724 ///
725 /// # futures_lite::future::block_on(async {
726 /// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
727 /// let inner = listener.get_ref();
728 /// # std::io::Result::Ok(()) });
729 /// ```
730 pub fn get_ref(&self) -> &T {
731 self.io.as_ref().unwrap()
732 }
733
734 /// Gets a mutable reference to the inner I/O handle.
735 ///
736 /// # Safety
737 ///
738 /// The underlying I/O source must not be dropped using this function.
739 ///
740 /// # Examples
741 ///
742 /// ```
743 /// use async_io::Async;
744 /// use std::net::TcpListener;
745 ///
746 /// # futures_lite::future::block_on(async {
747 /// let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
748 /// let inner = unsafe { listener.get_mut() };
749 /// # std::io::Result::Ok(()) });
750 /// ```
751 pub unsafe fn get_mut(&mut self) -> &mut T {
752 self.io.as_mut().unwrap()
753 }
754
755 /// Unwraps the inner I/O handle.
756 ///
757 /// This method will **not** put the I/O handle back into blocking mode.
758 ///
759 /// # Examples
760 ///
761 /// ```
762 /// use async_io::Async;
763 /// use std::net::TcpListener;
764 ///
765 /// # futures_lite::future::block_on(async {
766 /// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
767 /// let inner = listener.into_inner()?;
768 ///
769 /// // Put the listener back into blocking mode.
770 /// inner.set_nonblocking(false)?;
771 /// # std::io::Result::Ok(()) });
772 /// ```
773 pub fn into_inner(mut self) -> io::Result<T> {
774 let io = self.io.take().unwrap();
775 Reactor::get().remove_io(&self.source)?;
776 Ok(io)
777 }
778
779 /// Waits until the I/O handle is readable.
780 ///
781 /// This method completes when a read operation on this I/O handle wouldn't block.
782 ///
783 /// # Examples
784 ///
785 /// ```no_run
786 /// use async_io::Async;
787 /// use std::net::TcpListener;
788 ///
789 /// # futures_lite::future::block_on(async {
790 /// let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
791 ///
792 /// // Wait until a client can be accepted.
793 /// listener.readable().await?;
794 /// # std::io::Result::Ok(()) });
795 /// ```
796 pub fn readable(&self) -> Readable<'_, T> {
797 Source::readable(self)
798 }
799
800 /// Waits until the I/O handle is readable.
801 ///
802 /// This method completes when a read operation on this I/O handle wouldn't block.
803 pub fn readable_owned(self: Arc<Self>) -> ReadableOwned<T> {
804 Source::readable_owned(self)
805 }
806
807 /// Waits until the I/O handle is writable.
808 ///
809 /// This method completes when a write operation on this I/O handle wouldn't block.
810 ///
811 /// # Examples
812 ///
813 /// ```
814 /// use async_io::Async;
815 /// use std::net::{TcpStream, ToSocketAddrs};
816 ///
817 /// # futures_lite::future::block_on(async {
818 /// let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
819 /// let stream = Async::<TcpStream>::connect(addr).await?;
820 ///
821 /// // Wait until the stream is writable.
822 /// stream.writable().await?;
823 /// # std::io::Result::Ok(()) });
824 /// ```
825 pub fn writable(&self) -> Writable<'_, T> {
826 Source::writable(self)
827 }
828
829 /// Waits until the I/O handle is writable.
830 ///
831 /// This method completes when a write operation on this I/O handle wouldn't block.
832 pub fn writable_owned(self: Arc<Self>) -> WritableOwned<T> {
833 Source::writable_owned(self)
834 }
835
836 /// Polls the I/O handle for readability.
837 ///
838 /// When this method returns [`Poll::Ready`], that means the OS has delivered an event
839 /// indicating readability since the last time this task has called the method and received
840 /// [`Poll::Pending`].
841 ///
842 /// # Caveats
843 ///
844 /// Two different tasks should not call this method concurrently. Otherwise, conflicting tasks
845 /// will just keep waking each other in turn, thus wasting CPU time.
846 ///
847 /// Note that the [`AsyncRead`] implementation for [`Async`] also uses this method.
848 ///
849 /// # Examples
850 ///
851 /// ```no_run
852 /// use async_io::Async;
853 /// use std::future::poll_fn;
854 /// use std::net::TcpListener;
855 ///
856 /// # futures_lite::future::block_on(async {
857 /// let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
858 ///
859 /// // Wait until a client can be accepted.
860 /// poll_fn(|cx| listener.poll_readable(cx)).await?;
861 /// # std::io::Result::Ok(()) });
862 /// ```
863 pub fn poll_readable(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
864 self.source.poll_readable(cx)
865 }
866
867 /// Polls the I/O handle for writability.
868 ///
869 /// When this method returns [`Poll::Ready`], that means the OS has delivered an event
870 /// indicating writability since the last time this task has called the method and received
871 /// [`Poll::Pending`].
872 ///
873 /// # Caveats
874 ///
875 /// Two different tasks should not call this method concurrently. Otherwise, conflicting tasks
876 /// will just keep waking each other in turn, thus wasting CPU time.
877 ///
878 /// Note that the [`AsyncWrite`] implementation for [`Async`] also uses this method.
879 ///
880 /// # Examples
881 ///
882 /// ```
883 /// use async_io::Async;
884 /// use std::future::poll_fn;
885 /// use std::net::{TcpStream, ToSocketAddrs};
886 ///
887 /// # futures_lite::future::block_on(async {
888 /// let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
889 /// let stream = Async::<TcpStream>::connect(addr).await?;
890 ///
891 /// // Wait until the stream is writable.
892 /// poll_fn(|cx| stream.poll_writable(cx)).await?;
893 /// # std::io::Result::Ok(()) });
894 /// ```
895 pub fn poll_writable(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
896 self.source.poll_writable(cx)
897 }
898
899 /// Performs a read operation asynchronously.
900 ///
901 /// The I/O handle is registered in the reactor and put in non-blocking mode. This method
902 /// invokes the `op` closure in a loop until it succeeds or returns an error other than
903 /// [`io::ErrorKind::WouldBlock`]. In between iterations of the loop, it waits until the OS
904 /// sends a notification that the I/O handle is readable.
905 ///
906 /// The closure receives a shared reference to the I/O handle.
907 ///
908 /// # Examples
909 ///
910 /// ```no_run
911 /// use async_io::Async;
912 /// use std::net::TcpListener;
913 ///
914 /// # futures_lite::future::block_on(async {
915 /// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
916 ///
917 /// // Accept a new client asynchronously.
918 /// let (stream, addr) = listener.read_with(|l| l.accept()).await?;
919 /// # std::io::Result::Ok(()) });
920 /// ```
921 pub async fn read_with<R>(&self, op: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {
922 let mut op = op;
923 loop {
924 match op(self.get_ref()) {
925 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
926 res => return res,
927 }
928 optimistic(self.readable()).await?;
929 }
930 }
931
932 /// Performs a read operation asynchronously.
933 ///
934 /// The I/O handle is registered in the reactor and put in non-blocking mode. This method
935 /// invokes the `op` closure in a loop until it succeeds or returns an error other than
936 /// [`io::ErrorKind::WouldBlock`]. In between iterations of the loop, it waits until the OS
937 /// sends a notification that the I/O handle is readable.
938 ///
939 /// The closure receives a mutable reference to the I/O handle.
940 ///
941 /// # Safety
942 ///
943 /// In the closure, the underlying I/O source must not be dropped.
944 ///
945 /// # Examples
946 ///
947 /// ```no_run
948 /// use async_io::Async;
949 /// use std::net::TcpListener;
950 ///
951 /// # futures_lite::future::block_on(async {
952 /// let mut listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
953 ///
954 /// // Accept a new client asynchronously.
955 /// let (stream, addr) = unsafe { listener.read_with_mut(|l| l.accept()).await? };
956 /// # std::io::Result::Ok(()) });
957 /// ```
958 pub async unsafe fn read_with_mut<R>(
959 &mut self,
960 op: impl FnMut(&mut T) -> io::Result<R>,
961 ) -> io::Result<R> {
962 let mut op = op;
963 loop {
964 match op(self.get_mut()) {
965 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
966 res => return res,
967 }
968 optimistic(self.readable()).await?;
969 }
970 }
971
972 /// Performs a write operation asynchronously.
973 ///
974 /// The I/O handle is registered in the reactor and put in non-blocking mode. This method
975 /// invokes the `op` closure in a loop until it succeeds or returns an error other than
976 /// [`io::ErrorKind::WouldBlock`]. In between iterations of the loop, it waits until the OS
977 /// sends a notification that the I/O handle is writable.
978 ///
979 /// The closure receives a shared reference to the I/O handle.
980 ///
981 /// # Examples
982 ///
983 /// ```no_run
984 /// use async_io::Async;
985 /// use std::net::UdpSocket;
986 ///
987 /// # futures_lite::future::block_on(async {
988 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
989 /// socket.get_ref().connect("127.0.0.1:9000")?;
990 ///
991 /// let msg = b"hello";
992 /// let len = socket.write_with(|s| s.send(msg)).await?;
993 /// # std::io::Result::Ok(()) });
994 /// ```
995 pub async fn write_with<R>(&self, op: impl FnMut(&T) -> io::Result<R>) -> io::Result<R> {
996 let mut op = op;
997 loop {
998 match op(self.get_ref()) {
999 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1000 res => return res,
1001 }
1002 optimistic(self.writable()).await?;
1003 }
1004 }
1005
1006 /// Performs a write operation asynchronously.
1007 ///
1008 /// The I/O handle is registered in the reactor and put in non-blocking mode. This method
1009 /// invokes the `op` closure in a loop until it succeeds or returns an error other than
1010 /// [`io::ErrorKind::WouldBlock`]. In between iterations of the loop, it waits until the OS
1011 /// sends a notification that the I/O handle is writable.
1012 ///
1013 /// # Safety
1014 ///
1015 /// The closure receives a mutable reference to the I/O handle. In the closure, the underlying
1016 /// I/O source must not be dropped.
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```no_run
1021 /// use async_io::Async;
1022 /// use std::net::UdpSocket;
1023 ///
1024 /// # futures_lite::future::block_on(async {
1025 /// let mut socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
1026 /// socket.get_ref().connect("127.0.0.1:9000")?;
1027 ///
1028 /// let msg = b"hello";
1029 /// let len = unsafe { socket.write_with_mut(|s| s.send(msg)).await? };
1030 /// # std::io::Result::Ok(()) });
1031 /// ```
1032 pub async unsafe fn write_with_mut<R>(
1033 &mut self,
1034 op: impl FnMut(&mut T) -> io::Result<R>,
1035 ) -> io::Result<R> {
1036 let mut op = op;
1037 loop {
1038 match op(self.get_mut()) {
1039 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1040 res => return res,
1041 }
1042 optimistic(self.writable()).await?;
1043 }
1044 }
1045}
1046
1047impl<T> AsRef<T> for Async<T> {
1048 fn as_ref(&self) -> &T {
1049 self.get_ref()
1050 }
1051}
1052
1053impl<T> Drop for Async<T> {
1054 fn drop(&mut self) {
1055 if self.io.is_some() {
1056 // Deregister and ignore errors because destructors should not panic.
1057 Reactor::get().remove_io(&self.source).ok();
1058
1059 // Drop the I/O handle to close it.
1060 self.io.take();
1061 }
1062 }
1063}
1064
1065/// Types whose I/O trait implementations do not drop the underlying I/O source.
1066///
1067/// The resource contained inside of the [`Async`] cannot be invalidated. This invalidation can
1068/// happen if the inner resource (the [`TcpStream`], [`UnixListener`] or other `T`) is moved out
1069/// and dropped before the [`Async`]. Because of this, functions that grant mutable access to
1070/// the inner type are unsafe, as there is no way to guarantee that the source won't be dropped
1071/// and a dangling handle won't be left behind.
1072///
1073/// Unfortunately this extends to implementations of [`Read`] and [`Write`]. Since methods on those
1074/// traits take `&mut`, there is no guarantee that the implementor of those traits won't move the
1075/// source out while the method is being run.
1076///
1077/// This trait is an antidote to this predicament. By implementing this trait, the user pledges
1078/// that using any I/O traits won't destroy the source. This way, [`Async`] can implement the
1079/// `async` version of these I/O traits, like [`AsyncRead`] and [`AsyncWrite`].
1080///
1081/// # Safety
1082///
1083/// Any I/O trait implementations for this type must not drop the underlying I/O source. Traits
1084/// affected by this trait include [`Read`], [`Write`], [`Seek`] and [`BufRead`].
1085///
1086/// This trait is implemented by default on top of `libstd` types. In addition, it is implemented
1087/// for immutable reference types, as it is impossible to invalidate any outstanding references
1088/// while holding an immutable reference, even with interior mutability. As Rust's current pinning
1089/// system relies on similar guarantees, I believe that this approach is robust.
1090///
1091/// [`BufRead`]: https://doc.rust-lang.org/std/io/trait.BufRead.html
1092/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
1093/// [`Seek`]: https://doc.rust-lang.org/std/io/trait.Seek.html
1094/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1095///
1096/// [`AsyncRead`]: https://docs.rs/futures-io/latest/futures_io/trait.AsyncRead.html
1097/// [`AsyncWrite`]: https://docs.rs/futures-io/latest/futures_io/trait.AsyncWrite.html
1098pub unsafe trait IoSafe {}
1099
1100/// Reference types can't be mutated.
1101///
1102/// The worst thing that can happen is that external state is used to change what kind of pointer
1103/// `as_fd()` returns. For instance:
1104///
1105/// ```
1106/// # #[cfg(unix)] {
1107/// use std::cell::Cell;
1108/// use std::net::TcpStream;
1109/// use std::os::unix::io::{AsFd, BorrowedFd};
1110///
1111/// struct Bar {
1112/// flag: Cell<bool>,
1113/// a: TcpStream,
1114/// b: TcpStream
1115/// }
1116///
1117/// impl AsFd for Bar {
1118/// fn as_fd(&self) -> BorrowedFd<'_> {
1119/// if self.flag.replace(!self.flag.get()) {
1120/// self.a.as_fd()
1121/// } else {
1122/// self.b.as_fd()
1123/// }
1124/// }
1125/// }
1126/// # }
1127/// ```
1128///
1129/// We solve this problem by only calling `as_fd()` once to get the original source. Implementations
1130/// like this are considered buggy (but not unsound) and are thus not really supported by `async-io`.
1131unsafe impl<T: ?Sized> IoSafe for &T {}
1132
1133// Can be implemented on top of libstd types.
1134unsafe impl IoSafe for std::fs::File {}
1135unsafe impl IoSafe for std::io::Stderr {}
1136unsafe impl IoSafe for std::io::Stdin {}
1137unsafe impl IoSafe for std::io::Stdout {}
1138unsafe impl IoSafe for std::io::StderrLock<'_> {}
1139unsafe impl IoSafe for std::io::StdinLock<'_> {}
1140unsafe impl IoSafe for std::io::StdoutLock<'_> {}
1141unsafe impl IoSafe for std::net::TcpStream {}
1142unsafe impl IoSafe for std::process::ChildStdin {}
1143unsafe impl IoSafe for std::process::ChildStdout {}
1144unsafe impl IoSafe for std::process::ChildStderr {}
1145
1146#[cfg(unix)]
1147unsafe impl IoSafe for std::os::unix::net::UnixStream {}
1148
1149// PipeReader & PipeWriter require std >= 1.87, our MSRV is 1.71, hence
1150// conditional on cfg()s, generated from build.rs
1151#[cfg(not(async_io_no_pipe))]
1152#[allow(clippy::incompatible_msrv)]
1153unsafe impl IoSafe for std::io::PipeReader {}
1154#[cfg(not(async_io_no_pipe))]
1155#[allow(clippy::incompatible_msrv)]
1156unsafe impl IoSafe for std::io::PipeWriter {}
1157
1158unsafe impl<T: IoSafe + Read> IoSafe for std::io::BufReader<T> {}
1159unsafe impl<T: IoSafe + Write> IoSafe for std::io::BufWriter<T> {}
1160unsafe impl<T: IoSafe + Write> IoSafe for std::io::LineWriter<T> {}
1161unsafe impl<T: IoSafe + ?Sized> IoSafe for &mut T {}
1162unsafe impl<T: IoSafe + ?Sized> IoSafe for Box<T> {}
1163unsafe impl<T: Clone + IoSafe> IoSafe for std::borrow::Cow<'_, T> {}
1164
1165impl<T: IoSafe + Read> AsyncRead for Async<T> {
1166 fn poll_read(
1167 mut self: Pin<&mut Self>,
1168 cx: &mut Context<'_>,
1169 buf: &mut [u8],
1170 ) -> Poll<io::Result<usize>> {
1171 loop {
1172 match unsafe { (*self).get_mut() }.read(buf) {
1173 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1174 res => return Poll::Ready(res),
1175 }
1176 ready!(self.poll_readable(cx))?;
1177 }
1178 }
1179
1180 fn poll_read_vectored(
1181 mut self: Pin<&mut Self>,
1182 cx: &mut Context<'_>,
1183 bufs: &mut [IoSliceMut<'_>],
1184 ) -> Poll<io::Result<usize>> {
1185 loop {
1186 match unsafe { (*self).get_mut() }.read_vectored(bufs) {
1187 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1188 res => return Poll::Ready(res),
1189 }
1190 ready!(self.poll_readable(cx))?;
1191 }
1192 }
1193}
1194
1195// Since this is through a reference, we can't mutate the inner I/O source.
1196// Therefore this is safe!
1197impl<T> AsyncRead for &Async<T>
1198where
1199 for<'a> &'a T: Read,
1200{
1201 fn poll_read(
1202 self: Pin<&mut Self>,
1203 cx: &mut Context<'_>,
1204 buf: &mut [u8],
1205 ) -> Poll<io::Result<usize>> {
1206 loop {
1207 match (*self).get_ref().read(buf) {
1208 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1209 res => return Poll::Ready(res),
1210 }
1211 ready!(self.poll_readable(cx))?;
1212 }
1213 }
1214
1215 fn poll_read_vectored(
1216 self: Pin<&mut Self>,
1217 cx: &mut Context<'_>,
1218 bufs: &mut [IoSliceMut<'_>],
1219 ) -> Poll<io::Result<usize>> {
1220 loop {
1221 match (*self).get_ref().read_vectored(bufs) {
1222 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1223 res => return Poll::Ready(res),
1224 }
1225 ready!(self.poll_readable(cx))?;
1226 }
1227 }
1228}
1229
1230impl<T: IoSafe + Write> AsyncWrite for Async<T> {
1231 fn poll_write(
1232 mut self: Pin<&mut Self>,
1233 cx: &mut Context<'_>,
1234 buf: &[u8],
1235 ) -> Poll<io::Result<usize>> {
1236 loop {
1237 match unsafe { (*self).get_mut() }.write(buf) {
1238 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1239 res => return Poll::Ready(res),
1240 }
1241 ready!(self.poll_writable(cx))?;
1242 }
1243 }
1244
1245 fn poll_write_vectored(
1246 mut self: Pin<&mut Self>,
1247 cx: &mut Context<'_>,
1248 bufs: &[IoSlice<'_>],
1249 ) -> Poll<io::Result<usize>> {
1250 loop {
1251 match unsafe { (*self).get_mut() }.write_vectored(bufs) {
1252 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1253 res => return Poll::Ready(res),
1254 }
1255 ready!(self.poll_writable(cx))?;
1256 }
1257 }
1258
1259 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1260 loop {
1261 match unsafe { (*self).get_mut() }.flush() {
1262 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1263 res => return Poll::Ready(res),
1264 }
1265 ready!(self.poll_writable(cx))?;
1266 }
1267 }
1268
1269 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1270 self.poll_flush(cx)
1271 }
1272}
1273
1274impl<T> AsyncWrite for &Async<T>
1275where
1276 for<'a> &'a T: Write,
1277{
1278 fn poll_write(
1279 self: Pin<&mut Self>,
1280 cx: &mut Context<'_>,
1281 buf: &[u8],
1282 ) -> Poll<io::Result<usize>> {
1283 loop {
1284 match (*self).get_ref().write(buf) {
1285 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1286 res => return Poll::Ready(res),
1287 }
1288 ready!(self.poll_writable(cx))?;
1289 }
1290 }
1291
1292 fn poll_write_vectored(
1293 self: Pin<&mut Self>,
1294 cx: &mut Context<'_>,
1295 bufs: &[IoSlice<'_>],
1296 ) -> Poll<io::Result<usize>> {
1297 loop {
1298 match (*self).get_ref().write_vectored(bufs) {
1299 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1300 res => return Poll::Ready(res),
1301 }
1302 ready!(self.poll_writable(cx))?;
1303 }
1304 }
1305
1306 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1307 loop {
1308 match (*self).get_ref().flush() {
1309 Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
1310 res => return Poll::Ready(res),
1311 }
1312 ready!(self.poll_writable(cx))?;
1313 }
1314 }
1315
1316 fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1317 self.poll_flush(cx)
1318 }
1319}
1320
1321impl Async<TcpListener> {
1322 /// Creates a TCP listener bound to the specified address.
1323 ///
1324 /// Binding with port number 0 will request an available port from the OS.
1325 ///
1326 /// # Examples
1327 ///
1328 /// ```
1329 /// use async_io::Async;
1330 /// use std::net::TcpListener;
1331 ///
1332 /// # futures_lite::future::block_on(async {
1333 /// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 0))?;
1334 /// println!("Listening on {}", listener.get_ref().local_addr()?);
1335 /// # std::io::Result::Ok(()) });
1336 /// ```
1337 pub fn bind<A: Into<SocketAddr>>(addr: A) -> io::Result<Async<TcpListener>> {
1338 let addr = addr.into();
1339 Async::new(TcpListener::bind(addr)?)
1340 }
1341
1342 /// Accepts a new incoming TCP connection.
1343 ///
1344 /// When a connection is established, it will be returned as a TCP stream together with its
1345 /// remote address.
1346 ///
1347 /// # Examples
1348 ///
1349 /// ```no_run
1350 /// use async_io::Async;
1351 /// use std::net::TcpListener;
1352 ///
1353 /// # futures_lite::future::block_on(async {
1354 /// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?;
1355 /// let (stream, addr) = listener.accept().await?;
1356 /// println!("Accepted client: {}", addr);
1357 /// # std::io::Result::Ok(()) });
1358 /// ```
1359 pub async fn accept(&self) -> io::Result<(Async<TcpStream>, SocketAddr)> {
1360 let (stream, addr) = self.read_with(|io| io.accept()).await?;
1361 Ok((Async::new(stream)?, addr))
1362 }
1363
1364 /// Returns a stream of incoming TCP connections.
1365 ///
1366 /// The stream is infinite, i.e. it never stops with a [`None`].
1367 ///
1368 /// # Examples
1369 ///
1370 /// ```no_run
1371 /// use async_io::Async;
1372 /// use futures_lite::{stream::StreamExt};
1373 /// use std::net::TcpListener;
1374 /// use std::pin::pin;
1375 ///
1376 /// # futures_lite::future::block_on(async {
1377 /// let listener = Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?;
1378 /// let incoming = listener.incoming();
1379 /// let mut incoming = pin!(incoming);
1380 ///
1381 /// while let Some(stream) = incoming.next().await {
1382 /// let stream = stream?;
1383 /// println!("Accepted client: {}", stream.get_ref().peer_addr()?);
1384 /// }
1385 /// # std::io::Result::Ok(()) });
1386 /// ```
1387 pub fn incoming(&self) -> impl Stream<Item = io::Result<Async<TcpStream>>> + Send + '_ {
1388 stream::unfold(self, |listener| async move {
1389 let res = listener.accept().await.map(|(stream, _)| stream);
1390 Some((res, listener))
1391 })
1392 }
1393}
1394
1395impl TryFrom<std::net::TcpListener> for Async<std::net::TcpListener> {
1396 type Error = io::Error;
1397
1398 fn try_from(listener: std::net::TcpListener) -> io::Result<Self> {
1399 Async::new(listener)
1400 }
1401}
1402
1403impl Async<TcpStream> {
1404 /// Creates a TCP connection to the specified address.
1405 ///
1406 /// # Examples
1407 ///
1408 /// ```
1409 /// use async_io::Async;
1410 /// use std::net::{TcpStream, ToSocketAddrs};
1411 ///
1412 /// # futures_lite::future::block_on(async {
1413 /// let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
1414 /// let stream = Async::<TcpStream>::connect(addr).await?;
1415 /// # std::io::Result::Ok(()) });
1416 /// ```
1417 pub async fn connect<A: Into<SocketAddr>>(addr: A) -> io::Result<Async<TcpStream>> {
1418 // Figure out how to handle this address.
1419 let addr = addr.into();
1420 let (domain, sock_addr) = match addr {
1421 SocketAddr::V4(v4) => (rn::AddressFamily::INET, v4.as_any()),
1422 SocketAddr::V6(v6) => (rn::AddressFamily::INET6, v6.as_any()),
1423 };
1424
1425 // Begin async connect.
1426 let socket = connect(sock_addr, domain, Some(rn::ipproto::TCP))?;
1427 // Use new_nonblocking because connect already sets socket to non-blocking mode.
1428 let stream = Async::new_nonblocking(TcpStream::from(socket))?;
1429
1430 // The stream becomes writable when connected.
1431 stream.writable().await?;
1432
1433 // Check if there was an error while connecting.
1434 match stream.get_ref().take_error()? {
1435 None => Ok(stream),
1436 Some(err) => Err(err),
1437 }
1438 }
1439
1440 /// Reads data from the stream without removing it from the buffer.
1441 ///
1442 /// Returns the number of bytes read. Successive calls of this method read the same data.
1443 ///
1444 /// # Examples
1445 ///
1446 /// ```
1447 /// use async_io::Async;
1448 /// use futures_lite::{io::AsyncWriteExt, stream::StreamExt};
1449 /// use std::net::{TcpStream, ToSocketAddrs};
1450 ///
1451 /// # futures_lite::future::block_on(async {
1452 /// let addr = "example.com:80".to_socket_addrs()?.next().unwrap();
1453 /// let mut stream = Async::<TcpStream>::connect(addr).await?;
1454 ///
1455 /// stream
1456 /// .write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
1457 /// .await?;
1458 ///
1459 /// let mut buf = [0u8; 1024];
1460 /// let len = stream.peek(&mut buf).await?;
1461 /// # std::io::Result::Ok(()) });
1462 /// ```
1463 pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1464 self.read_with(|io| io.peek(buf)).await
1465 }
1466}
1467
1468impl TryFrom<std::net::TcpStream> for Async<std::net::TcpStream> {
1469 type Error = io::Error;
1470
1471 fn try_from(stream: std::net::TcpStream) -> io::Result<Self> {
1472 Async::new(stream)
1473 }
1474}
1475
1476impl Async<UdpSocket> {
1477 /// Creates a UDP socket bound to the specified address.
1478 ///
1479 /// Binding with port number 0 will request an available port from the OS.
1480 ///
1481 /// # Examples
1482 ///
1483 /// ```
1484 /// use async_io::Async;
1485 /// use std::net::UdpSocket;
1486 ///
1487 /// # futures_lite::future::block_on(async {
1488 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 0))?;
1489 /// println!("Bound to {}", socket.get_ref().local_addr()?);
1490 /// # std::io::Result::Ok(()) });
1491 /// ```
1492 pub fn bind<A: Into<SocketAddr>>(addr: A) -> io::Result<Async<UdpSocket>> {
1493 let addr = addr.into();
1494 Async::new(UdpSocket::bind(addr)?)
1495 }
1496
1497 /// Receives a single datagram message.
1498 ///
1499 /// Returns the number of bytes read and the address the message came from.
1500 ///
1501 /// This method must be called with a valid byte slice of sufficient size to hold the message.
1502 /// If the message is too long to fit, excess bytes may get discarded.
1503 ///
1504 /// # Examples
1505 ///
1506 /// ```no_run
1507 /// use async_io::Async;
1508 /// use std::net::UdpSocket;
1509 ///
1510 /// # futures_lite::future::block_on(async {
1511 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
1512 ///
1513 /// let mut buf = [0u8; 1024];
1514 /// let (len, addr) = socket.recv_from(&mut buf).await?;
1515 /// # std::io::Result::Ok(()) });
1516 /// ```
1517 pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1518 self.read_with(|io| io.recv_from(buf)).await
1519 }
1520
1521 /// Receives a single datagram message without removing it from the queue.
1522 ///
1523 /// Returns the number of bytes read and the address the message came from.
1524 ///
1525 /// This method must be called with a valid byte slice of sufficient size to hold the message.
1526 /// If the message is too long to fit, excess bytes may get discarded.
1527 ///
1528 /// # Examples
1529 ///
1530 /// ```no_run
1531 /// use async_io::Async;
1532 /// use std::net::UdpSocket;
1533 ///
1534 /// # futures_lite::future::block_on(async {
1535 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
1536 ///
1537 /// let mut buf = [0u8; 1024];
1538 /// let (len, addr) = socket.peek_from(&mut buf).await?;
1539 /// # std::io::Result::Ok(()) });
1540 /// ```
1541 pub async fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1542 self.read_with(|io| io.peek_from(buf)).await
1543 }
1544
1545 /// Sends data to the specified address.
1546 ///
1547 /// Returns the number of bytes written.
1548 ///
1549 /// # Examples
1550 ///
1551 /// ```no_run
1552 /// use async_io::Async;
1553 /// use std::net::UdpSocket;
1554 ///
1555 /// # futures_lite::future::block_on(async {
1556 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 0))?;
1557 /// let addr = socket.get_ref().local_addr()?;
1558 ///
1559 /// let msg = b"hello";
1560 /// let len = socket.send_to(msg, addr).await?;
1561 /// # std::io::Result::Ok(()) });
1562 /// ```
1563 pub async fn send_to<A: Into<SocketAddr>>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
1564 let addr = addr.into();
1565 self.write_with(|io| io.send_to(buf, addr)).await
1566 }
1567
1568 /// Receives a single datagram message from the connected peer.
1569 ///
1570 /// Returns the number of bytes read.
1571 ///
1572 /// This method must be called with a valid byte slice of sufficient size to hold the message.
1573 /// If the message is too long to fit, excess bytes may get discarded.
1574 ///
1575 /// The [`connect`][`UdpSocket::connect()`] method connects this socket to a remote address.
1576 /// This method will fail if the socket is not connected.
1577 ///
1578 /// # Examples
1579 ///
1580 /// ```no_run
1581 /// use async_io::Async;
1582 /// use std::net::UdpSocket;
1583 ///
1584 /// # futures_lite::future::block_on(async {
1585 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
1586 /// socket.get_ref().connect("127.0.0.1:9000")?;
1587 ///
1588 /// let mut buf = [0u8; 1024];
1589 /// let len = socket.recv(&mut buf).await?;
1590 /// # std::io::Result::Ok(()) });
1591 /// ```
1592 pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1593 self.read_with(|io| io.recv(buf)).await
1594 }
1595
1596 /// Receives a single datagram message from the connected peer without removing it from the
1597 /// queue.
1598 ///
1599 /// Returns the number of bytes read and the address the message came from.
1600 ///
1601 /// This method must be called with a valid byte slice of sufficient size to hold the message.
1602 /// If the message is too long to fit, excess bytes may get discarded.
1603 ///
1604 /// The [`connect`][`UdpSocket::connect()`] method connects this socket to a remote address.
1605 /// This method will fail if the socket is not connected.
1606 ///
1607 /// # Examples
1608 ///
1609 /// ```no_run
1610 /// use async_io::Async;
1611 /// use std::net::UdpSocket;
1612 ///
1613 /// # futures_lite::future::block_on(async {
1614 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
1615 /// socket.get_ref().connect("127.0.0.1:9000")?;
1616 ///
1617 /// let mut buf = [0u8; 1024];
1618 /// let len = socket.peek(&mut buf).await?;
1619 /// # std::io::Result::Ok(()) });
1620 /// ```
1621 pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1622 self.read_with(|io| io.peek(buf)).await
1623 }
1624
1625 /// Sends data to the connected peer.
1626 ///
1627 /// Returns the number of bytes written.
1628 ///
1629 /// The [`connect`][`UdpSocket::connect()`] method connects this socket to a remote address.
1630 /// This method will fail if the socket is not connected.
1631 ///
1632 /// # Examples
1633 ///
1634 /// ```no_run
1635 /// use async_io::Async;
1636 /// use std::net::UdpSocket;
1637 ///
1638 /// # futures_lite::future::block_on(async {
1639 /// let socket = Async::<UdpSocket>::bind(([127, 0, 0, 1], 8000))?;
1640 /// socket.get_ref().connect("127.0.0.1:9000")?;
1641 ///
1642 /// let msg = b"hello";
1643 /// let len = socket.send(msg).await?;
1644 /// # std::io::Result::Ok(()) });
1645 /// ```
1646 pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
1647 self.write_with(|io| io.send(buf)).await
1648 }
1649}
1650
1651impl TryFrom<std::net::UdpSocket> for Async<std::net::UdpSocket> {
1652 type Error = io::Error;
1653
1654 fn try_from(socket: std::net::UdpSocket) -> io::Result<Self> {
1655 Async::new(socket)
1656 }
1657}
1658
1659#[cfg(unix)]
1660impl Async<UnixListener> {
1661 /// Creates a UDS listener bound to the specified path.
1662 ///
1663 /// # Examples
1664 ///
1665 /// ```no_run
1666 /// use async_io::Async;
1667 /// use std::os::unix::net::UnixListener;
1668 ///
1669 /// # futures_lite::future::block_on(async {
1670 /// let listener = Async::<UnixListener>::bind("/tmp/socket")?;
1671 /// println!("Listening on {:?}", listener.get_ref().local_addr()?);
1672 /// # std::io::Result::Ok(()) });
1673 /// ```
1674 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<Async<UnixListener>> {
1675 let path = path.as_ref().to_owned();
1676 Async::new(UnixListener::bind(path)?)
1677 }
1678
1679 /// Accepts a new incoming UDS stream connection.
1680 ///
1681 /// When a connection is established, it will be returned as a stream together with its remote
1682 /// address.
1683 ///
1684 /// # Examples
1685 ///
1686 /// ```no_run
1687 /// use async_io::Async;
1688 /// use std::os::unix::net::UnixListener;
1689 ///
1690 /// # futures_lite::future::block_on(async {
1691 /// let listener = Async::<UnixListener>::bind("/tmp/socket")?;
1692 /// let (stream, addr) = listener.accept().await?;
1693 /// println!("Accepted client: {:?}", addr);
1694 /// # std::io::Result::Ok(()) });
1695 /// ```
1696 pub async fn accept(&self) -> io::Result<(Async<UnixStream>, UnixSocketAddr)> {
1697 let (stream, addr) = self.read_with(|io| io.accept()).await?;
1698 Ok((Async::new(stream)?, addr))
1699 }
1700
1701 /// Returns a stream of incoming UDS connections.
1702 ///
1703 /// The stream is infinite, i.e. it never stops with a [`None`] item.
1704 ///
1705 /// # Examples
1706 ///
1707 /// ```no_run
1708 /// use async_io::Async;
1709 /// use futures_lite::stream::StreamExt;
1710 /// use std::os::unix::net::UnixListener;
1711 /// use std::pin::pin;
1712 ///
1713 /// # futures_lite::future::block_on(async {
1714 /// let listener = Async::<UnixListener>::bind("/tmp/socket")?;
1715 /// let incoming = listener.incoming();
1716 /// let mut incoming = pin!(incoming);
1717 ///
1718 /// while let Some(stream) = incoming.next().await {
1719 /// let stream = stream?;
1720 /// println!("Accepted client: {:?}", stream.get_ref().peer_addr()?);
1721 /// }
1722 /// # std::io::Result::Ok(()) });
1723 /// ```
1724 pub fn incoming(&self) -> impl Stream<Item = io::Result<Async<UnixStream>>> + Send + '_ {
1725 stream::unfold(self, |listener| async move {
1726 let res = listener.accept().await.map(|(stream, _)| stream);
1727 Some((res, listener))
1728 })
1729 }
1730}
1731
1732#[cfg(unix)]
1733impl TryFrom<std::os::unix::net::UnixListener> for Async<std::os::unix::net::UnixListener> {
1734 type Error = io::Error;
1735
1736 fn try_from(listener: std::os::unix::net::UnixListener) -> io::Result<Self> {
1737 Async::new(listener)
1738 }
1739}
1740
1741#[cfg(unix)]
1742impl Async<UnixStream> {
1743 /// Creates a UDS stream connected to the specified path.
1744 ///
1745 /// # Examples
1746 ///
1747 /// ```no_run
1748 /// use async_io::Async;
1749 /// use std::os::unix::net::UnixStream;
1750 ///
1751 /// # futures_lite::future::block_on(async {
1752 /// let stream = Async::<UnixStream>::connect("/tmp/socket").await?;
1753 /// # std::io::Result::Ok(()) });
1754 /// ```
1755 pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Async<UnixStream>> {
1756 let address = convert_path_to_socket_address(path.as_ref())?;
1757
1758 // Begin async connect.
1759 let socket = connect(address.into(), rn::AddressFamily::UNIX, None)?;
1760 // Use new_nonblocking because connect already sets socket to non-blocking mode.
1761 let stream = Async::new_nonblocking(UnixStream::from(socket))?;
1762
1763 // The stream becomes writable when connected.
1764 stream.writable().await?;
1765
1766 // On Linux, it appears the socket may become writable even when connecting fails, so we
1767 // must do an extra check here and see if the peer address is retrievable.
1768 stream.get_ref().peer_addr()?;
1769 Ok(stream)
1770 }
1771
1772 /// Creates an unnamed pair of connected UDS stream sockets.
1773 ///
1774 /// # Examples
1775 ///
1776 /// ```no_run
1777 /// use async_io::Async;
1778 /// use std::os::unix::net::UnixStream;
1779 ///
1780 /// # futures_lite::future::block_on(async {
1781 /// let (stream1, stream2) = Async::<UnixStream>::pair()?;
1782 /// # std::io::Result::Ok(()) });
1783 /// ```
1784 pub fn pair() -> io::Result<(Async<UnixStream>, Async<UnixStream>)> {
1785 let (stream1, stream2) = UnixStream::pair()?;
1786 Ok((Async::new(stream1)?, Async::new(stream2)?))
1787 }
1788}
1789
1790#[cfg(unix)]
1791impl TryFrom<std::os::unix::net::UnixStream> for Async<std::os::unix::net::UnixStream> {
1792 type Error = io::Error;
1793
1794 fn try_from(stream: std::os::unix::net::UnixStream) -> io::Result<Self> {
1795 Async::new(stream)
1796 }
1797}
1798
1799#[cfg(unix)]
1800impl Async<UnixDatagram> {
1801 /// Creates a UDS datagram socket bound to the specified path.
1802 ///
1803 /// # Examples
1804 ///
1805 /// ```no_run
1806 /// use async_io::Async;
1807 /// use std::os::unix::net::UnixDatagram;
1808 ///
1809 /// # futures_lite::future::block_on(async {
1810 /// let socket = Async::<UnixDatagram>::bind("/tmp/socket")?;
1811 /// # std::io::Result::Ok(()) });
1812 /// ```
1813 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<Async<UnixDatagram>> {
1814 let path = path.as_ref().to_owned();
1815 Async::new(UnixDatagram::bind(path)?)
1816 }
1817
1818 /// Creates a UDS datagram socket not bound to any address.
1819 ///
1820 /// # Examples
1821 ///
1822 /// ```no_run
1823 /// use async_io::Async;
1824 /// use std::os::unix::net::UnixDatagram;
1825 ///
1826 /// # futures_lite::future::block_on(async {
1827 /// let socket = Async::<UnixDatagram>::unbound()?;
1828 /// # std::io::Result::Ok(()) });
1829 /// ```
1830 pub fn unbound() -> io::Result<Async<UnixDatagram>> {
1831 Async::new(UnixDatagram::unbound()?)
1832 }
1833
1834 /// Creates an unnamed pair of connected Unix datagram sockets.
1835 ///
1836 /// # Examples
1837 ///
1838 /// ```no_run
1839 /// use async_io::Async;
1840 /// use std::os::unix::net::UnixDatagram;
1841 ///
1842 /// # futures_lite::future::block_on(async {
1843 /// let (socket1, socket2) = Async::<UnixDatagram>::pair()?;
1844 /// # std::io::Result::Ok(()) });
1845 /// ```
1846 pub fn pair() -> io::Result<(Async<UnixDatagram>, Async<UnixDatagram>)> {
1847 let (socket1, socket2) = UnixDatagram::pair()?;
1848 Ok((Async::new(socket1)?, Async::new(socket2)?))
1849 }
1850
1851 /// Receives data from the socket.
1852 ///
1853 /// Returns the number of bytes read and the address the message came from.
1854 ///
1855 /// # Examples
1856 ///
1857 /// ```no_run
1858 /// use async_io::Async;
1859 /// use std::os::unix::net::UnixDatagram;
1860 ///
1861 /// # futures_lite::future::block_on(async {
1862 /// let socket = Async::<UnixDatagram>::bind("/tmp/socket")?;
1863 ///
1864 /// let mut buf = [0u8; 1024];
1865 /// let (len, addr) = socket.recv_from(&mut buf).await?;
1866 /// # std::io::Result::Ok(()) });
1867 /// ```
1868 pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, UnixSocketAddr)> {
1869 self.read_with(|io| io.recv_from(buf)).await
1870 }
1871
1872 /// Sends data to the specified address.
1873 ///
1874 /// Returns the number of bytes written.
1875 ///
1876 /// # Examples
1877 ///
1878 /// ```no_run
1879 /// use async_io::Async;
1880 /// use std::os::unix::net::UnixDatagram;
1881 ///
1882 /// # futures_lite::future::block_on(async {
1883 /// let socket = Async::<UnixDatagram>::unbound()?;
1884 ///
1885 /// let msg = b"hello";
1886 /// let addr = "/tmp/socket";
1887 /// let len = socket.send_to(msg, addr).await?;
1888 /// # std::io::Result::Ok(()) });
1889 /// ```
1890 pub async fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
1891 self.write_with(|io| io.send_to(buf, &path)).await
1892 }
1893
1894 /// Receives data from the connected peer.
1895 ///
1896 /// Returns the number of bytes read and the address the message came from.
1897 ///
1898 /// The [`connect`][`UnixDatagram::connect()`] method connects this socket to a remote address.
1899 /// This method will fail if the socket is not connected.
1900 ///
1901 /// # Examples
1902 ///
1903 /// ```no_run
1904 /// use async_io::Async;
1905 /// use std::os::unix::net::UnixDatagram;
1906 ///
1907 /// # futures_lite::future::block_on(async {
1908 /// let socket = Async::<UnixDatagram>::bind("/tmp/socket1")?;
1909 /// socket.get_ref().connect("/tmp/socket2")?;
1910 ///
1911 /// let mut buf = [0u8; 1024];
1912 /// let len = socket.recv(&mut buf).await?;
1913 /// # std::io::Result::Ok(()) });
1914 /// ```
1915 pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1916 self.read_with(|io| io.recv(buf)).await
1917 }
1918
1919 /// Sends data to the connected peer.
1920 ///
1921 /// Returns the number of bytes written.
1922 ///
1923 /// The [`connect`][`UnixDatagram::connect()`] method connects this socket to a remote address.
1924 /// This method will fail if the socket is not connected.
1925 ///
1926 /// # Examples
1927 ///
1928 /// ```no_run
1929 /// use async_io::Async;
1930 /// use std::os::unix::net::UnixDatagram;
1931 ///
1932 /// # futures_lite::future::block_on(async {
1933 /// let socket = Async::<UnixDatagram>::bind("/tmp/socket1")?;
1934 /// socket.get_ref().connect("/tmp/socket2")?;
1935 ///
1936 /// let msg = b"hello";
1937 /// let len = socket.send(msg).await?;
1938 /// # std::io::Result::Ok(()) });
1939 /// ```
1940 pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
1941 self.write_with(|io| io.send(buf)).await
1942 }
1943}
1944
1945#[cfg(unix)]
1946impl TryFrom<std::os::unix::net::UnixDatagram> for Async<std::os::unix::net::UnixDatagram> {
1947 type Error = io::Error;
1948
1949 fn try_from(socket: std::os::unix::net::UnixDatagram) -> io::Result<Self> {
1950 Async::new(socket)
1951 }
1952}
1953
1954/// Polls a future once, waits for a wakeup, and then optimistically assumes the future is ready.
1955async fn optimistic(fut: impl Future<Output = io::Result<()>>) -> io::Result<()> {
1956 let mut polled = false;
1957 let mut fut = pin!(fut);
1958
1959 poll_fn(|cx| {
1960 if !polled {
1961 polled = true;
1962 fut.as_mut().poll(cx)
1963 } else {
1964 Poll::Ready(Ok(()))
1965 }
1966 })
1967 .await
1968}
1969
1970fn connect(
1971 addr: rn::SocketAddrAny,
1972 domain: rn::AddressFamily,
1973 protocol: Option<rn::Protocol>,
1974) -> io::Result<rustix::fd::OwnedFd> {
1975 #[cfg(any(
1976 target_os = "android",
1977 target_os = "dragonfly",
1978 target_os = "freebsd",
1979 target_os = "fuchsia",
1980 target_os = "illumos",
1981 target_os = "linux",
1982 target_os = "netbsd",
1983 target_os = "openbsd"
1984 ))]
1985 let socket = rn::socket_with(
1986 domain,
1987 rn::SocketType::STREAM,
1988 rn::SocketFlags::CLOEXEC | rn::SocketFlags::NONBLOCK,
1989 protocol,
1990 )?;
1991
1992 #[cfg(not(any(
1993 target_os = "android",
1994 target_os = "dragonfly",
1995 target_os = "freebsd",
1996 target_os = "fuchsia",
1997 target_os = "illumos",
1998 target_os = "linux",
1999 target_os = "netbsd",
2000 target_os = "openbsd"
2001 )))]
2002 let socket = {
2003 #[cfg(not(any(
2004 target_os = "aix",
2005 target_vendor = "apple",
2006 target_os = "espidf",
2007 target_os = "haiku",
2008 )))]
2009 let flags = rn::SocketFlags::CLOEXEC;
2010 #[cfg(any(
2011 target_os = "aix",
2012 target_vendor = "apple",
2013 target_os = "espidf",
2014 target_os = "haiku",
2015 ))]
2016 let flags = rn::SocketFlags::empty();
2017
2018 // Create the socket.
2019 let socket = rn::socket_with(domain, rn::SocketType::STREAM, flags, protocol)?;
2020
2021 // Set cloexec if necessary.
2022 #[cfg(any(target_os = "aix", target_vendor = "apple"))]
2023 rio::fcntl_setfd(&socket, rio::fcntl_getfd(&socket)? | rio::FdFlags::CLOEXEC)?;
2024
2025 // Set non-blocking mode.
2026 set_nonblocking(socket.as_fd())?;
2027
2028 socket
2029 };
2030
2031 // Set nosigpipe if necessary.
2032 #[cfg(any(
2033 target_vendor = "apple",
2034 target_os = "freebsd",
2035 target_os = "netbsd",
2036 target_os = "dragonfly",
2037 ))]
2038 rn::sockopt::set_socket_nosigpipe(&socket, true)?;
2039
2040 #[allow(unreachable_patterns)]
2041 match rn::connect(&socket, &addr) {
2042 Ok(_) => {}
2043 #[cfg(unix)]
2044 Err(rio::Errno::INPROGRESS) => {}
2045 Err(rio::Errno::AGAIN) | Err(rio::Errno::WOULDBLOCK) => {}
2046 Err(err) => return Err(err.into()),
2047 }
2048 Ok(socket)
2049}
2050
2051#[inline]
2052fn set_nonblocking(#[cfg(unix)] fd: BorrowedFd<'_>) -> io::Result<()> {
2053 cfg_if::cfg_if! {
2054 // ioctl(FIONBIO) sets the flag atomically, but we use this only on Linux
2055 // for now, as with the standard library, because it seems to behave
2056 // differently depending on the platform.
2057 // https://github.com/rust-lang/rust/commit/efeb42be2837842d1beb47b51bb693c7474aba3d
2058 // https://github.com/libuv/libuv/blob/e9d91fccfc3e5ff772d5da90e1c4a24061198ca0/src/unix/poll.c#L78-L80
2059 // https://github.com/tokio-rs/mio/commit/0db49f6d5caf54b12176821363d154384357e70a
2060 if #[cfg(target_os = "linux")] {
2061 rustix::io::ioctl_fionbio(fd, true)?;
2062 } else {
2063 let previous = rustix::fs::fcntl_getfl(fd)?;
2064 let new = previous | rustix::fs::OFlags::NONBLOCK;
2065 if new != previous {
2066 rustix::fs::fcntl_setfl(fd, new)?;
2067 }
2068 }
2069 }
2070
2071 Ok(())
2072}
2073
2074/// Converts a `Path` to its socket address representation.
2075///
2076/// This function is abstract socket-aware.
2077#[cfg(unix)]
2078#[inline]
2079fn convert_path_to_socket_address(path: &Path) -> io::Result<rn::SocketAddrUnix> {
2080 // SocketAddrUnix::new() will throw EINVAL when a path with a zero in it is passed in.
2081 // However, some users expect to be able to pass in paths to abstract sockets, which
2082 // triggers this error as it has a zero in it. Therefore, if a path starts with a zero,
2083 // make it an abstract socket.
2084 #[cfg(any(target_os = "linux", target_os = "android"))]
2085 let address = {
2086 use std::os::unix::ffi::OsStrExt;
2087
2088 let path = path.as_os_str();
2089 match path.as_bytes().first() {
2090 Some(0) => rn::SocketAddrUnix::new_abstract_name(path.as_bytes().get(1..).unwrap())?,
2091 _ => rn::SocketAddrUnix::new(path)?,
2092 }
2093 };
2094
2095 // Only Linux and Android support abstract sockets.
2096 #[cfg(not(any(target_os = "linux", target_os = "android")))]
2097 let address = rn::SocketAddrUnix::new(path)?;
2098
2099 Ok(address)
2100}