use std::sync::Arc;
use super::{ConnectionContext, WireframeProtocol};
use crate::{codec::EofError, push::PushHandle};
trait ProtocolOperations<F, E>: Send {
fn on_connection_setup(&mut self, handle: PushHandle<F>, ctx: &mut ConnectionContext);
fn before_send(&mut self, frame: &mut F, ctx: &mut ConnectionContext);
fn on_command_end(&mut self, ctx: &mut ConnectionContext);
fn handle_error(&mut self, error: E, ctx: &mut ConnectionContext);
fn stream_end_frame(&mut self, ctx: &mut ConnectionContext) -> Option<F>;
fn on_eof(&mut self, error: &EofError, partial_data: &[u8], ctx: &mut ConnectionContext);
}
struct ProtocolAdapter<P: ?Sized> {
protocol: Arc<P>,
setup_consumed: bool,
}
impl<P, F, E> ProtocolOperations<F, E> for ProtocolAdapter<P>
where
P: WireframeProtocol<Frame = F, ProtocolError = E> + ?Sized,
{
fn on_connection_setup(&mut self, handle: PushHandle<F>, ctx: &mut ConnectionContext) {
if self.setup_consumed {
return;
}
self.setup_consumed = true;
self.protocol.on_connection_setup(handle, ctx);
}
fn before_send(&mut self, frame: &mut F, ctx: &mut ConnectionContext) {
self.protocol.before_send(frame, ctx);
}
fn on_command_end(&mut self, ctx: &mut ConnectionContext) { self.protocol.on_command_end(ctx); }
fn handle_error(&mut self, error: E, ctx: &mut ConnectionContext) {
self.protocol.handle_error(error, ctx);
}
fn stream_end_frame(&mut self, ctx: &mut ConnectionContext) -> Option<F> {
self.protocol.stream_end_frame(ctx)
}
fn on_eof(&mut self, error: &EofError, partial_data: &[u8], ctx: &mut ConnectionContext) {
self.protocol.on_eof(error, partial_data, ctx);
}
}
pub struct ProtocolDispatch<F, E> {
operations: Box<dyn ProtocolOperations<F, E> + Send>,
}
impl<F, E> ProtocolDispatch<F, E> {
pub(crate) fn from_protocol<P>(protocol: &Arc<P>) -> Self
where
P: WireframeProtocol<Frame = F, ProtocolError = E> + ?Sized,
{
Self {
operations: Box::new(ProtocolAdapter {
protocol: Arc::clone(protocol),
setup_consumed: false,
}),
}
}
pub(crate) fn on_connection_setup(
&mut self,
handle: PushHandle<F>,
ctx: &mut ConnectionContext,
) {
self.operations.on_connection_setup(handle, ctx);
}
pub(crate) fn before_send(&mut self, frame: &mut F, ctx: &mut ConnectionContext) {
self.operations.before_send(frame, ctx);
}
pub(crate) fn on_command_end(&mut self, ctx: &mut ConnectionContext) {
self.operations.on_command_end(ctx);
}
pub(crate) fn handle_error(&mut self, error: E, ctx: &mut ConnectionContext) {
self.operations.handle_error(error, ctx);
}
pub(crate) fn stream_end_frame(&mut self, ctx: &mut ConnectionContext) -> Option<F> {
self.operations.stream_end_frame(ctx)
}
pub(crate) fn on_eof(
&mut self,
error: &EofError,
partial_data: &[u8],
ctx: &mut ConnectionContext,
) {
self.operations.on_eof(error, partial_data, ctx);
}
}