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