fidl_next/protocol/
server.rsuse crate::protocol::{encode_buffer, MessageBuffer, ProtocolError, Transport};
use crate::{Decoder, Encode, EncodeError, Encoder};
pub fn make_server<T: Transport>(transport: T) -> (Server<T>, Requests<T>) {
let (sender, receiver) = transport.split();
(Server { sender }, Requests { receiver })
}
#[derive(Clone)]
pub struct Server<T: Transport> {
sender: T::Sender,
}
impl<T: Transport> Server<T> {
pub fn send_event<'s, M>(
&'s self,
ordinal: u64,
event: &mut M,
) -> Result<T::SendFuture<'s>, EncodeError>
where
for<'a> T::Encoder<'a>: Encoder,
M: for<'a> Encode<T::Encoder<'a>>,
{
let mut buffer = T::acquire(&self.sender);
encode_buffer(&mut buffer, 0, ordinal, event)?;
Ok(T::send(&self.sender, buffer))
}
pub fn send_response<'s, M>(
&'s self,
responder: Responder,
ordinal: u64,
response: &mut M,
) -> Result<T::SendFuture<'s>, EncodeError>
where
for<'a> T::Encoder<'a>: Encoder,
M: for<'a> Encode<T::Encoder<'a>>,
{
let mut buffer = T::acquire(&self.sender);
encode_buffer(&mut buffer, responder.txid, ordinal, response)?;
Ok(T::send(&self.sender, buffer))
}
}
pub struct Requests<T: Transport> {
receiver: T::Receiver,
}
impl<T: Transport> Requests<T> {
pub async fn next(&mut self) -> Result<Option<Request<T>>, ProtocolError<T::Error>>
where
for<'a> T::Decoder<'a>: Decoder<'a>,
{
let next = T::recv(&mut self.receiver).await.map_err(ProtocolError::TransportError)?;
if let Some(buffer) = next {
let (txid, buffer) = MessageBuffer::parse_header(buffer)?;
if txid == 0 {
Ok(Some(Request::OneWay { buffer }))
} else {
Ok(Some(Request::Transaction { responder: Responder { txid }, buffer }))
}
} else {
Ok(None)
}
}
}
pub enum Request<T: Transport> {
OneWay {
buffer: MessageBuffer<T>,
},
Transaction {
responder: Responder,
buffer: MessageBuffer<T>,
},
}
pub struct Responder {
txid: u32,
}