| 1 |
|
| 2 |
|
| 3 |
use log::{debug, trace}; |
| 4 |
use thiserror::Error; |
| 5 |
|
| 6 |
use crate::io::{StreamIo, StreamOutput}; |
| 7 |
|
| 8 |
|
| 9 |
#[derive(Clone, Debug, Error)] |
| 10 |
pub enum WriteStreamError { |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
#[error("Invalid argument: expected {0}, got {1:?}")] |
| 17 |
InvalidArgument(&'static str, StreamIo), |
| 18 |
} |
| 19 |
|
| 20 |
|
| 21 |
#[derive(Clone, Debug)] |
| 22 |
pub enum WriteStreamResult { |
| 23 |
|
| 24 |
Ok(StreamOutput), |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
Io(StreamIo), |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
Eof, |
| 34 |
|
| 35 |
|
| 36 |
Err(WriteStreamError), |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
#[derive(Debug, Default)] |
| 41 |
pub struct WriteStream { |
| 42 |
bytes: Vec<u8>, |
| 43 |
} |
| 44 |
|
| 45 |
impl WriteStream { |
| 46 |
|
| 47 |
pub fn new(bytes: Vec<u8>) -> Self { |
| 48 |
trace!("init coroutine for writing {} bytes", bytes.len()); |
| 49 |
Self { bytes } |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
pub fn resume(&mut self, arg: Option<StreamIo>) -> WriteStreamResult { |
| 73 |
let Some(arg) = arg else { |
| 74 |
let bytes = self.bytes.drain(..).collect(); |
| 75 |
trace!("wants I/O to write bytes"); |
| 76 |
return WriteStreamResult::Io(StreamIo::Write(Err(bytes))); |
| 77 |
}; |
| 78 |
|
| 79 |
trace!("resume after writing bytes"); |
| 80 |
|
| 81 |
let StreamIo::Write(io) = arg else { |
| 82 |
return WriteStreamResult::Err(WriteStreamError::InvalidArgument("write output", arg)); |
| 83 |
}; |
| 84 |
|
| 85 |
let output = match io { |
| 86 |
Ok(output) => output, |
| 87 |
Err(bytes) => return WriteStreamResult::Io(StreamIo::Write(Err(bytes))), |
| 88 |
}; |
| 89 |
|
| 90 |
match output.bytes_count { |
| 91 |
0 => WriteStreamResult::Eof, |
| 92 |
n => { |
| 93 |
debug!("wrote {n} bytes"); |
| 94 |
WriteStreamResult::Ok(output) |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
} |