libp2p_quic/provider/async_std.rs
1// Copyright 2022 Protocol Labs.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::{
22 io,
23 net::UdpSocket,
24 task::{Context, Poll},
25 time::Duration,
26};
27
28use futures::{future::BoxFuture, FutureExt};
29
30use crate::GenTransport;
31
32/// Transport with [`async-std`] runtime.
33pub type Transport = GenTransport<Provider>;
34
35/// Provider for quinn runtime and spawning tasks using [`async-std`].
36pub struct Provider;
37
38impl super::Provider for Provider {
39 type IfWatcher = if_watch::smol::IfWatcher;
40
41 fn runtime() -> super::Runtime {
42 super::Runtime::AsyncStd
43 }
44
45 fn new_if_watcher() -> io::Result<Self::IfWatcher> {
46 if_watch::smol::IfWatcher::new()
47 }
48
49 fn poll_if_event(
50 watcher: &mut Self::IfWatcher,
51 cx: &mut Context<'_>,
52 ) -> Poll<io::Result<if_watch::IfEvent>> {
53 watcher.poll_if_event(cx)
54 }
55
56 fn sleep(duration: Duration) -> BoxFuture<'static, ()> {
57 async_std::task::sleep(duration).boxed()
58 }
59
60 fn send_to<'a>(
61 udp_socket: &'a UdpSocket,
62 buf: &'a [u8],
63 target: std::net::SocketAddr,
64 ) -> BoxFuture<'a, io::Result<usize>> {
65 Box::pin(async move {
66 async_std::net::UdpSocket::from(udp_socket.try_clone()?)
67 .send_to(buf, target)
68 .await
69 })
70 }
71}