| 1 |
|
| 2 |
|
| 3 |
use std::io; |
| 4 |
|
| 5 |
use log::trace; |
| 6 |
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; |
| 7 |
|
| 8 |
use crate::io::{StreamIo, StreamOutput}; |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
pub async fn handle( |
| 15 |
stream: impl AsyncRead + AsyncWrite + Unpin, |
| 16 |
io: StreamIo, |
| 17 |
) -> io::Result<StreamIo> { |
| 18 |
match io { |
| 19 |
StreamIo::Read(io) => read(stream, io).await, |
| 20 |
StreamIo::Write(io) => write(stream, io).await, |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
pub async fn read( |
| 25 |
mut stream: impl AsyncRead + Unpin, |
| 26 |
input: Result<StreamOutput, Vec<u8>>, |
| 27 |
) -> io::Result<StreamIo> { |
| 28 |
let mut buffer = match input { |
| 29 |
Ok(output) => return Ok(StreamIo::Read(Ok(output))), |
| 30 |
Err(buffer) => buffer, |
| 31 |
}; |
| 32 |
|
| 33 |
trace!("reading bytes asynchronously"); |
| 34 |
let bytes_count = stream.read(&mut buffer).await?; |
| 35 |
|
| 36 |
let output = StreamOutput { |
| 37 |
buffer, |
| 38 |
bytes_count, |
| 39 |
}; |
| 40 |
|
| 41 |
Ok(StreamIo::Read(Ok(output))) |
| 42 |
} |
| 43 |
|
| 44 |
pub async fn write( |
| 45 |
mut stream: impl AsyncWrite + Unpin, |
| 46 |
input: Result<StreamOutput, Vec<u8>>, |
| 47 |
) -> io::Result<StreamIo> { |
| 48 |
let bytes = match input { |
| 49 |
Ok(output) => return Ok(StreamIo::Write(Ok(output))), |
| 50 |
Err(bytes) => bytes, |
| 51 |
}; |
| 52 |
|
| 53 |
trace!("writing bytes asynchronously"); |
| 54 |
let bytes_count = stream.write(&bytes).await?; |
| 55 |
|
| 56 |
let output = StreamOutput { |
| 57 |
buffer: bytes, |
| 58 |
bytes_count, |
| 59 |
}; |
| 60 |
|
| 61 |
Ok(StreamIo::Write(Ok(output))) |
| 62 |
} |