use crate::protocol::common::{ProtocolMessage, ReceivingStream, SendReceivePair, SendingStream};
use anyhow::Result;
use either::{Either, Left, Right};
use std::future::Future;
use std::pin::Pin;
use tokio::io::{ReadHalf, SimplexStream, WriteHalf, simplex};
type TestStreamPair = SendReceivePair<WriteHalf<SimplexStream>, ReadHalf<SimplexStream>>;
impl SendingStream for WriteHalf<SimplexStream> {}
impl ReceivingStream for ReadHalf<SimplexStream> {}
const STREAM_BUFFER_SIZE: usize = 4_096;
pub(crate) fn new_test_plumbing() -> (TestStreamPair, TestStreamPair) {
let p1 = simplex(STREAM_BUFFER_SIZE);
let p2 = simplex(STREAM_BUFFER_SIZE);
let r1 = (p1.1, p2.0).into();
let r2 = (p2.1, p1.0).into();
(r1, r2)
}
pub(crate) async fn read_from_stream<T, R, F>(
pipe: &mut R,
other_fut: &mut Pin<Box<F>>,
) -> Either<Result<T>, <F as futures_util::Future>::Output>
where
T: ProtocolMessage,
R: ReceivingStream,
F: Future + ?Sized,
{
let obj_fut = T::from_reader_async_framed(pipe);
tokio::pin!(obj_fut);
tokio::select! {
o = obj_fut => Left(o),
v = other_fut => Right(v),
}
}