From d4c3b70d6290c52f903e674e9957b979abd4ce07 Mon Sep 17 00:00:00 2001 From: lamp Date: Sun, 5 Mar 2023 21:37:45 +0000 Subject: init --- src/peekable_bufreader.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/peekable_bufreader.rs (limited to 'src/peekable_bufreader.rs') diff --git a/src/peekable_bufreader.rs b/src/peekable_bufreader.rs new file mode 100644 index 0000000..ae02155 --- /dev/null +++ b/src/peekable_bufreader.rs @@ -0,0 +1,47 @@ +use async_std::prelude::*; +use async_std::io::BufReader; +use async_std::io::Read; + +pub struct PeekableBufReader + where T: Read + Unpin { + reader: BufReader, + buffer: [u8; 1], + peeked_last: bool, +} + +impl PeekableBufReader + where T: Read + Unpin { + pub fn new(reader: BufReader) -> Self { + Self { + reader, + buffer: [0], + peeked_last: false, + } + } + + pub async fn next(&mut self) -> Option { + if self.peeked_last { + self.peeked_last = false; + Some(self.buffer[0]) + } else { + match self.reader.read(&mut self.buffer).await.ok()? { + 1 => Some(self.buffer[0]), + _ => None, + } + } + } + + pub async fn peek(&mut self) -> Option<&u8> { + if self.peeked_last { + Some(&self.buffer[0]) + } else { + match self.reader.read(&mut self.buffer).await.ok()? { + 1 => { + self.peeked_last = true; + Some(&self.buffer[0]) + }, + _ => None, + } + } + } +} -- cgit v1.2.3