use core::fmt;
use crate::runtime::sync;
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (sender, receiver) = sync::oneshot::channel();
(Sender { inner: sender }, Receiver { inner: receiver })
}
pub struct Sender<T> {
inner: sync::oneshot::Sender<T>,
}
impl<T> Sender<T> {
pub fn send(self, value: T) -> Result<(), SendError<T>> {
self.inner.send(value).map_err(SendError)
}
}
impl<T> fmt::Debug for Sender<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Sender").finish_non_exhaustive()
}
}
pub struct Receiver<T> {
inner: sync::oneshot::Receiver<T>,
}
impl<T> Receiver<T> {
pub fn recv(self) -> Result<T, RecvError> {
self.inner.recv().map_err(|_| RecvError)
}
}
impl<T> fmt::Debug for Receiver<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Receiver").finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SendError<T>(pub T);
impl<T> SendError<T> {
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> fmt::Display for SendError<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("one-shot receiver dropped before the value was sent")
}
}
impl<T: fmt::Debug> std::error::Error for SendError<T> {}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RecvError;
impl fmt::Display for RecvError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("one-shot sender dropped without sending a value")
}
}
impl std::error::Error for RecvError {}