feat(proto): add generic proto writer
This commit is contained in:
parent
65f90ba600
commit
0a3683e2fa
4 changed files with 69 additions and 0 deletions
|
|
@ -1 +1,2 @@
|
||||||
pub mod message;
|
pub mod message;
|
||||||
|
pub mod writer;
|
||||||
|
|
|
||||||
3
proto/src/writer/mod.rs
Normal file
3
proto/src/writer/mod.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
|
||||||
|
pub mod oneway;
|
||||||
|
pub mod protowriter;
|
||||||
31
proto/src/writer/oneway.rs
Normal file
31
proto/src/writer/oneway.rs
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
use crate::message::proto_message::ProtoMessage;
|
||||||
|
use crate::writer::protowriter::ProtoWriter;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use tokio::io::{AsyncWrite, AsyncWriteExt};
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait OneWayProtoWriter<T>
|
||||||
|
where
|
||||||
|
T: ProtoMessage,
|
||||||
|
{
|
||||||
|
async fn write_proto(&mut self, message: T) -> anyhow::Result<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<W, T> OneWayProtoWriter<T> for ProtoWriter<W>
|
||||||
|
where
|
||||||
|
W: AsyncWrite + Unpin + Send,
|
||||||
|
T: ProtoMessage + Send + 'static,
|
||||||
|
{
|
||||||
|
async fn write_proto(&mut self, message: T) -> anyhow::Result<()> {
|
||||||
|
let variant = message.variant();
|
||||||
|
let mut data = message.serialize()?;
|
||||||
|
let length = data.len() as i32 + 4;
|
||||||
|
|
||||||
|
self.inner.write_u8(variant).await?;
|
||||||
|
self.inner.write_i32(length).await?;
|
||||||
|
self.inner.write_all(&mut data).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
34
proto/src/writer/protowriter.rs
Normal file
34
proto/src/writer/protowriter.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use tokio::io::{AsyncWrite, AsyncWriteExt};
|
||||||
|
|
||||||
|
pub struct ProtoWriter<W>
|
||||||
|
where
|
||||||
|
W: AsyncWrite + Unpin + Send,
|
||||||
|
{
|
||||||
|
pub(super) inner: W,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W> ProtoWriter<W>
|
||||||
|
where
|
||||||
|
W: AsyncWrite + Unpin + Send,
|
||||||
|
{
|
||||||
|
pub fn new(writer: W) -> ProtoWriter<W> {
|
||||||
|
ProtoWriter { inner: writer }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ProtoFlush {
|
||||||
|
async fn flush(&mut self) -> anyhow::Result<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<W> ProtoFlush for ProtoWriter<W>
|
||||||
|
where
|
||||||
|
W: AsyncWrite + Unpin + Send,
|
||||||
|
{
|
||||||
|
async fn flush(&mut self) -> anyhow::Result<()> {
|
||||||
|
self.inner.flush().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue