use std::fmt;
use super::stats::ChannelStatistics;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelError {
Full,
Empty,
Closed,
WouldBlock,
InvalidConfig,
}
impl fmt::Display for ChannelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Full => write!(f, "channel is full"),
Self::Empty => write!(f, "channel is empty"),
Self::Closed => write!(f, "channel is closed"),
Self::WouldBlock => write!(f, "operation would block"),
Self::InvalidConfig => write!(f, "invalid channel configuration"),
}
}
}
impl std::error::Error for ChannelError {}
pub type Result<T> = std::result::Result<T, ChannelError>;
pub trait Channel<T>: Send + Sync {
fn send(&self, value: T) -> Result<()>;
fn try_send(&self, value: T) -> Result<()>;
fn recv(&self) -> Result<T>;
fn try_recv(&self) -> Result<T>;
fn is_empty(&self) -> bool;
fn is_full(&self) -> bool;
fn capacity(&self) -> Option<usize>;
fn send_batch(&self, values: Vec<T>) -> Result<usize> {
let mut count = 0;
for value in values {
self.send(value)?;
count += 1;
}
Ok(count)
}
fn recv_batch(&self, max_count: usize) -> Vec<T> {
let mut results = Vec::with_capacity(max_count);
for _ in 0..max_count {
match self.recv() {
Ok(value) => results.push(value),
Err(_) => break,
}
}
results
}
fn close(&self) {}
fn is_closed(&self) -> bool {
false
}
fn len(&self) -> usize {
0
}
fn stats(&self) -> Option<ChannelStatistics> {
None
}
}