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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

use crate::uri::fmt::UriDisplay;
use crate::uri::fmt::{self, Part};

/// Conversion trait for parameters used in [`uri!`] invocations.
///
/// # Overview
///
/// In addition to implementing [`UriDisplay`], to use a custom type in a `uri!`
/// expression, the `FromUriParam` trait must be implemented. The `UriDisplay`
/// derive automatically generates _identity_ implementations of `FromUriParam`,
/// so in the majority of cases, as with `UriDisplay`, this trait is never
/// implemented manually.
///
/// In the rare case that `UriDisplay` is implemented manually, this trait, too,
/// must be implemented explicitly. In the majority of cases, implementation can
/// be automated. Rocket provides [`impl_from_uri_param_identity`] to generate
/// the _identity_ implementations automatically. For a type `T`, these are:
///
///   * `impl<P: Part> FromUriParam<P, T> for T`
///   * `impl<'x, P: Part> FromUriParam<P, &'x T> for T`
///   * `impl<'x, P: Part> FromUriParam<P, &'x mut T> for T`
///
/// See [`impl_from_uri_param_identity!`](crate::impl_from_uri_param_identity!)
/// for usage details.
///
/// # Code Generation
///
/// This trait is invoked once per expression passed into a [`uri!`] invocation.
/// In particular, for a route URI parameter of type `T` and a user-supplied
/// expression `e` of type `S`, `<T as FromUriParam<S>>::from_uri_param(e)` is
/// invoked. The returned value of type `T::Target` is used in place of the
/// user's value and rendered using its [`UriDisplay`] implementation.
///
/// This trait allows types that differ from the route URI parameter's types to
/// be used in their place at no cost. For instance, the following
/// implementation, provided by Rocket, allows an `&str` to be used in a `uri!`
/// invocation for route URI parameters declared as `String`:
///
/// ```rust
/// # extern crate rocket;
/// # use rocket::http::uri::fmt::{FromUriParam, Part};
/// # struct S;
/// # type String = S;
/// impl<'a, P: Part> FromUriParam<P, &'a str> for String {
///     type Target = &'a str;
/// #   fn from_uri_param(s: &'a str) -> Self::Target { "hi" }
/// }
/// ```
///
/// Because the [`FromUriParam::Target`] type is the same as the input type, the
/// conversion is a no-op and free of cost, allowing an `&str` to be used in
/// place of a `String` without penalty.
///
/// # Provided Implementations
///
/// The following types have _identity_ implementations:
///
///    * `String`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `u8`, `u16`,
///      `u32`, `u64`, `u128`, `usize`, `f32`, `f64`, `bool`, `IpAddr`,
///      `Ipv4Addr`, `Ipv6Addr`, `&str`, `Cow<str>`
///
/// The following types have _identity_ implementations _only in [`Path`]_:
///
///   * `&Path`, `PathBuf`
///
/// The following types have _identity_ implementations _only in [`Query`]_:
///
///   * `Option<T>`, `Result<T, E>`
///
/// The following conversions are implemented for both paths and queries,
/// allowing a value of the type on the left to be used when a type on the right
/// is expected by a route:
///
///   * `&str` to `String`
///   * `String` to `&str`
///   * `T` to `Form<T>`
///
/// The following conversions are implemented _only in [`Path`]_:
///
///   * `&str` to `&Path`
///   * `&str` to `PathBuf`
///   * `PathBuf` to `&Path`
///   * `T` to `Option<T>`
///   * `T` to `Result<T, E>`
///
/// The following conversions are implemented _only in [`Query`]_:
///
///   * `Option<T>` to `Result<T, E>` (for any `E`)
///   * `Result<T, E>` to `Option<T>` (for any `E`)
///
/// See [Foreign Impls](#foreign-impls) for all provided implementations.
///
/// # Implementing
///
/// This trait should only be implemented when you'd like to allow a type
/// different from the route's declared type to be used in its place in a `uri!`
/// invocation. For instance, if the route has a type of `T` and you'd like to
/// use a type of `S` in a `uri!` invocation, you'd implement `FromUriParam<P,
/// T> for S` where `P` is `Path` for conversions valid in the path part of a
/// URI, `Uri` for conversions valid in the query part of a URI, or `P: Part`
/// when a conversion is valid in either case.
///
/// This is typically only warranted for owned-value types with corresponding
/// reference types: `String` and `&str`, for instance. In this case, it's
/// desirable to allow an `&str` to be used in place of a `String`.
///
/// When implementing `FromUriParam`, be aware that Rocket will use the
/// [`UriDisplay`] implementation of [`FromUriParam::Target`], _not_ of the
/// source type. Incorrect implementations can result in creating unsafe URIs.
///
/// # Example
///
/// The following example implements `FromUriParam<Query, (&str, &str)>` for a
/// `User` type. The implementation allows an `(&str, &str)` type to be used in
/// a `uri!` invocation where a `User` type is expected in the query part of the
/// URI.
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use std::fmt;
///
/// use rocket::http::uri::fmt::{Formatter, UriDisplay, FromUriParam, Query};
///
/// #[derive(FromForm)]
/// struct User<'a> {
///     name: &'a str,
///     nickname: String,
/// }
///
/// impl UriDisplay<Query> for User<'_> {
///     fn fmt(&self, f: &mut Formatter<Query>) -> fmt::Result {
///         f.write_named_value("name", &self.name)?;
///         f.write_named_value("nickname", &self.nickname)
///     }
/// }
///
/// impl<'a, 'b> FromUriParam<Query, (&'a str, &'b str)> for User<'a> {
///     type Target = User<'a>;
///
///     fn from_uri_param((name, nickname): (&'a str, &'b str)) -> User<'a> {
///         User { name: name.into(), nickname: nickname.to_string() }
///     }
/// }
/// ```
///
/// With these implementations, the following typechecks:
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// # use std::fmt;
/// # use rocket::http::uri::fmt::{Formatter, UriDisplay, FromUriParam, Query};
/// #
/// # #[derive(FromForm)]
/// # struct User<'a> { name: &'a str, nickname: String, }
/// #
/// # impl UriDisplay<Query> for User<'_> {
/// #     fn fmt(&self, f: &mut Formatter<Query>) -> fmt::Result {
/// #         f.write_named_value("name", &self.name)?;
/// #         f.write_named_value("nickname", &self.nickname)
/// #     }
/// # }
/// #
/// # impl<'a, 'b> FromUriParam<Query, (&'a str, &'b str)> for User<'a> {
/// #     type Target = User<'a>;
/// #     fn from_uri_param((name, nickname): (&'a str, &'b str)) -> User<'a> {
/// #         User { name: name.into(), nickname: nickname.to_string() }
/// #     }
/// # }
/// #
/// #[post("/<name>?<user..>")]
/// fn some_route(name: &str, user: User<'_>)  { /* .. */ }
///
/// let uri = uri!(some_route(name = "hey", user = ("Robert Mike", "Bob")));
/// assert_eq!(uri.path(), "/hey");
/// assert_eq!(uri.query().unwrap(), "name=Robert%20Mike&nickname=Bob");
/// ```
///
/// [`uri!`]: rocket::uri
/// [`FromUriParam::Target`]: crate::uri::fmt::FromUriParam::Target
/// [`Path`]: crate::uri::fmt::Path
/// [`Query`]: crate::uri::fmt::Query
pub trait FromUriParam<P: Part, T> {
    /// The resulting type of this conversion.
    type Target: UriDisplay<P>;

    /// Converts a value of type `T` into a value of type `Self::Target`. The
    /// resulting value of type `Self::Target` will be rendered into a URI using
    /// its [`UriDisplay`] implementation.
    fn from_uri_param(param: T) -> Self::Target;
}

#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! impl_conversion_ref {
    ($(($($l:tt)+) $A:ty => $B:ty),* $(,)?) => (
        impl_conversion_ref!(@_ $(($($l)+,) $A => $B),*);
    );

    ($($A:ty => $B:ty),* $(,)?) => (
        impl_conversion_ref!(@_ $(() $A => $B),*);
    );

    (@_ $(($($l:tt)*) $A:ty => $B:ty),* $(,)?) => ($(
        impl_conversion_ref!([P] ($($l)* P: $crate::uri::fmt::Part) $A => $B);
    )*);

    ($([$P:ty] ($($l:tt)*) $A:ty => $B:ty),* $(,)?) => ($(
        impl_conversion_ref!(@_ [$P] ($($l)*) $A => $B);
        impl_conversion_ref!(@_ [$P] ('x, $($l)*) &'x $A => $B);
        impl_conversion_ref!(@_ [$P] ('x, $($l)*) &'x mut $A => $B);
    )*);

    ($([$P:ty] $A:ty => $B:ty),* $(,)?) => ( impl_conversion_ref!($([$P] () $A => $B),*););

    (@_ [$P:ty] ($($l:tt)*) $A:ty => $B:ty) => (
        impl<$($l)*> $crate::uri::fmt::FromUriParam<$P, $A> for $B {
            type Target = $A;
            #[inline(always)] fn from_uri_param(param: $A) -> $A { param }
        }
    );
}

/// Macro to automatically generate _identity_ [`FromUriParam`] trait
/// implementations.
///
/// For a type `T`, the _identity_ implementations of `FromUriParam` are:
///
///   * `impl<P: Part> FromUriParam<P, T> for T`
///   * `impl<'x> FromUriParam<P, &'x T> for T`
///   * `impl<'x> FromUriParam<P, &'x mut T> for T`
///
/// where `P` is one of:
///
///   * `P: Part` (the generic `P`)
///   * [`Path`]
///   * [`Query`]
///
/// This macro can be invoked in four ways:
///
///   1. `impl_from_uri_param_identity!(Type);`
///
///      Generates the three _identity_ implementations for the generic `P`.
///
///      * Example: `impl_from_uri_param_identity!(MyType);`
///      * Generates: `impl<P: Part> FromUriParam<P, _> for MyType { ... }`
///
///   2. `impl_from_uri_param_identity!((generics*) Type);`
///
///      Generates the three _identity_ implementations for the generic `P`,
///      adding the tokens `generics` to the `impl` generics of the generated
///      implementation.
///
///      * Example: `impl_from_uri_param_identity!(('a) MyType<'a>);`
///      * Generates: `impl<'a, P: Part> FromUriParam<P, _> for MyType<'a> { ... }`
///
///   3. `impl_from_uri_param_identity!([Part] Type);`
///
///      Generates the three _identity_ implementations for the `Part`
///      `Part`, where `Part` is a path to [`Path`] or [`Query`].
///
///      * Example: `impl_from_uri_param_identity!([Path] MyType);`
///      * Generates: `impl FromUriParam<Path, _> for MyType { ... }`
///
///   4. `impl_from_uri_param_identity!([Part] (generics*) Type);`
///
///      See 2 and 3.
///
///      * Example: `impl_from_uri_param_identity!([Path] ('a) MyType<'a>);`
///      * Generates: `impl<'a> FromUriParam<Path, _> for MyType<'a> { ... }`
///
/// [`FromUriParam`]: crate::uri::fmt::FromUriParam
/// [`Path`]: crate::uri::fmt::Path
/// [`Query`]: crate::uri::fmt::Query
#[macro_export(local_inner_macros)]
macro_rules! impl_from_uri_param_identity {
    ($(($($l:tt)*) $T:ty),* $(,)?) => ($( impl_conversion_ref!(($($l)*) $T => $T); )*);
    ($([$P:ty] ($($l:tt)*) $T:ty),* $(,)?) => ($( impl_conversion_ref!([$P] ($($l)*) $T => $T); )*);
    ($([$P:ty] $T:ty),* $(,)?) => ($( impl_conversion_ref!([$P] $T => $T); )*);
    ($($T:ty),* $(,)?) => ($( impl_conversion_ref!($T => $T); )*);
}

use std::borrow::Cow;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::num::{
    NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128,
    NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128,
};

impl_from_uri_param_identity! {
    String,
    i8, i16, i32, i64, i128, isize,
    u8, u16, u32, u64, u128, usize,
    f32, f64, bool,
    IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6,
    NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128,
    NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128,
    time::Date, time::Time, time::PrimitiveDateTime,
}

impl_from_uri_param_identity! {
    ('a) &'a str,
    ('a) Cow<'a, str>
}

impl_conversion_ref! {
    ('a) &'a str => String,

    ('a) String => &'a str
}

impl_from_uri_param_identity!([fmt::Path] ('a) &'a Path);
impl_from_uri_param_identity!([fmt::Path] PathBuf);

impl_conversion_ref! {
    [fmt::Path] ('a) &'a Path => PathBuf,
    [fmt::Path] ('a) PathBuf => &'a Path
}

/// A no cost conversion allowing an `&str` to be used in place of a `PathBuf`.
impl<'a> FromUriParam<fmt::Path, &'a str> for PathBuf {
    type Target = &'a Path;

    #[inline(always)]
    fn from_uri_param(param: &'a str) -> &'a Path {
        Path::new(param)
    }
}

/// A no cost conversion allowing an `&&str` to be used in place of a `PathBuf`.
impl<'a, 'b> FromUriParam<fmt::Path, &'a &'b str> for PathBuf {
    type Target = &'b Path;

    #[inline(always)]
    fn from_uri_param(param: &'a &'b str) -> &'b Path {
        Path::new(*param)
    }
}

/// A no cost conversion allowing any `T` to be used in place of an `Option<T>`.
impl<A, T: FromUriParam<fmt::Path, A>> FromUriParam<fmt::Path, A> for Option<T> {
    type Target = T::Target;

    #[inline(always)]
    fn from_uri_param(param: A) -> Self::Target {
        T::from_uri_param(param)
    }
}

/// A no cost conversion allowing `T` to be used in place of an `Result<T, E>`.
impl<A, E, T: FromUriParam<fmt::Path, A>> FromUriParam<fmt::Path, A> for Result<T, E> {
    type Target = T::Target;

    #[inline(always)]
    fn from_uri_param(param: A) -> Self::Target {
        T::from_uri_param(param)
    }
}

impl<A, T: FromUriParam<fmt::Query, A>> FromUriParam<fmt::Query, Option<A>> for Option<T> {
    type Target = Option<T::Target>;

    #[inline(always)]
    fn from_uri_param(param: Option<A>) -> Self::Target {
        param.map(T::from_uri_param)
    }
}

impl<A, E, T: FromUriParam<fmt::Query, A>> FromUriParam<fmt::Query, Option<A>> for Result<T, E> {
    type Target = Option<T::Target>;

    #[inline(always)]
    fn from_uri_param(param: Option<A>) -> Self::Target {
        param.map(T::from_uri_param)
    }
}

impl<A, E, T: FromUriParam<fmt::Query, A>> FromUriParam<fmt::Query, Result<A, E>> for Result<T, E> {
    type Target = Result<T::Target, E>;

    #[inline(always)]
    fn from_uri_param(param: Result<A, E>) -> Self::Target {
        param.map(T::from_uri_param)
    }
}

impl<A, E, T: FromUriParam<fmt::Query, A>> FromUriParam<fmt::Query, Result<A, E>> for Option<T> {
    type Target = Result<T::Target, E>;

    #[inline(always)]
    fn from_uri_param(param: Result<A, E>) -> Self::Target {
        param.map(T::from_uri_param)
    }
}

macro_rules! impl_map_conversion {
    ($From:ident => $To:ident) => (
        impl<K, V, A, B> FromUriParam<fmt::Query, $From<A, B>> for $To<K, V>
            where A: UriDisplay<fmt::Query>, K: FromUriParam<fmt::Query, A>,
                  B: UriDisplay<fmt::Query>, V: FromUriParam<fmt::Query, B>
        {
            type Target = $From<A, B>;

            #[inline(always)]
            fn from_uri_param(param: $From<A, B>) -> Self::Target {
                param
            }
        }
    );

    (& $([$mut:tt])? $From:ident => $To:ident) => (
        impl<'a, K, V, A, B> FromUriParam<fmt::Query, &'a $($mut)? $From<A, B>> for $To<K, V>
            where A: UriDisplay<fmt::Query>, K: FromUriParam<fmt::Query, A>,
                  B: UriDisplay<fmt::Query>, V: FromUriParam<fmt::Query, B>
        {
            type Target = &'a $From<A, B>;

            #[inline(always)]
            fn from_uri_param(param: &'a $($mut)? $From<A, B>) -> Self::Target {
                param
            }
        }
    );
}

impl_map_conversion!(HashMap => HashMap);
impl_map_conversion!(HashMap => BTreeMap);
impl_map_conversion!(BTreeMap => BTreeMap);
impl_map_conversion!(BTreeMap => HashMap);

impl_map_conversion!(&HashMap => HashMap);
impl_map_conversion!(&HashMap => BTreeMap);
impl_map_conversion!(&BTreeMap => BTreeMap);
impl_map_conversion!(&BTreeMap => HashMap);

impl_map_conversion!(&[mut] HashMap => HashMap);
impl_map_conversion!(&[mut] HashMap => BTreeMap);
impl_map_conversion!(&[mut] BTreeMap => BTreeMap);
impl_map_conversion!(&[mut] BTreeMap => HashMap);