Skip to content

Commit

Permalink
Merge pull request #39 from NobodyXu/optimize
Browse files Browse the repository at this point in the history
Optimize `unix::Client::new`: Avoid multi `write`
  • Loading branch information
alexcrichton authored Jul 5, 2022
2 parents 888d2d7 + f049e25 commit 2c7fbf0
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/unix.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use libc::c_int;

use std::fs::File;
use std::io::{self, Read, Write};
use std::mem;
Expand All @@ -21,13 +22,24 @@ pub struct Acquired {
}

impl Client {
pub fn new(limit: usize) -> io::Result<Client> {
pub fn new(mut limit: usize) -> io::Result<Client> {
let client = unsafe { Client::mk()? };

// I don't think the character written here matters, but I could be
// wrong!
for _ in 0..limit {
(&client.write).write_all(&[b'|'])?;
const BUFFER: [u8; 128] = [b'|'; 128];

set_nonblocking(client.write.as_raw_fd(), true)?;

while limit > 0 {
let n = limit.min(BUFFER.len());

(&client.write).write_all(&BUFFER[..n])?;
limit -= n;
}

set_nonblocking(client.write.as_raw_fd(), false)?;

Ok(client)
}

Expand Down Expand Up @@ -322,6 +334,16 @@ fn set_cloexec(fd: c_int, set: bool) -> io::Result<()> {
}
}

fn set_nonblocking(fd: c_int, set: bool) -> io::Result<()> {
let status_flag = if set { libc::O_NONBLOCK } else { 0 };

unsafe {
cvt(libc::fcntl(fd, libc::F_SETFL, status_flag))?;
}

Ok(())
}

fn cvt(t: c_int) -> io::Result<c_int> {
if t == -1 {
Err(io::Error::last_os_error())
Expand Down

0 comments on commit 2c7fbf0

Please sign in to comment.