aboutsummaryrefslogtreecommitdiffstats
path: root/src/reader.rs
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2021-12-03 21:28:44 -0500
committerJesse Luehrs <doy@tozt.net>2021-12-04 01:58:12 -0500
commit9d07ac10cf7ec1278dd90ae8c4fe73cbd80c3fd5 (patch)
treef13aa19d200087b392e6481da97fdeb30dfd3bae /src/reader.rs
parent8a98d4fee2172d5ac53e74bcc95cd39aa68492a3 (diff)
downloadttyrec-9d07ac10cf7ec1278dd90ae8c4fe73cbd80c3fd5.tar.gz
ttyrec-9d07ac10cf7ec1278dd90ae8c4fe73cbd80c3fd5.zip
reintroduce readers and writers with a new api
Diffstat (limited to 'src/reader.rs')
-rw-r--r--src/reader.rs49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/reader.rs b/src/reader.rs
new file mode 100644
index 0000000..6641bb9
--- /dev/null
+++ b/src/reader.rs
@@ -0,0 +1,49 @@
+use futures::io::AsyncReadExt as _;
+
+/// Reads ttyrec frames from a `futures::io::AsyncRead` instance.
+pub struct Reader<T: futures::io::AsyncRead> {
+ input: T,
+ parser: crate::Parser,
+ buf: [u8; 4096],
+}
+
+impl<T: futures::io::AsyncRead + std::marker::Unpin + Send> Reader<T> {
+ /// Creates a new `Reader` from a `futures::io::AsyncRead` instance.
+ pub fn new(input: T) -> Self {
+ Self {
+ input,
+ parser: crate::Parser::new(),
+ buf: [0; 4096],
+ }
+ }
+
+ /// Returns the next parsed frame from the input stream.
+ ///
+ /// # Errors
+ /// * `crate::Error::EOF`: The input stream has been closed.
+ /// * `crate::Error::Read`: There was an error reading from the input
+ /// stream.
+ pub async fn read_frame(&mut self) -> crate::Result<crate::Frame> {
+ loop {
+ if let Some(frame) = self.parser.next_frame() {
+ return Ok(frame);
+ }
+ let bytes = self
+ .input
+ .read(&mut self.buf)
+ .await
+ .map_err(|source| crate::Error::Read { source })?;
+ if bytes == 0 {
+ return Err(crate::Error::EOF);
+ }
+ self.parser.add_bytes(&self.buf[..bytes]);
+ }
+ }
+
+ /// How much the timestamps in this file should be offset by.
+ ///
+ /// See `Parser::offset`.
+ pub fn offset(&self) -> Option<std::time::Duration> {
+ self.parser.offset()
+ }
+}