1use std::time::Duration;
2
3use crate::Socket;
4
5#[derive(Default, Debug, Copy, Clone)]
8pub struct TcpOpts {
9 recv_buffer_size: Option<usize>,
10 send_buffer_size: Option<usize>,
11 keepalive: Option<bool>,
12 linger: Option<Duration>,
13 read_timeout: Option<Duration>,
14 write_timeout: Option<Duration>,
15 reuse_address: Option<bool>,
16 reuse_port: Option<bool>,
17 nodelay: Option<bool>,
18}
19
20impl TcpOpts {
21 pub fn new() -> Self {
23 TcpOpts::default()
24 }
25
26 pub fn recv_buffer_size(mut self, size: usize) -> Self {
28 self.recv_buffer_size = Some(size);
29 self
30 }
31
32 pub fn send_buffer_size(mut self, size: usize) -> Self {
34 self.send_buffer_size = Some(size);
35 self
36 }
37
38 pub fn keepalive(mut self, keepalive: bool) -> Self {
40 self.keepalive = Some(keepalive);
41 self
42 }
43
44 pub fn linger(mut self, duration: Duration) -> Self {
46 self.linger = Some(duration);
47 self
48 }
49
50 pub fn read_timeout(mut self, duration: Duration) -> Self {
52 self.read_timeout = Some(duration);
53 self
54 }
55
56 pub fn write_timeout(mut self, duration: Duration) -> Self {
58 self.write_timeout = Some(duration);
59 self
60 }
61
62 pub fn reuse_address(mut self, reuse: bool) -> Self {
64 self.reuse_address = Some(reuse);
65 self
66 }
67
68 pub fn reuse_port(mut self, reuse: bool) -> Self {
70 self.reuse_port = Some(reuse);
71 self
72 }
73
74 pub fn nodelay(mut self, nodelay: bool) -> Self {
76 self.nodelay = Some(nodelay);
77 self
78 }
79
80 pub(crate) fn setup_socket(&self, socket: &Socket) -> std::io::Result<()> {
81 if let Some(size) = self.recv_buffer_size {
82 socket.socket.set_recv_buffer_size(size)?;
83 }
84 if let Some(size) = self.send_buffer_size {
85 socket.socket.set_send_buffer_size(size)?;
86 }
87 if let Some(keepalive) = self.keepalive {
88 socket.socket.set_keepalive(keepalive)?;
89 }
90 if let Some(linger) = self.linger {
91 socket.socket.set_linger(Some(linger))?;
92 }
93 if let Some(read_timeout) = self.read_timeout {
94 socket.socket.set_read_timeout(Some(read_timeout))?;
95 }
96 if let Some(write_timeout) = self.write_timeout {
97 socket.socket.set_write_timeout(Some(write_timeout))?;
98 }
99 if let Some(reuse_address) = self.reuse_address {
100 socket.socket.set_reuse_address(reuse_address)?;
101 }
102 #[cfg(all(
103 unix,
104 not(any(target_os = "illumos", target_os = "solaris", target_os = "cygwin"))
105 ))]
106 if let Some(reuse_port) = self.reuse_port {
107 socket.socket.set_reuse_port(reuse_port)?;
108 }
109 if let Some(nodelay) = self.nodelay {
110 socket.socket.set_tcp_nodelay(nodelay)?;
111 }
112 Ok(())
113 }
114}