pessimize/
net.rs

1//! Implementations of Pessimize for std::net types
2
3use crate::{pessimize_copy, pessimize_extractible};
4use std::net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream, UdpSocket};
5#[cfg(unix)]
6use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
7#[cfg(windows)]
8use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
9
10pessimize_copy!(
11    doc(cfg(feature = "std"))
12    {
13        u32 : (Ipv4Addr: (Self::into, Self::from)),
14
15        (Ipv4Addr, u16) : (
16            SocketAddrV4: (
17                |self_: Self| (*self_.ip(), self_.port()),
18                |(ip, port)| Self::new(ip, port)
19            )
20        )
21
22        // Will not pessimize IPv6 types as doing that efficiently would require
23        // native u128 support, which no mainstream hardware has.
24    }
25);
26
27#[cfg(any(unix, windows))]
28macro_rules! pessimize_sockets {
29    ($fd:ty, $as_fd:path, $into_fd:path, $from_fd:path) => {
30        pessimize_extractible!(
31            doc(cfg(all(feature = "std", any(unix, windows))))
32            {
33                $fd : (
34                    TcpListener : ($into_fd, $from_fd, $as_fd),
35                    TcpStream : ($into_fd, $from_fd, $as_fd),
36                    UdpSocket : ($into_fd, $from_fd, $as_fd)
37                )
38            }
39        );
40    };
41}
42//
43#[cfg(unix)]
44pessimize_sockets!(
45    RawFd,
46    AsRawFd::as_raw_fd,
47    IntoRawFd::into_raw_fd,
48    FromRawFd::from_raw_fd
49);
50//
51#[cfg(windows)]
52pessimize_sockets!(
53    RawSocket,
54    AsRawSocket::as_raw_handle,
55    IntoRawSocket::into_raw_handle,
56    FromRawSocket::from_raw_handle
57);
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::tests::{test_unoptimized_value, test_value};
63
64    #[test]
65    fn ipv4_addr() {
66        test_value(Ipv4Addr::from(u32::MIN));
67        test_value(Ipv4Addr::from(u32::MAX));
68    }
69
70    #[test]
71    #[ignore]
72    fn ipv4_addr_optim() {
73        test_unoptimized_value(Ipv4Addr::from(u32::MAX));
74    }
75
76    #[test]
77    fn socket_addr_v4() {
78        test_value(SocketAddrV4::new(Ipv4Addr::from(u32::MIN), u16::MAX));
79        test_value(SocketAddrV4::new(Ipv4Addr::from(u32::MAX), u16::MIN));
80    }
81
82    #[test]
83    #[ignore]
84    fn socket_addr_v4_optim() {
85        test_unoptimized_value(SocketAddrV4::new(Ipv4Addr::from(u32::MAX), u16::MAX));
86    }
87
88    // Can't test inbound sockets because that would require ability to open
89    // inbound network ports (can't be assumed, e.g. Windows firewall is enabled
90    // by default and blocks that), and without that can't test outbound sockets
91    // either because without a local server that would require internet
92    // connectivity, which cannot be assumed.
93}