libp2p_quic/
provider.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::{SocketAddr, UdpSocket},
24    task::{Context, Poll},
25    time::Duration,
26};
27
28use futures::future::BoxFuture;
29use if_watch::IfEvent;
30
31#[cfg(feature = "async-std")]
32pub mod async_std;
33#[cfg(feature = "tokio")]
34pub mod tokio;
35
36pub enum Runtime {
37    #[cfg(feature = "tokio")]
38    Tokio,
39    #[cfg(feature = "async-std")]
40    AsyncStd,
41    Dummy,
42}
43
44/// Provider for a corresponding quinn runtime and spawning tasks.
45pub trait Provider: Unpin + Send + Sized + 'static {
46    type IfWatcher: Unpin + Send;
47
48    /// Run the corresponding runtime
49    fn runtime() -> Runtime;
50
51    /// Create a new [`if_watch`] watcher that reports [`IfEvent`]s for network interface changes.
52    fn new_if_watcher() -> io::Result<Self::IfWatcher>;
53
54    /// Poll for an address change event.
55    fn poll_if_event(
56        watcher: &mut Self::IfWatcher,
57        cx: &mut Context<'_>,
58    ) -> Poll<io::Result<IfEvent>>;
59
60    /// Sleep for specified amount of time.
61    fn sleep(duration: Duration) -> BoxFuture<'static, ()>;
62
63    /// Sends data on the socket to the given address. On success,
64    /// returns the number of bytes written.
65    fn send_to<'a>(
66        udp_socket: &'a UdpSocket,
67        buf: &'a [u8],
68        target: SocketAddr,
69    ) -> BoxFuture<'a, io::Result<usize>>;
70}