Skip to content

Commit 2c7fbf0

Browse files
authored
Merge pull request #39 from NobodyXu/optimize
Optimize `unix::Client::new`: Avoid multi `write`
2 parents 888d2d7 + f049e25 commit 2c7fbf0

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/unix.rs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use libc::c_int;
2+
23
use std::fs::File;
34
use std::io::{self, Read, Write};
45
use std::mem;
@@ -21,13 +22,24 @@ pub struct Acquired {
2122
}
2223

2324
impl Client {
24-
pub fn new(limit: usize) -> io::Result<Client> {
25+
pub fn new(mut limit: usize) -> io::Result<Client> {
2526
let client = unsafe { Client::mk()? };
27+
2628
// I don't think the character written here matters, but I could be
2729
// wrong!
28-
for _ in 0..limit {
29-
(&client.write).write_all(&[b'|'])?;
30+
const BUFFER: [u8; 128] = [b'|'; 128];
31+
32+
set_nonblocking(client.write.as_raw_fd(), true)?;
33+
34+
while limit > 0 {
35+
let n = limit.min(BUFFER.len());
36+
37+
(&client.write).write_all(&BUFFER[..n])?;
38+
limit -= n;
3039
}
40+
41+
set_nonblocking(client.write.as_raw_fd(), false)?;
42+
3143
Ok(client)
3244
}
3345

@@ -322,6 +334,16 @@ fn set_cloexec(fd: c_int, set: bool) -> io::Result<()> {
322334
}
323335
}
324336

337+
fn set_nonblocking(fd: c_int, set: bool) -> io::Result<()> {
338+
let status_flag = if set { libc::O_NONBLOCK } else { 0 };
339+
340+
unsafe {
341+
cvt(libc::fcntl(fd, libc::F_SETFL, status_flag))?;
342+
}
343+
344+
Ok(())
345+
}
346+
325347
fn cvt(t: c_int) -> io::Result<c_int> {
326348
if t == -1 {
327349
Err(io::Error::last_os_error())

0 commit comments

Comments
 (0)