pub use std::sync::mpsc::{RecvError, RecvTimeoutError, SendError, TryRecvError};
use crate::time::Instant;
#[must_use]
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (tx, rx) = std::sync::mpsc::channel();
(Sender(tx), Receiver(rx))
}
pub struct Sender<T>(std::sync::mpsc::Sender<T>);
impl<T> Sender<T> {
pub fn send(&self, value: T) -> Result<(), SendError<T>> {
self.0.send(value)
}
}
impl<T> Clone for Sender<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
pub struct Receiver<T>(std::sync::mpsc::Receiver<T>);
impl<T> Receiver<T> {
pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
self.0.iter()
}
pub fn recv(&self) -> Result<T, RecvError> {
self.0.recv()
}
pub fn recv_timeout(&self, deadline: Instant) -> Result<T, RecvTimeoutError> {
let now = Instant::now();
let remaining = deadline.saturating_duration_since(now);
self.0.recv_timeout(remaining)
}
pub fn try_iter(&self) -> impl Iterator<Item = T> + '_ {
self.0.try_iter()
}
pub fn try_recv(&self) -> Result<T, TryRecvError> {
self.0.try_recv()
}
}