From 71427f8ec8f3ca3a919c94164657c649897bb4b8 Mon Sep 17 00:00:00 2001 From: pca006132 Date: Tue, 25 Aug 2020 13:11:58 +0800 Subject: [PATCH] runtime/proto_async: simplify functions And the compiler can use its intrinsic for byte rev. --- src/runtime/src/proto_async.rs | 68 ++++------------------------------ 1 file changed, 8 insertions(+), 60 deletions(-) diff --git a/src/runtime/src/proto_async.rs b/src/runtime/src/proto_async.rs index b974e22..32cd23c 100644 --- a/src/runtime/src/proto_async.rs +++ b/src/runtime/src/proto_async.rs @@ -52,55 +52,15 @@ pub async fn read_i8(stream: &TcpStream) -> Result { } pub async fn read_i32(stream: &TcpStream) -> Result { - let mut state = RecvState::NeedsMore(0, 0); - loop { - state = stream.recv(|buf| { - let mut consumed = 0; - if let RecvState::NeedsMore(mut cur_index, mut cur_value) = state { - for b in buf.iter() { - consumed += 1; - cur_index += 1; - cur_value <<= 8; - cur_value |= *b as i32; - if cur_index == 4 { - return (consumed, RecvState::Completed(cur_value)); - } - } - (consumed, RecvState::NeedsMore(cur_index, cur_value)) - } else { - unreachable!(); - } - }).await?; - if let RecvState::Completed(result) = state { - return Ok(result); - } - } + let mut buffer: [u8; 4] = [0; 4]; + read_chunk(stream, &mut buffer).await?; + Ok(i32::from_be_bytes(buffer)) } pub async fn read_i64(stream: &TcpStream) -> Result { - let mut state = RecvState::NeedsMore(0, 0); - loop { - state = stream.recv(|buf| { - let mut consumed = 0; - if let RecvState::NeedsMore(mut cur_index, mut cur_value) = state { - for b in buf.iter() { - consumed += 1; - cur_index += 1; - cur_value <<= 8; - cur_value |= *b as i64; - if cur_index == 8 { - return (consumed, RecvState::Completed(cur_value)); - } - } - (consumed, RecvState::NeedsMore(cur_index, cur_value)) - } else { - unreachable!(); - } - }).await?; - if let RecvState::Completed(result) = state { - return Ok(result); - } - } + let mut buffer: [u8; 8] = [0; 8]; + read_chunk(stream, &mut buffer).await?; + Ok(i64::from_be_bytes(buffer)) } pub async fn read_chunk(stream: &TcpStream, destination: &mut [u8]) -> Result<()> { @@ -130,24 +90,12 @@ pub async fn write_bool(stream: &TcpStream, value: bool) -> Result<()> { } pub async fn write_i32(stream: &TcpStream, value: i32) -> Result<()> { - stream.send_slice(&[ - (value >> 24) as u8, - (value >> 16) as u8, - (value >> 8) as u8, - value as u8]).await?; + stream.send_slice(&value.to_be_bytes()).await?; Ok(()) } pub async fn write_i64(stream: &TcpStream, value: i64) -> Result<()> { - stream.send_slice(&[ - (value >> 56) as u8, - (value >> 48) as u8, - (value >> 40) as u8, - (value >> 32) as u8, - (value >> 24) as u8, - (value >> 16) as u8, - (value >> 8) as u8, - value as u8]).await?; + stream.send_slice(&value.to_be_bytes()).await?; Ok(()) }