use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use futures_core::future::FusedFuture;
use super::{chan::Chan, channel::Sender, error::SendError};
pub struct Send<'a, T> {
sender: &'a Sender<T>,
item: Option<T>,
done: bool,
waker_id: Option<u64>,
outcome: Option<Result<(), SendError<T>>>,
}
impl<'a, T> Send<'a, T> {
#[inline(always)]
pub(super) fn new(sender: &'a Sender<T>, item: T) -> Self {
Self {
sender,
item: Some(item),
done: false,
waker_id: None,
outcome: None,
}
}
#[inline]
fn commit(
&mut self,
result: Result<(), SendError<T>>,
chan: &Chan<T>,
) -> Poll<Result<(), SendError<T>>> {
let wake = result.is_ok();
self.done = true;
self.outcome = Some(result);
if let Some(id) = self.waker_id.take() {
chan.remove_send_waker(id);
}
if wake {
chan.wake_receiver();
}
Poll::Ready(self.outcome.take().expect("committed outcome"))
}
}
impl<T> Future for Send<'_, T> {
type Output = Result<(), SendError<T>>;
#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = unsafe { self.get_unchecked_mut() };
if let Some(outcome) = this.outcome.take() {
return Poll::Ready(outcome);
}
if this.done {
return Poll::Pending;
}
let chan = this.sender.chan();
if !chan.receiver_alive() || chan.is_closed() {
let item = this.item.take().expect("message present");
return this.commit(Err(SendError::new(item)), chan);
}
let item = this.item.take().expect("message present");
match chan.try_push(item) {
Ok(()) => this.commit(Ok(()), chan),
Err(item) => {
this.item = Some(item);
if let Some(old_id) = this.waker_id.take() {
chan.remove_send_waker(old_id);
}
let id = chan.add_send_waker(cx.waker());
this.waker_id = Some(id);
if !chan.receiver_alive() || chan.is_closed() {
let item = this.item.take().expect("message present");
return this.commit(Err(SendError::new(item)), chan);
}
let item = this.item.take().expect("message present");
match chan.try_push(item) {
Ok(()) => this.commit(Ok(()), chan),
Err(item) => {
this.item = Some(item);
Poll::Pending
}
}
}
}
}
}
impl<T> FusedFuture for Send<'_, T> {
#[inline(always)]
fn is_terminated(&self) -> bool {
self.done
}
}
impl<T> Drop for Send<'_, T> {
#[inline]
fn drop(&mut self) {
if let Some(id) = self.waker_id.take() {
self.sender.chan().remove_send_waker(id);
}
}
}