runtime/proto_async: simplify functions

And the compiler can use its intrinsic for byte rev.
This commit is contained in:
pca006132 2020-08-25 13:11:58 +08:00
parent d6ab23de1f
commit 71427f8ec8
1 changed files with 8 additions and 60 deletions

View File

@ -52,55 +52,15 @@ pub async fn read_i8(stream: &TcpStream) -> Result<i8> {
} }
pub async fn read_i32(stream: &TcpStream) -> Result<i32> { pub async fn read_i32(stream: &TcpStream) -> Result<i32> {
let mut state = RecvState::NeedsMore(0, 0); let mut buffer: [u8; 4] = [0; 4];
loop { read_chunk(stream, &mut buffer).await?;
state = stream.recv(|buf| { Ok(i32::from_be_bytes(buffer))
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);
}
}
} }
pub async fn read_i64(stream: &TcpStream) -> Result<i64> { pub async fn read_i64(stream: &TcpStream) -> Result<i64> {
let mut state = RecvState::NeedsMore(0, 0); let mut buffer: [u8; 8] = [0; 8];
loop { read_chunk(stream, &mut buffer).await?;
state = stream.recv(|buf| { Ok(i64::from_be_bytes(buffer))
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);
}
}
} }
pub async fn read_chunk(stream: &TcpStream, destination: &mut [u8]) -> Result<()> { 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<()> { pub async fn write_i32(stream: &TcpStream, value: i32) -> Result<()> {
stream.send_slice(&[ stream.send_slice(&value.to_be_bytes()).await?;
(value >> 24) as u8,
(value >> 16) as u8,
(value >> 8) as u8,
value as u8]).await?;
Ok(()) Ok(())
} }
pub async fn write_i64(stream: &TcpStream, value: i64) -> Result<()> { pub async fn write_i64(stream: &TcpStream, value: i64) -> Result<()> {
stream.send_slice(&[ stream.send_slice(&value.to_be_bytes()).await?;
(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?;
Ok(()) Ok(())
} }