use std::{
cell::Cell,
fmt,
future::Future,
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use super::{CompletionError, shared::Shared};
#[must_use = "dropping a completion abandons observation; producer work may continue"]
pub struct Completion<T> {
pub(super) shared: Shared<T>,
pub(super) _single_observer: PhantomData<Cell<()>>,
}
impl<T> Completion<T> {
pub fn wait(self) -> Result<T, CompletionError> {
self.shared.wait()
}
pub fn try_take(&self) -> Option<Result<T, CompletionError>> {
self.shared.try_take()
}
pub fn poll_take(&mut self, context: &mut Context<'_>) -> Poll<Result<T, CompletionError>> {
self.shared.poll(context)
}
pub fn abandon(self) {
drop(self);
}
}
impl<T> Future for Completion<T> {
type Output = Result<T, CompletionError>;
fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
self.get_mut().poll_take(context)
}
}
impl<T> fmt::Debug for Completion<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Completion").finish_non_exhaustive()
}
}
impl<T> Drop for Completion<T> {
fn drop(&mut self) {
self.shared.abandon_observer();
}
}