Skip to content

Instantly share code, notes, and snippets.

@Milo123459
Created September 11, 2021 13:44
Show Gist options
  • Save Milo123459/59dc242accfac60631e6492b0a64991a to your computer and use it in GitHub Desktop.
Save Milo123459/59dc242accfac60631e6492b0a64991a to your computer and use it in GitHub Desktop.
Some Tokio utilities I use
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::sync::broadcast;
use tokio::time::{sleep, Duration, Instant, Sleep};
pub fn spawn_named<T>(
name: &str,
future: impl std::future::Future<Output = T> + Send + 'static,
) -> tokio::task::JoinHandle<T>
where
T: Send + 'static,
{
#[cfg(tokio_unstable)]
return tokio::task::Builder::new().name(name).spawn(future);
#[cfg(not(tokio_unstable))]
tokio::spawn(future)
}
pin_project_lite::pin_project! {
pub struct PollAndRecieveTimeout<F> {
#[pin]
future: F,
#[pin]
sleep: Sleep,
duration: Duration,
channel: broadcast::Receiver<()>
}
}
impl<F> PollAndRecieveTimeout<F> {
pub fn new(future: F, duration: Duration, channel: broadcast::Receiver<()>) -> Self {
Self {
future,
sleep: sleep(duration),
duration,
channel,
}
}
}
impl<F: Future> Future for PollAndRecieveTimeout<F> {
type Output = Result<F::Output, TimeoutAndRecieveError>;
fn poll(
self: Pin<&mut Self>,
ctx: &mut Context<'_>,
) -> Poll<Result<F::Output, TimeoutAndRecieveError>> {
let me = self.project();
let mut sleep = me.sleep;
let future = me.future;
if sleep.as_mut().poll(ctx).is_ready() || me.channel.try_recv().is_ok() {
return Poll::Ready(Err(TimeoutAndRecieveError {}));
}
sleep.reset(Instant::now() + *me.duration);
future.poll(ctx).map(Ok)
}
}
pub struct TimeoutAndRecieveError {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment