File size: 1,207 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::{future::Future, mem::replace};

use pin_project_lite::pin_project;
use tracing::Span;

pin_project! {
    pub struct With<T, H>
    where
        T: Future,
    {
        #[pin]
        future: T,
        span: Span,
        handle: Option<H>,
    }
}

impl<T, H> With<T, H>
where
    T: Future,
{
    pub fn new(future: T, span: Span, handle: H) -> Self {
        Self {
            future,
            span,
            handle: Some(handle),
        }
    }
}

impl<T, H> Future for With<T, H>
where
    T: Future,
{
    type Output = (H, Span, T::Output);

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        let this = self.project();
        let guard = this.span.enter();
        match this.future.poll(cx) {
            std::task::Poll::Ready(result) => {
                drop(guard);
                std::task::Poll::Ready((
                    this.handle.take().expect("polled after completion"),
                    replace(this.span, Span::none()),
                    result,
                ))
            }
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}