use crate::Trigger;
use futures_core::{ready, stream::Stream};
use pin_project::pin_project;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::sync::watch;
#[pin_project]
#[derive(Clone, Debug)]
pub struct TakeUntilIf<S, F> {
#[pin]
stream: S,
#[pin]
until: F,
free: bool,
}
impl<S, F> TakeUntilIf<S, F> {
pub fn into_inner(self) -> S {
self.stream
}
}
pub trait StreamExt: Stream {
fn take_until_if<U>(self, until: U) -> TakeUntilIf<Self, U>
where
U: Future<Output = bool>,
Self: Sized,
{
TakeUntilIf {
stream: self,
until,
free: false,
}
}
}
impl<S> StreamExt for S where S: Stream {}
impl<S, F> Stream for TakeUntilIf<S, F>
where
S: Stream,
F: Future<Output = bool>,
{
type Item = S::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
if !*this.free {
if let Poll::Ready(terminate) = this.until.poll(cx) {
if terminate {
return Poll::Ready(None);
}
*this.free = true;
}
}
this.stream.poll_next(cx)
}
}
#[pin_project]
pub struct Tripwire {
watch: watch::Receiver<bool>,
#[pin]
fut: Option<Pin<Box<dyn Future<Output = bool> + Send + Sync>>>,
}
#[cfg(test)]
static_assertions::assert_impl_all!(Tripwire: Sync, Send);
impl Clone for Tripwire {
fn clone(&self) -> Self {
Self {
watch: self.watch.clone(),
fut: None,
}
}
}
impl fmt::Debug for Tripwire {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Tripwire").field(&self.watch).finish()
}
}
impl Tripwire {
pub fn new() -> (Trigger, Self) {
let (tx, rx) = watch::channel(false);
(
Trigger(Some(tx)),
Tripwire {
watch: rx,
fut: None,
},
)
}
}
impl Future for Tripwire {
type Output = bool;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
if this.fut.is_none() {
let mut watch = this.watch.clone();
this.fut.set(Some(Box::pin(async move {
while !*watch.borrow() {
if let Err(_) = watch.changed().await {
return *watch.borrow();
}
}
true
})));
}
unsafe { this.fut.map_unchecked_mut(|f| f.as_mut().unwrap()) }
.as_mut()
.poll(cx)
}
}
#[pin_project]
struct ResultTrueFalse<F>(#[pin] F);
impl<F, T, E> Future for ResultTrueFalse<F>
where
F: Future<Output = Result<T, E>>,
{
type Output = bool;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
ready!(self.project().0.poll(cx)).is_ok().into()
}
}