use std::marker::PhantomData; use std::pin::Pin; use std::task::{Context, Poll}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed}; use actix_utils::mpsc; use futures::Stream; use pin_project::pin_project; use crate::dispatcher::FramedMessage; use crate::sink::Sink; pub struct Connect { io: Io, _t: PhantomData<(St, Codec)>, } impl Connect where Io: AsyncRead + AsyncWrite + Unpin, { pub(crate) fn new(io: Io) -> Self { Self { io, _t: PhantomData, } } pub fn codec(self, codec: Codec) -> ConnectResult where Codec: Encoder + Decoder + Unpin, { let (tx, rx) = mpsc::channel(); let sink = Sink::new(tx); ConnectResult { state: (), framed: Framed::new(self.io, codec), rx, sink, } } } #[pin_project] pub struct ConnectResult { pub(crate) state: St, #[pin] pub(crate) framed: Framed, pub(crate) rx: mpsc::Receiver::Item>>, pub(crate) sink: Sink<::Item>, } impl ConnectResult { #[inline] pub fn sink(&self) -> &Sink<::Item> { &self.sink } #[inline] pub fn get_ref(&self) -> &Io { self.framed.get_ref() } #[inline] pub fn get_mut(&mut self) -> &mut Io { self.framed.get_mut() } #[inline] pub fn state(self, state: S) -> ConnectResult { ConnectResult { state, framed: self.framed, rx: self.rx, sink: self.sink, } } } impl Stream for ConnectResult where Io: AsyncRead + AsyncWrite + Unpin, Codec: Encoder + Decoder + Unpin, { type Item = Result<::Item, ::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { self.project().framed.poll_next(cx) } } impl futures::Sink<::Item> for ConnectResult where Io: AsyncRead + AsyncWrite + Unpin, Codec: Encoder + Decoder + Unpin, { type Error = ::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().framed.poll_ready(cx) } fn start_send( self: Pin<&mut Self>, item: ::Item, ) -> Result<(), Self::Error> { self.project().framed.start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().framed.poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.project().framed.poll_close(cx) } }