async_rs/traits/
addr.rs

1use std::{
2    future, io,
3    net::{IpAddr, SocketAddr},
4};
5
6/// A common interface for resolving domain name + port to `SocketAddr`
7pub trait AsyncToSocketAddrs {
8    /// Resolve the domain name through DNS and return an `Iterator` of `SocketAddr`
9    fn to_socket_addrs(
10        self,
11    ) -> impl Future<Output = io::Result<impl Iterator<Item = SocketAddr> + Send + 'static>>
12    + Send
13    + 'static
14    where
15        Self: Sized;
16}
17
18impl<A: Into<SocketAddr> + sealed::SocketSealed> AsyncToSocketAddrs for A {
19    fn to_socket_addrs(
20        self,
21    ) -> impl Future<Output = io::Result<impl Iterator<Item = SocketAddr> + Send + 'static>>
22    + Send
23    + 'static {
24        future::ready(Ok(Some(self.into()).into_iter()))
25    }
26}
27
28impl<I: Into<IpAddr> + sealed::IpSealed> AsyncToSocketAddrs for (I, u16) {
29    fn to_socket_addrs(
30        self,
31    ) -> impl Future<Output = io::Result<impl Iterator<Item = SocketAddr> + Send + 'static>>
32    + Send
33    + 'static {
34        future::ready(Ok(Some((self.0.into(), self.1).into()).into_iter()))
35    }
36}
37
38impl AsyncToSocketAddrs for Vec<SocketAddr> {
39    fn to_socket_addrs(
40        self,
41    ) -> impl Future<Output = io::Result<impl Iterator<Item = SocketAddr> + Send + 'static>>
42    + Send
43    + 'static {
44        future::ready(Ok(self.into_iter()))
45    }
46}
47
48impl AsyncToSocketAddrs for &[SocketAddr] {
49    fn to_socket_addrs(
50        self,
51    ) -> impl Future<Output = io::Result<impl Iterator<Item = SocketAddr> + Send + 'static>>
52    + Send
53    + 'static {
54        self.to_vec().to_socket_addrs()
55    }
56}
57
58mod sealed {
59    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
60
61    pub trait SocketSealed {}
62
63    // Into<SocketAddr>
64    impl SocketSealed for SocketAddr {}
65    impl SocketSealed for SocketAddrV4 {}
66    impl SocketSealed for SocketAddrV6 {}
67
68    pub trait IpSealed {}
69
70    // Into<IpAddr>
71    impl IpSealed for IpAddr {}
72    impl IpSealed for Ipv4Addr {}
73    impl IpSealed for Ipv6Addr {}
74    impl IpSealed for [u8; 4] {}
75    impl IpSealed for [u8; 16] {}
76    impl IpSealed for [u16; 8] {}
77}