Skip to main content

msg_common/
lib.rs

1//! Common utilities and types for msg-rs.
2
3#![doc(issue_tracker_base_url = "https://github.com/chainbound/msg-rs/issues/")]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![cfg_attr(not(test), warn(unused_crate_dependencies))]
6
7use std::{
8    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
9    time::SystemTime,
10};
11
12use futures::future::BoxFuture;
13
14mod channel;
15pub use channel::{Channel, channel};
16
17mod task;
18pub use task::JoinMap;
19
20pub mod span;
21
22/// Returns the current UNIX timestamp in microseconds.
23#[inline]
24pub fn unix_micros() -> u64 {
25    SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_micros() as u64
26}
27
28/// Wraps the given error in a boxed future.
29pub fn async_error<E: std::error::Error + Send + 'static, T>(
30    e: E,
31) -> BoxFuture<'static, Result<T, E>> {
32    Box::pin(async move { Err(e) })
33}
34
35#[allow(non_upper_case_globals)]
36pub mod constants {
37    pub const KiB: u32 = 1024;
38    pub const MiB: u32 = 1024 * KiB;
39    pub const GiB: u32 = 1024 * MiB;
40}
41
42/// Extension trait for `SocketAddr`.
43pub trait SocketAddrExt: Sized {
44    /// Returns the unspecified IPv4 socket address, bound to port 0.
45    fn unspecified_v4() -> Self;
46
47    /// Returns the unspecified IPv6 socket address, bound to port 0.
48    fn unspecified_v6() -> Self;
49
50    /// Returns the unspecified socket address of the same family as `other`, bound to port 0.
51    fn as_unspecified(&self) -> Self;
52}
53
54impl SocketAddrExt for SocketAddr {
55    #[inline]
56    fn unspecified_v4() -> Self {
57        Self::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0))
58    }
59
60    #[inline]
61    fn unspecified_v6() -> Self {
62        Self::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0))
63    }
64
65    #[inline]
66    fn as_unspecified(&self) -> Self {
67        match self {
68            Self::V4(_) => Self::unspecified_v4(),
69            Self::V6(_) => Self::unspecified_v6(),
70        }
71    }
72}
73
74/// Extension trait for IP addresses.
75pub trait IpAddrExt: Sized {
76    /// Returns the localhost address of the same family as `other`.
77    fn as_localhost(&self) -> Self;
78}
79
80impl IpAddrExt for IpAddr {
81    #[inline]
82    fn as_localhost(&self) -> Self {
83        match self {
84            Self::V4(_) => Self::V4(Ipv4Addr::LOCALHOST),
85            Self::V6(_) => Self::V6(Ipv6Addr::LOCALHOST),
86        }
87    }
88}