feat(proto): add generic proto reader
This commit is contained in:
parent
67af05ea42
commit
413e0216e3
5 changed files with 87 additions and 0 deletions
37
proto/src/reader/oneway.rs
Normal file
37
proto/src/reader/oneway.rs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
use crate::message::proto_message::ProtoMessage;
|
||||
use crate::reader::protoreader::ProtoReader;
|
||||
use crate::reader::utils::AsyncPeek;
|
||||
use async_trait::async_trait;
|
||||
use tokio::io::{AsyncBufRead, AsyncReadExt};
|
||||
|
||||
#[async_trait]
|
||||
pub trait OneWayProtoReader<T>
|
||||
where
|
||||
T: ProtoMessage,
|
||||
{
|
||||
async fn read_proto(&mut self) -> anyhow::Result<T>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<R, T> OneWayProtoReader<T> for ProtoReader<R>
|
||||
where
|
||||
R: AsyncBufRead + AsyncPeek + Unpin + Send,
|
||||
T: ProtoMessage,
|
||||
{
|
||||
async fn read_proto(&mut self) -> anyhow::Result<T> {
|
||||
let variant = self.inner.read_u8().await?;
|
||||
let length = self.inner.read_i32().await?;
|
||||
|
||||
if length < 4 {
|
||||
return Err(anyhow::anyhow!("Invalid message length"));
|
||||
}
|
||||
if length > self.msg_len_limit {
|
||||
return Err(anyhow::anyhow!("Message length over limit"));
|
||||
}
|
||||
|
||||
let mut data = vec![0u8; (length - 4) as usize];
|
||||
self.inner.read_exact(&mut data).await?;
|
||||
|
||||
T::deserialize(variant, &data)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue