diff options
author | Jesse Luehrs <doy@tozt.net> | 2021-12-03 21:28:44 -0500 |
---|---|---|
committer | Jesse Luehrs <doy@tozt.net> | 2021-12-04 01:58:12 -0500 |
commit | 9d07ac10cf7ec1278dd90ae8c4fe73cbd80c3fd5 (patch) | |
tree | f13aa19d200087b392e6481da97fdeb30dfd3bae /src/writer.rs | |
parent | 8a98d4fee2172d5ac53e74bcc95cd39aa68492a3 (diff) | |
download | ttyrec-9d07ac10cf7ec1278dd90ae8c4fe73cbd80c3fd5.tar.gz ttyrec-9d07ac10cf7ec1278dd90ae8c4fe73cbd80c3fd5.zip |
reintroduce readers and writers with a new api
Diffstat (limited to 'src/writer.rs')
-rw-r--r-- | src/writer.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/writer.rs b/src/writer.rs new file mode 100644 index 0000000..6975ad1 --- /dev/null +++ b/src/writer.rs @@ -0,0 +1,46 @@ +use futures::io::AsyncWriteExt as _; + +/// Writes ttyrec frames to a `futures::io::AsyncWrite` instance. +pub struct Writer<T: futures::io::AsyncWrite> { + output: T, + creator: crate::Creator, +} + +impl<T: futures::io::AsyncWrite + std::marker::Unpin + Send> Writer<T> { + /// Creates a new `Writer` from a `futures::io::AsyncWrite` instance. + pub fn new(output: T) -> Self { + Self { + output, + creator: crate::Creator::new(), + } + } + + /// Writes a new frame to the output stream, using the current time and + /// given data. + /// + /// # Errors + /// * `crate::Error::Write`: There was an error writing to the input + /// stream. + pub async fn frame(&mut self, data: &[u8]) -> crate::Result<()> { + self.frame_at(std::time::Instant::now(), data).await + } + + /// Writes a new frame to the output stream, using the given time and + /// data. + /// + /// # Errors + /// * `crate::Error::Write`: There was an error writing to the input + /// stream. + pub async fn frame_at( + &mut self, + cur_time: std::time::Instant, + data: &[u8], + ) -> crate::Result<()> { + let frame = self.creator.frame_at(cur_time, data); + let bytes: Vec<u8> = frame.try_into()?; + self.output + .write_all(&bytes) + .await + .map_err(|source| crate::Error::Write { source }) + } +} |