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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
//! Client headers.
//!
//! This module includes everything you need to build valid header entries.

use std::marker::PhantomData;

pub use reqwest::header::{HeaderName, HeaderValue, InvalidHeaderValue, ToStrError};

/// [`HeaderEntry`] attribute identifying those that have been prevalidated.
///
/// The specification of a header entry identified by this discriminant doesn't return a [`Result`].
///
/// ### Example
///
/// This example adds the header name `custom-header` and value `custom:some-value`.
///
/// ```
/// use unc_jsonrpc_client::{
///     header::{HeaderEntry, HeaderValue, Prevalidated},
///     methods, JsonRpcClient,
/// };
///
/// struct CustomHeader(HeaderValue);
///
/// impl HeaderEntry<Prevalidated> for CustomHeader {
///     type HeaderName = &'static str;
///     type HeaderValue = HeaderValue;
///
///     fn header_name(&self) -> &Self::HeaderName {
///         &"custom-header"
///     }
///
///     fn header_pair(self) -> (Self::HeaderName, Self::HeaderValue) {
///         ("custom-header", self.0)
///     }
/// }
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// let header_value = HeaderValue::try_from("custom:some-value")?; // <- error handling here
///
/// let client = JsonRpcClient::connect("https://rpc.testnet.unc.org").header(CustomHeader(header_value));
/// # Ok(())
/// # }
pub struct Prevalidated {
    _priv: (),
}

/// [`HeaderEntry`] attribute identifying those that need to be validated.
///
/// The specification of a header entry identified by this discriminant will return a [`Result`].
///
/// ### Example
///
/// This example adds the header name `custom-header` and value `custom:some-value`.
///
/// ```
/// # use std::{fmt, error::Error};
/// use unc_jsonrpc_client::{
///     header::{HeaderEntry, HeaderValue, Postvalidated},
///     methods, JsonRpcClient,
/// };
///
/// struct CustomValue(&'static str);
///
/// struct CustomHeader(CustomValue);
///
/// # #[derive(Debug)]
/// struct CustomError;
/// # impl Error for CustomError {}
/// # impl fmt::Display for CustomError {
/// #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// #         write!(f, "custom error")
/// #     }
/// # }
///
/// impl TryFrom<CustomValue> for HeaderValue {
///     type Error = CustomError;
///
///     fn try_from(v: CustomValue) -> Result<Self, Self::Error> {
///         HeaderValue::try_from(format!("custom:{}", v.0)).map_err(|_| CustomError)
///     }
/// }
///
/// impl HeaderEntry<Postvalidated<CustomError>> for CustomHeader {
///     type HeaderName = &'static str;
///     type HeaderValue = CustomValue;
///
///     fn header_name(&self) -> &Self::HeaderName {
///         &"custom-header"
///     }
///
///     fn header_pair(self) -> (Self::HeaderName, Self::HeaderValue) {
///         ("custom-header", self.0)
///     }
/// }
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// let client = JsonRpcClient::connect("https://rpc.testnet.unc.org")
///     .header(CustomHeader(CustomValue("some-value")))?; // <- error handling here
/// # Ok(())
/// # }
pub struct Postvalidated<E> {
    _priv: PhantomData<E>,
}

/// Trait for identifying valid header entries.
///
/// Header entries are distinguished by their discrimimants, (See [HeaderEntryDiscriminant]).
pub trait HeaderEntry<D = Prevalidated>: Sized
where
    D: HeaderEntryDiscriminant<Self>,
{
    type HeaderName;
    type HeaderValue;

    fn header_name(&self) -> &Self::HeaderName;
    fn header_pair(self) -> (Self::HeaderName, Self::HeaderValue);
}

pub use discriminant::HeaderEntryDiscriminant;
mod discriminant {
    use reqwest::header::IntoHeaderName;

    use super::{super::JsonRpcClient, HeaderEntry, HeaderValue, Postvalidated, Prevalidated};

    pub trait Sealed {}

    /// Trait for defining a [`HeaderEntry`]'s application on a client.
    pub trait HeaderEntryDiscriminant<H>: Sealed {
        type Output;

        fn apply(client: JsonRpcClient, entry: H) -> Self::Output;
    }

    impl Sealed for Prevalidated {}
    impl<T> HeaderEntryDiscriminant<T> for Prevalidated
    where
        T: HeaderEntry<Self, HeaderValue = HeaderValue>,
        T::HeaderName: IntoHeaderName,
    {
        type Output = JsonRpcClient;

        fn apply(mut client: JsonRpcClient, entry: T) -> Self::Output {
            let (k, v) = entry.header_pair();
            client.headers.insert(k, v);
            client
        }
    }

    impl<E> Sealed for Postvalidated<E> {}
    impl<T, E> HeaderEntryDiscriminant<T> for Postvalidated<E>
    where
        T: HeaderEntry<Self>,
        T::HeaderName: IntoHeaderName,
        T::HeaderValue: TryInto<HeaderValue, Error = E>,
    {
        type Output = Result<JsonRpcClient, E>;

        fn apply(mut client: JsonRpcClient, entry: T) -> Self::Output {
            let (k, v) = entry.header_pair();
            client.headers.insert(k, v.try_into()?);
            Ok(client)
        }
    }

    impl<N: IntoHeaderName> HeaderEntry<Prevalidated> for (N, HeaderValue) {
        type HeaderName = N;
        type HeaderValue = HeaderValue;

        fn header_name(&self) -> &Self::HeaderName {
            &self.0
        }

        fn header_pair(self) -> (Self::HeaderName, Self::HeaderValue) {
            self
        }
    }

    impl<N, V> HeaderEntry<Postvalidated<V::Error>> for (N, V)
    where
        N: IntoHeaderName,
        V: TryInto<HeaderValue>,
    {
        type HeaderName = N;
        type HeaderValue = V;

        fn header_name(&self) -> &Self::HeaderName {
            &self.0
        }

        fn header_pair(self) -> (Self::HeaderName, Self::HeaderValue) {
            self
        }
    }
}