Skip to content

Commit

Permalink
optimize by merging 3 unbuffered reads on IPC message header into one
Browse files Browse the repository at this point in the history
This reduces the number of system calls done for reading an
incoming IPC message from 4 to 2 and improves latency
  • Loading branch information
gergo-salyi authored and JayceFayne committed Oct 19, 2024
1 parent 8c2d587 commit 577f673
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
11 changes: 5 additions & 6 deletions async/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ use swayipc_types::{Error::InvalidMagic, Fallible, MAGIC};
pub(super) async fn receive_from_stream(
stream: &mut Async<UnixStream>,
) -> Fallible<(u32, Vec<u8>)> {
let mut magic_data = [0_u8; 6];
stream.read_exact(&mut magic_data).await?;
let mut header_buf = [0_u8; 14];
stream.read_exact(&mut header_buf).await?;
let magic_data: [u8; 6] = header_buf[..6].try_into().unwrap();
if magic_data != MAGIC {
return Err(InvalidMagic(magic_data));
}
let mut payload_len_buf = [0_u8; 4];
stream.read_exact(&mut payload_len_buf).await?;
let payload_len_buf: [u8; 4] = header_buf[6..10].try_into().unwrap();
let payload_len = u32::from_ne_bytes(payload_len_buf);
let mut reply_type_buf = [0_u8; 4];
stream.read_exact(&mut reply_type_buf).await?;
let reply_type_buf: [u8; 4] = header_buf[10..14].try_into().unwrap();
let reply_type = u32::from_ne_bytes(reply_type_buf);
let mut reply_payload = vec![0_u8; payload_len as usize];
stream.read_exact(&mut reply_payload).await?;
Expand Down
11 changes: 5 additions & 6 deletions blocking/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ use std::os::unix::net::UnixStream;
use swayipc_types::{Error::InvalidMagic, Fallible, MAGIC};

pub(super) fn receive_from_stream(stream: &mut UnixStream) -> Fallible<(u32, Vec<u8>)> {
let mut magic_data = [0_u8; 6];
stream.read_exact(&mut magic_data)?;
let mut header_buf = [0_u8; 14];
stream.read_exact(&mut header_buf)?;
let magic_data: [u8; 6] = header_buf[..6].try_into().unwrap();
if magic_data != MAGIC {
return Err(InvalidMagic(magic_data));
}
let mut payload_len_buf = [0_u8; 4];
stream.read_exact(&mut payload_len_buf)?;
let payload_len_buf: [u8; 4] = header_buf[6..10].try_into().unwrap();
let payload_len = u32::from_ne_bytes(payload_len_buf);
let mut reply_type_buf = [0_u8; 4];
stream.read_exact(&mut reply_type_buf)?;
let reply_type_buf: [u8; 4] = header_buf[10..14].try_into().unwrap();
let reply_type = u32::from_ne_bytes(reply_type_buf);
let mut reply_payload = vec![0_u8; payload_len as usize];
stream.read_exact(&mut reply_payload)?;
Expand Down

0 comments on commit 577f673

Please sign in to comment.