use std::{io, net::TcpStream};
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
use std::time::Duration;
#[derive(Clone, Debug)]
pub struct TcpSettings {
nodelay: bool,
keepalive: Option<socket2::TcpKeepalive>,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
user_timeout: Option<Duration>,
}
impl TcpSettings {
pub fn set_nodelay(self, nodelay: bool) -> Self {
Self { nodelay, ..self }
}
pub fn set_keepalive(self, keepalive: socket2::TcpKeepalive) -> Self {
Self {
keepalive: Some(keepalive),
..self
}
}
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub fn set_user_timeout(self, user_timeout: Duration) -> Self {
Self {
user_timeout: Some(user_timeout),
..self
}
}
}
impl Default for TcpSettings {
fn default() -> Self {
Self {
#[cfg(feature = "tcp_nodelay")]
nodelay: true,
#[cfg(not(feature = "tcp_nodelay"))]
nodelay: false,
keepalive: None,
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
user_timeout: None,
}
}
}
pub(crate) fn stream_with_settings(
socket: TcpStream,
settings: &TcpSettings,
) -> io::Result<TcpStream> {
socket.set_nodelay(settings.nodelay)?;
let socket2: socket2::Socket = socket.into();
if let Some(keepalive) = &settings.keepalive {
socket2.set_tcp_keepalive(keepalive)?;
}
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
socket2.set_tcp_user_timeout(settings.user_timeout)?;
Ok(socket2.into())
}