use alloc::vec::Vec;
use core::future::Future;
use super::ids::LocalId;
use super::session::Session;
use crate::error::Error;
#[derive(Debug)]
pub enum SelectResult<T> {
Data(usize),
Interrupted(T),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChannelId {
pub(crate) slot: usize,
pub(crate) local: LocalId,
}
impl ChannelId {
pub fn from_raw(slot: usize, local_id: u32) -> Self {
Self {
slot,
local: LocalId::from(local_id),
}
}
pub fn slot(self) -> usize {
self.slot
}
pub fn local_id(self) -> u32 {
self.local.raw()
}
}
pub struct Channel<'a, S> {
pub(crate) session: &'a mut S,
pub(crate) id: ChannelId,
}
impl<S: Session> Channel<'_, S> {
pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error<S::IoError>> {
self.session.read_channel(self.id, buf).await
}
pub async fn write(&mut self, data: &[u8]) -> Result<(), Error<S::IoError>> {
self.session.write_channel(self.id, data).await
}
pub async fn select<F: Future>(
&mut self,
buf: &mut [u8],
interrupt: F,
) -> Result<SelectResult<F::Output>, Error<S::IoError>> {
self.session.select_channel(self.id, buf, interrupt).await
}
pub async fn close(self) -> Result<(), Error<S::IoError>> {
self.session.close_channel(self.id).await
}
}
pub(crate) struct Capped;
pub(crate) trait ReadToEnd: Sized {
type IoError;
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error<Self::IoError>>;
async fn close(self) -> Result<(), Error<Self::IoError>>;
async fn read_to_end(mut self, buf: &mut [u8]) -> Result<usize, Error<Self::IoError>> {
let mut tail = 0;
let mut scratch = [0u8; 1];
let read = loop {
let full = tail == buf.len();
let room = if full {
&mut scratch[..]
} else {
&mut buf[tail..]
};
match self.read(room).await {
Ok(n) if full && n > 0 => break Err(Error::ReceiveBufferFull),
Ok(n) => tail += n,
Err(Error::ChannelClosed) => break Ok(tail),
Err(e) => break Err(e),
}
};
let _ = self.close().await;
read
}
async fn read_to_vec(
mut self,
rx: &mut [u8],
cap: usize,
) -> Result<Result<Vec<u8>, Capped>, Error<Self::IoError>> {
let mut out = Vec::new();
let read = loop {
match self.read(rx).await {
Ok(n) if n > cap - out.len() => break Ok(Err(Capped)),
Ok(n) => out.extend_from_slice(&rx[..n]),
Err(Error::ChannelClosed) => break Ok(Ok(out)),
Err(e) => break Err(e),
}
};
let _ = self.close().await;
read
}
}
impl<S: Session> ReadToEnd for Channel<'_, S> {
type IoError = S::IoError;
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error<S::IoError>> {
Channel::read(self, buf).await
}
async fn close(self) -> Result<(), Error<S::IoError>> {
Channel::close(self).await
}
}