|
4 | 4 | #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] |
5 | 5 | #![cfg_attr(not(test), warn(unused_crate_dependencies))] |
6 | 6 |
|
7 | | -use std::time::SystemTime; |
| 7 | +use std::{ |
| 8 | + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}, |
| 9 | + time::SystemTime, |
| 10 | +}; |
8 | 11 |
|
9 | 12 | use futures::future::BoxFuture; |
10 | 13 |
|
@@ -33,3 +36,47 @@ pub mod constants { |
33 | 36 | pub const MiB: u32 = 1024 * KiB; |
34 | 37 | pub const GiB: u32 = 1024 * MiB; |
35 | 38 | } |
| 39 | + |
| 40 | +/// Extension trait for `SocketAddr`. |
| 41 | +pub trait SocketAddrExt: Sized { |
| 42 | + /// Returns the unspecified IPv4 socket address, bound to port 0. |
| 43 | + fn unspecified_v4() -> Self; |
| 44 | + |
| 45 | + /// Returns the unspecified IPv6 socket address, bound to port 0. |
| 46 | + fn unspecified_v6() -> Self; |
| 47 | + |
| 48 | + /// Returns the unspecified socket address of the same family as `other`, bound to port 0. |
| 49 | + fn as_unspecified(&self) -> Self; |
| 50 | +} |
| 51 | + |
| 52 | +impl SocketAddrExt for SocketAddr { |
| 53 | + fn unspecified_v4() -> Self { |
| 54 | + Self::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) |
| 55 | + } |
| 56 | + |
| 57 | + fn unspecified_v6() -> Self { |
| 58 | + Self::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)) |
| 59 | + } |
| 60 | + |
| 61 | + fn as_unspecified(&self) -> Self { |
| 62 | + match self { |
| 63 | + Self::V4(_) => Self::unspecified_v4(), |
| 64 | + Self::V6(_) => Self::unspecified_v6(), |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +/// Extension trait for IP addresses. |
| 70 | +pub trait IpAddrExt: Sized { |
| 71 | + /// Returns the localhost address of the same family as `other`. |
| 72 | + fn as_localhost(&self) -> Self; |
| 73 | +} |
| 74 | + |
| 75 | +impl IpAddrExt for IpAddr { |
| 76 | + fn as_localhost(&self) -> Self { |
| 77 | + match self { |
| 78 | + Self::V4(_) => Self::V4(Ipv4Addr::LOCALHOST), |
| 79 | + Self::V6(_) => Self::V6(Ipv6Addr::LOCALHOST), |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments