isahc/interceptor/
obj.rs

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
use super::{Context, Interceptor, InterceptorFuture};
use crate::{body::AsyncBody, error::Error};
use http::Request;

/// Type-erased interceptor object.
pub(crate) struct InterceptorObj(Box<dyn DynInterceptor>);

impl InterceptorObj {
    pub(crate) fn new(interceptor: impl Interceptor + 'static) -> Self {
        Self(Box::new(interceptor))
    }
}

impl Interceptor for InterceptorObj {
    type Err = Error;

    fn intercept<'a>(
        &'a self,
        request: Request<AsyncBody>,
        cx: Context<'a>,
    ) -> InterceptorFuture<'a, Self::Err> {
        self.0.dyn_intercept(request, cx)
    }
}

/// Object-safe version of the interceptor used for type erasure. Implementation
/// detail of [`InterceptorObj`].
trait DynInterceptor: Send + Sync {
    fn dyn_intercept<'a>(
        &'a self,
        request: Request<AsyncBody>,
        cx: Context<'a>,
    ) -> InterceptorFuture<'a, Error>;
}

impl<I: Interceptor> DynInterceptor for I {
    fn dyn_intercept<'a>(
        &'a self,
        request: Request<AsyncBody>,
        cx: Context<'a>,
    ) -> InterceptorFuture<'a, Error> {
        Box::pin(async move { self.intercept(request, cx).await.map_err(Error::from_any) })
    }
}