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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use axol_http::{request::RequestPartsRef, Body};

use crate::{Error, FromRequestParts, Result};

mod private {
    #[derive(Debug, Clone, Copy)]
    pub enum ViaParts {}

    #[derive(Debug, Clone, Copy)]
    pub enum ViaRequest {}
}

#[async_trait::async_trait]
pub trait FromRequest<'a, M = private::ViaRequest>: Sized + Send + Sync + 'a {
    async fn from_request(request: RequestPartsRef<'a>, body: Body) -> Result<Self>;
}

#[async_trait::async_trait]
impl<'a, R: FromRequestParts<'a>> FromRequest<'a, private::ViaParts> for R {
    async fn from_request(request: RequestPartsRef<'a>, _: Body) -> Result<Self> {
        Self::from_request_parts(request).await
    }
}

#[async_trait::async_trait]
impl<'a, T: FromRequest<'a>> FromRequest<'a> for Option<T> {
    async fn from_request(request: RequestPartsRef<'a>, body: Body) -> Result<Self> {
        Ok(T::from_request(request, body).await.ok())
    }
}

#[async_trait::async_trait]
impl<'a, T: FromRequest<'a>> FromRequest<'a> for Result<T> {
    async fn from_request(request: RequestPartsRef<'a>, body: Body) -> Result<Self> {
        Ok(T::from_request(request, body).await)
    }
}

#[async_trait::async_trait]
impl<'a> FromRequest<'a> for Body {
    async fn from_request(_: RequestPartsRef<'a>, body: Body) -> Result<Self> {
        Ok(body)
    }
}

#[async_trait::async_trait]
impl<'a> FromRequest<'a> for Vec<u8> {
    async fn from_request(_: RequestPartsRef<'a>, body: Body) -> Result<Self> {
        Ok(body.collect().await?)
    }
}

#[async_trait::async_trait]
impl<'a> FromRequest<'a> for String {
    async fn from_request(_: RequestPartsRef<'a>, body: Body) -> Result<Self> {
        String::from_utf8(body.collect().await?).map_err(|_| Error::BadUtf8)
    }
}

macro_rules! impl_from_request {
    (
        [$($ty:ident),*], $last:ident
    ) => {
        #[async_trait::async_trait]
        #[allow(non_snake_case, unused_mut, unused_variables)]
        impl<'a, $($ty,)* $last> FromRequest<'a> for ($($ty,)* $last,)
        where
            $( $ty: FromRequestParts<'a>, )*
            $last: FromRequest<'a>,
        {
            async fn from_request(request: RequestPartsRef<'a>, body: Body) -> Result<Self> {
                $(
                    let $ty = $ty::from_request_parts(request).await?;
                )*

                let $last = $last::from_request(request, body).await?;

                Ok(($($ty,)* $last,))
            }
        }
    };
}

all_the_tuples!(impl_from_request);