/src/redis-rs/redis/src/io/tcp.rs
Line | Count | Source |
1 | | use std::{io, net::TcpStream}; |
2 | | |
3 | | #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] |
4 | | use std::time::Duration; |
5 | | |
6 | | #[cfg(not(target_family = "wasm"))] |
7 | | pub use socket2; |
8 | | |
9 | | /// Settings for a TCP stream. |
10 | | #[derive(Clone, Debug)] |
11 | | pub struct TcpSettings { |
12 | | nodelay: bool, |
13 | | #[cfg(not(target_family = "wasm"))] |
14 | | keepalive: Option<socket2::TcpKeepalive>, |
15 | | #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] |
16 | | user_timeout: Option<Duration>, |
17 | | } |
18 | | |
19 | | impl TcpSettings { |
20 | | /// Sets the value of the `TCP_NODELAY` option on this socket. |
21 | 0 | pub fn set_nodelay(self, nodelay: bool) -> Self { |
22 | 0 | Self { nodelay, ..self } |
23 | 0 | } |
24 | | |
25 | | /// Set parameters configuring TCP keepalive probes for this socket. |
26 | | /// |
27 | | /// Default values are system-specific |
28 | | #[cfg(not(target_family = "wasm"))] |
29 | 0 | pub fn set_keepalive(self, keepalive: socket2::TcpKeepalive) -> Self { |
30 | 0 | Self { |
31 | 0 | keepalive: Some(keepalive), |
32 | 0 | ..self |
33 | 0 | } |
34 | 0 | } |
35 | | |
36 | | /// Set the value of the `TCP_USER_TIMEOUT` option on this socket. |
37 | | #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] |
38 | 0 | pub fn set_user_timeout(self, user_timeout: Duration) -> Self { |
39 | 0 | Self { |
40 | 0 | user_timeout: Some(user_timeout), |
41 | 0 | ..self |
42 | 0 | } |
43 | 0 | } |
44 | | } |
45 | | |
46 | | #[allow(clippy::derivable_impls)] |
47 | | impl Default for TcpSettings { |
48 | 0 | fn default() -> Self { |
49 | 0 | Self { |
50 | 0 | nodelay: false, |
51 | 0 | #[cfg(not(target_family = "wasm"))] |
52 | 0 | keepalive: None, |
53 | 0 | #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] |
54 | 0 | user_timeout: None, |
55 | 0 | } |
56 | 0 | } |
57 | | } |
58 | | |
59 | 0 | pub(crate) fn stream_with_settings( |
60 | 0 | socket: TcpStream, |
61 | 0 | settings: &TcpSettings, |
62 | 0 | ) -> io::Result<TcpStream> { |
63 | 0 | socket.set_nodelay(settings.nodelay)?; |
64 | | #[cfg(not(target_family = "wasm"))] |
65 | | { |
66 | 0 | let socket2: socket2::Socket = socket.into(); |
67 | 0 | if let Some(keepalive) = &settings.keepalive { |
68 | 0 | socket2.set_tcp_keepalive(keepalive)?; |
69 | 0 | } |
70 | | #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] |
71 | 0 | socket2.set_tcp_user_timeout(settings.user_timeout)?; |
72 | 0 | Ok(socket2.into()) |
73 | | } |
74 | | #[cfg(target_family = "wasm")] |
75 | | { |
76 | | Ok(socket) |
77 | | } |
78 | 0 | } |