use crate::error::{Error, Result};
use bytes::{Bytes, BytesMut};
use std::future::Future;
pub trait Channel: Send {
fn recv(&mut self) -> impl Future<Output = Result<Option<Bytes>>> + Send;
fn send(&mut self, data: Bytes) -> impl Future<Output = Result<()>> + Send;
fn close(&mut self) -> impl Future<Output = Result<()>> + Send;
}
pub trait Connection: Send + Sync {
type Channel: Channel + 'static;
fn open(&self, service: &str) -> impl Future<Output = Result<Self::Channel>> + Send;
fn features(&self) -> impl Future<Output = Result<Vec<String>>> + Send;
}
impl<C: Connection> Connection for &C {
type Channel = C::Channel;
fn open(&self, service: &str) -> impl Future<Output = Result<Self::Channel>> + Send {
C::open(self, service)
}
fn features(&self) -> impl Future<Output = Result<Vec<String>>> + Send {
C::features(self)
}
}
impl<C: Connection> Connection for std::sync::Arc<C> {
type Channel = C::Channel;
fn open(&self, service: &str) -> impl Future<Output = Result<Self::Channel>> + Send {
C::open(self, service)
}
fn features(&self) -> impl Future<Output = Result<Vec<String>>> + Send {
C::features(self)
}
}
#[derive(Debug)]
pub struct ChannelReader<C> {
channel: C,
buffer: BytesMut,
}
impl<C: Channel> ChannelReader<C> {
pub fn new(channel: C) -> Self {
Self {
channel,
buffer: BytesMut::new(),
}
}
pub fn channel(&mut self) -> &mut C {
&mut self.channel
}
pub fn into_parts(self) -> (C, Bytes) {
(self.channel, self.buffer.freeze())
}
pub async fn read_exact(&mut self, len: usize) -> Result<Bytes> {
while self.buffer.len() < len {
match self.channel.recv().await? {
Some(chunk) => self.buffer.extend_from_slice(&chunk),
None => return Err(Error::StreamClosed),
}
}
Ok(self.buffer.split_to(len).freeze())
}
pub async fn read_u32(&mut self) -> Result<u32> {
let b = self.read_exact(4).await?;
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
pub async fn next_chunk(&mut self) -> Result<Option<Bytes>> {
if !self.buffer.is_empty() {
return Ok(Some(self.buffer.split().freeze()));
}
self.channel.recv().await
}
pub async fn read_to_end(&mut self) -> Result<Bytes> {
while let Some(chunk) = self.channel.recv().await? {
self.buffer.extend_from_slice(&chunk);
}
Ok(self.buffer.split().freeze())
}
}
pub async fn drain<C: Channel>(channel: C) -> Result<Bytes> {
let mut reader = ChannelReader::new(channel);
let out = reader.read_to_end().await?;
reader.channel().close().await?;
Ok(out)
}