use crate::connection::Endpoint;
use crate::muxing::{StreamMuxer, StreamMuxerEvent};
use futures::prelude::*;
use std::cell::Cell;
use std::pin::Pin;
use std::{io, task::Context, task::Poll};
pub struct SingletonMuxer<TSocket> {
inner: Cell<Option<TSocket>>,
endpoint: Endpoint,
}
impl<TSocket> SingletonMuxer<TSocket> {
pub fn new(inner: TSocket, endpoint: Endpoint) -> Self {
SingletonMuxer {
inner: Cell::new(Some(inner)),
endpoint,
}
}
}
impl<TSocket> StreamMuxer for SingletonMuxer<TSocket>
where
TSocket: AsyncRead + AsyncWrite + Unpin,
{
type Substream = TSocket;
type Error = io::Error;
fn poll_inbound(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Result<Self::Substream, Self::Error>> {
let this = self.get_mut();
match this.endpoint {
Endpoint::Dialer => Poll::Pending,
Endpoint::Listener => match this.inner.replace(None) {
None => Poll::Pending,
Some(stream) => Poll::Ready(Ok(stream)),
},
}
}
fn poll_outbound(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Result<Self::Substream, Self::Error>> {
let this = self.get_mut();
match this.endpoint {
Endpoint::Listener => Poll::Pending,
Endpoint::Dialer => match this.inner.replace(None) {
None => Poll::Pending,
Some(stream) => Poll::Ready(Ok(stream)),
},
}
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(()))
}
fn poll(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Result<StreamMuxerEvent, Self::Error>> {
Poll::Pending
}
}