feat(proto): add generic proto reader

This commit is contained in:
Jindřich Moravec 2023-12-11 16:53:21 +01:00
parent 67af05ea42
commit 413e0216e3
5 changed files with 87 additions and 0 deletions

24
proto/src/reader/utils.rs Normal file
View file

@ -0,0 +1,24 @@
use async_trait::async_trait;
use tokio::io::{AsyncBufRead, AsyncBufReadExt};
#[async_trait]
pub trait AsyncPeek {
async fn peek(&mut self, buf: &mut [u8]) -> std::io::Result<usize>;
}
#[async_trait]
impl<T> AsyncPeek for T
where
T: AsyncBufRead + Unpin + Send,
{
async fn peek(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let filled = self.fill_buf().await?;
if filled.len() >= buf.len() {
buf.copy_from_slice(&filled[..buf.len()]);
Ok(buf.len())
} else {
buf[..filled.len()].copy_from_slice(filled);
Ok(filled.len())
}
}
}