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