#![feature(async_await)]
pub mod protocol;
use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use std::io;
use std::marker::Unpin;
pub async fn send<'w, W>(data: &'w [u8], write: &'w mut W) -> Result<usize, io::Error>
where
W: AsyncWrite + Unpin,
{
let prefix = protocol::tobytcp_prefix(data.len());
write.write_all(&prefix).await?;
write.write_all(data).await?;
Ok(data.len() + 8)
}
pub async fn receive<R>(read: &mut R) -> Result<Vec<u8>, io::Error>
where
R: AsyncRead + Unpin,
{
let mut len_buf: [u8; 8] = [0; 8];
read.read_exact(&mut len_buf).await?;
let len = protocol::tobytcp_len(len_buf);
let mut buf = vec![0; len as usize];
read.read_exact(&mut buf).await?;
Ok(buf)
}
#[cfg(test)]
mod tests {
use super::*;
#[runtime::test]
async fn simple_test() {
let to_send: Vec<u8> = vec![13, 58, 2, 4];
let mut output = Vec::new();
let size: usize = 12;
assert_eq!(size, send(&to_send, &mut output).await.unwrap());
let mut len_bytes: [u8; 8] = [0; 8];
len_bytes.clone_from_slice(&output[0..8]);
assert_eq!(4, u64::from_be_bytes(len_bytes));
assert_eq!(to_send[0..], output[8..12]);
let x = output.clone();
let mut y = x.as_slice();
let received = receive(&mut y).await.unwrap();
assert_eq!(received, to_send);
}
#[runtime::test]
async fn many_sends_then_receive_test() {
let mut output = Vec::new();
let num = 20;
for i in 0..num {
let to_send: Vec<u8> = vec![i, i, i, i];
send(&to_send, &mut output).await.unwrap();
}
let x = output.clone();
let mut y = x.as_slice();
for i in 0..num {
let received = receive(&mut y).await.unwrap();
assert_eq!(vec![i, i, i, i], received);
}
}
}