diff options
author | lamp | 2023-03-05 21:37:45 +0000 |
---|---|---|
committer | lamp | 2023-03-05 21:37:45 +0000 |
commit | d4c3b70d6290c52f903e674e9957b979abd4ce07 (patch) | |
tree | ba415f0f85809ffe07dd17d83ed46e5c09f2c14d /src/peekable_bufreader.rs |
initmain
Diffstat (limited to 'src/peekable_bufreader.rs')
-rw-r--r-- | src/peekable_bufreader.rs | 47 |
1 files changed, 47 insertions, 0 deletions
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<T> + where T: Read + Unpin { + reader: BufReader<T>, + buffer: [u8; 1], + peeked_last: bool, +} + +impl<T> PeekableBufReader<T> + where T: Read + Unpin { + pub fn new(reader: BufReader<T>) -> Self { + Self { + reader, + buffer: [0], + peeked_last: false, + } + } + + pub async fn next(&mut self) -> Option<u8> { + 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, + } + } + } +} |