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