rocket/form/from_form.rs
1use std::borrow::Cow;
2use std::collections::{HashMap, BTreeMap};
3use std::hash::Hash;
4use std::sync::Arc;
5
6use either::Either;
7use indexmap::IndexMap;
8
9use crate::form::prelude::*;
10use crate::http::uncased::AsUncased;
11
12/// Trait implemented by form guards: types parseable from HTTP forms.
13///
14/// Only form guards that are _collections_, that is, collect more than one form
15/// field while parsing, should implement `FromForm`. All other types should
16/// implement [`FromFormField`] instead, which offers a simplified interface to
17/// parsing a single form field.
18///
19/// For a gentle introduction to forms in Rocket, see the [forms guide].
20///
21/// # Form Guards
22///
23/// A form guard is a guard that operates on form fields, typically those with a
24/// particular name prefix. Form guards validate and parse form field data via
25/// implementations of `FromForm`. In other words, a type is a form guard _iff_
26/// it implements `FromForm`.
27///
28/// Form guards are used as the inner type of the [`Form`] data guard:
29///
30/// ```rust
31/// # use rocket::post;
32/// use rocket::form::Form;
33///
34/// # type FormGuard = String;
35/// #[post("/submit", data = "<var>")]
36/// fn submit(var: Form<FormGuard>) { /* ... */ }
37/// ```
38///
39/// # Deriving
40///
41/// This trait can, and largely _should_, be automatically derived. When
42/// deriving `FromForm`, every field in the structure must implement
43/// [`FromForm`]. Form fields with the struct field's name are [shifted] and
44/// then pushed to the struct field's `FromForm` parser.
45///
46/// [shifted]: NameView::shift()
47///
48/// ```rust
49/// use rocket::form::FromForm;
50///
51/// #[derive(FromForm)]
52/// struct TodoTask<'r> {
53/// #[field(validate = len(1..))]
54/// description: &'r str,
55/// #[field(name = "done")]
56/// completed: bool
57/// }
58/// ```
59///
60/// For full details on deriving `FromForm`, see the [`FromForm` derive].
61///
62/// [`Form`]: crate::form::Form
63/// [`FromForm`]: crate::form::FromForm
64/// [`FromForm` derive]: derive@crate::FromForm
65/// [FromFormField]: crate::form::FromFormField
66/// [`shift()`ed]: NameView::shift()
67/// [`key()`]: NameView::key()
68/// [forms guide]: https://rocket.rs/v0.6-rc/guide/requests/#forms
69///
70/// # Parsing Strategy
71///
72/// Form parsing is either _strict_ or _lenient_, controlled by
73/// [`Options::strict`]. A _strict_ parse errors when there are missing or extra
74/// fields, while a _lenient_ parse allows both, providing there is a
75/// [`default()`](FromForm::default()) in the case of a missing field.
76///
77/// Most type inherit their strategy on [`FromForm::init()`], but some types
78/// like `Option` override the requested strategy. The strategy can also be
79/// overwritten manually, per-field or per-value, by using the [`Strict`] or
80/// [`Lenient`] form guard:
81///
82/// ```rust
83/// use rocket::form::{self, FromForm, Strict, Lenient};
84///
85/// #[derive(FromForm)]
86/// struct TodoTask<'r> {
87/// strict_bool: Strict<bool>,
88/// lenient_inner_option: Option<Lenient<bool>>,
89/// strict_inner_result: form::Result<'r, Strict<bool>>,
90/// }
91/// ```
92///
93/// # Defaults
94///
95/// A form guard may have a _default_ which is used in case of a missing field
96/// when parsing is _lenient_. When parsing is strict, all errors, including
97/// missing fields, are propagated directly.
98///
99/// # Provided Implementations
100///
101/// Rocket implements `FromForm` for many common types. As a result, most
102/// applications will never need a custom implementation of `FromForm` or
103/// `FromFormField`. Their behavior is documented in the table below.
104///
105/// | Type | Strategy | Default | Data | Value | Notes |
106/// |------------------------|-------------|-------------------|--------|--------|----------------------------------------------------|
107/// | [`Strict<T>`] | **strict** | if `strict` `T` | if `T` | if `T` | `T: FromForm` |
108/// | [`Lenient<T>`] | **lenient** | if `lenient` `T` | if `T` | if `T` | `T: FromForm` |
109/// | `Option<T>` | **strict** | `None` | if `T` | if `T` | Infallible, `T: FromForm` |
110/// | [`Result<T>`] | _inherit_ | `T::finalize()` | if `T` | if `T` | Infallible, `T: FromForm` |
111/// | `Vec<T>` | _inherit_ | `vec![]` | if `T` | if `T` | `T: FromForm` |
112/// | [`HashMap<K, V>`] | _inherit_ | `HashMap::new()` | if `V` | if `V` | `K: FromForm + Eq + Hash`, `V: FromForm` |
113/// | [`BTreeMap<K, V>`] | _inherit_ | `BTreeMap::new()` | if `V` | if `V` | `K: FromForm + Ord`, `V: FromForm` |
114/// | [`Range<T>`] | _inherit_ | **no default** | if `T` | if `T` | `T: FromForm`, expects `start`, `end` fields |
115/// | [`RangeFrom<T>`] | _inherit_ | **no default** | if `T` | if `T` | `T: FromForm`, expects `start` field |
116/// | [`RangeTo<T>`] | _inherit_ | **no default** | if `T` | if `T` | `T: FromForm`, expects `end` field |
117/// | [`RangeToInclusive<T>`]| _inherit_ | **no default** | if `T` | if `T` | `T: FromForm`, expects `end` field |
118/// | `bool` | _inherit_ | `false` | No | Yes | `"yes"/"on"/"true"`, `"no"/"off"/"false"` |
119/// | (un)signed int | _inherit_ | **no default** | No | Yes | `{u,i}{size,8,16,32,64,128}` |
120/// | _nonzero_ int | _inherit_ | **no default** | No | Yes | `NonZero{I,U}{size,8,16,32,64,128}` |
121/// | float | _inherit_ | **no default** | No | Yes | `f{32,64}` |
122/// | `&str` | _inherit_ | **no default** | Yes | Yes | Percent-decoded. Data limit `string` applies. |
123/// | `&[u8]` | _inherit_ | **no default** | Yes | Yes | Raw bytes. Data limit `bytes` applies. |
124/// | `String` | _inherit_ | **no default** | Yes | Yes | Exactly `&str`, but owned. Prefer `&str`. |
125/// | IP Address | _inherit_ | **no default** | No | Yes | [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`] |
126/// | Socket Address | _inherit_ | **no default** | No | Yes | [`SocketAddr`], [`SocketAddrV4`], [`SocketAddrV6`] |
127/// | [`TempFile`] | _inherit_ | **no default** | Yes | Yes | Data limits apply. See [`TempFile`]. |
128/// | [`Capped<C>`] | _inherit_ | **no default** | Yes | Yes | `C` is `&str`, `String`, `&[u8]` or `TempFile`. |
129/// | [`time::Date`] | _inherit_ | **no default** | No | Yes | `%F` (`YYYY-MM-DD`). HTML "date" input. |
130/// | [`time::DateTime`] | _inherit_ | **no default** | No | Yes | `%FT%R` or `%FT%T` (`YYYY-MM-DDTHH:MM[:SS]`) |
131/// | [`time::Time`] | _inherit_ | **no default** | No | Yes | `%R` or `%T` (`HH:MM[:SS]`) |
132///
133/// [`Result<T>`]: crate::form::Result
134/// [`Strict<T>`]: crate::form::Strict
135/// [`Lenient<T>`]: crate::form::Lenient
136/// [`HashMap<K, V>`]: std::collections::HashMap
137/// [`BTreeMap<K, V>`]: std::collections::BTreeMap
138/// [`TempFile`]: crate::fs::TempFile
139/// [`Capped<C>`]: crate::data::Capped
140/// [`time::DateTime`]: time::PrimitiveDateTime
141/// [`IpAddr`]: std::net::IpAddr
142/// [`Ipv4Addr`]: std::net::Ipv4Addr
143/// [`Ipv6Addr`]: std::net::Ipv6Addr
144/// [`SocketAddr`]: std::net::SocketAddr
145/// [`SocketAddrV4`]: std::net::SocketAddrV4
146/// [`SocketAddrV6`]: std::net::SocketAddrV6
147/// [`Range<T>`]: https://doc.rust-lang.org/stable/std/ops/struct.Range.html
148/// [`RangeFrom<T>`]: https://doc.rust-lang.org/stable/std/ops/struct.RangeFrom.html
149/// [`RangeTo<T>`]: https://doc.rust-lang.org/stable/std/ops/struct.RangeTo.html
150/// [`RangeToInclusive<T>`]: https://doc.rust-lang.org/stable/std/ops/struct.RangeToInclusive.html
151///
152/// ## Additional Notes
153///
154/// * **`Vec<T>` where `T: FromForm`**
155///
156/// Parses a sequence of `T`'s. A new `T` is created whenever the field
157/// name's key changes or is empty; the previous `T` is finalized and errors
158/// are stored. While the key remains the same and non-empty, form values
159/// are pushed to the current `T` after being shifted. All collected errors
160/// are returned at finalization, if any, or the successfully created vector
161/// is returned.
162///
163/// * **`HashMap<K, V>` where `K: FromForm + Eq + Hash`, `V: FromForm`**
164///
165/// **`BTreeMap<K, V>` where `K: FromForm + Ord`, `V: FromForm`**
166///
167/// Parses a sequence of `(K, V)`'s. A new pair is created for every unique
168/// first index of the key.
169///
170/// If the key has only one index (`map[index]=value`), the index itself is
171/// pushed to `K`'s parser and the remaining shifted field is pushed to
172/// `V`'s parser.
173///
174/// If the key has two indices (`map[k:index]=value` or
175/// `map[v:index]=value`), the first index must start with `k` or `v`. If
176/// the first index starts with `k`, the shifted field is pushed to `K`'s
177/// parser. If the first index starts with `v`, the shifted field is pushed
178/// to `V`'s parser. If the first index is anything else, an error is
179/// created for the offending form field.
180///
181/// Errors are collected as they occur. Finalization finalizes all pairs and
182/// returns errors, if any, or the map.
183///
184/// * **`bool`**
185///
186/// Parses as `false` for missing values (when lenient) and case-insensitive
187/// values of `off`, `false`, and `no`. Parses as `true` for values of `on`,
188/// `true`, `yes`, and the empty value. Failed to parse otherwise.
189///
190/// * **[`time::DateTime`]**
191///
192/// Parses a date in `%FT%R` or `%FT%T` format, that is, `YYYY-MM-DDTHH:MM`
193/// or `YYYY-MM-DDTHH:MM:SS`. This is the `"datetime-local"` HTML input type
194/// without support for the millisecond variant.
195///
196/// * **[`time::Time`]**
197///
198/// Parses a time in `%R` or `%T` format, that is, `HH:MM` or `HH:MM:SS`.
199/// This is the `"time"` HTML input type without support for the millisecond
200/// variant.
201///
202/// # Push Parsing
203///
204/// `FromForm` describes a push-based parser for Rocket's [field wire format].
205/// Fields are preprocessed into either [`ValueField`]s or [`DataField`]s which
206/// are then pushed to the parser in [`FromForm::push_value()`] or
207/// [`FromForm::push_data()`], respectively. Both url-encoded forms and
208/// multipart forms are supported. All url-encoded form fields are preprocessed
209/// as [`ValueField`]s, and their names and values are percent-decoded.
210///
211/// Multipart fields with neither a Content-Type nor a file name are value
212/// fields if their contents are valid UTF-8. All other multipart fields are
213/// data fields. Multipart values preserve their UTF-8 contents, including a
214/// leading byte order mark (BOM).
215///
216/// Data fields are subject to the receiving guard's data limit. For example,
217/// strings use `string`, byte slices use `bytes`, and [`TempFile`] uses `file`
218/// or `file/$ext`. See [`Limits`] for defaults.
219///
220/// [`TempFile`]: crate::fs::TempFile
221/// [`Limits`]: crate::data::Limits
222///
223/// [field wire format]: crate::form#field-wire-format
224///
225/// Parsing is split into 3 stages. After preprocessing, the three stages are:
226///
227/// 1. **Initialization.** The type sets up a context for later `push`es.
228///
229/// ```rust
230/// # use rocket::form::prelude::*;
231/// # struct Foo;
232/// use rocket::form::Options;
233///
234/// # #[rocket::async_trait]
235/// # impl<'r> FromForm<'r> for Foo {
236/// # type Context = std::convert::Infallible;
237/// fn init(opts: Options) -> Self::Context {
238/// todo!("return a context for storing parse state")
239/// }
240/// # fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) { todo!() }
241/// # async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) { todo!() }
242/// # fn finalize(ctxt: Self::Context) -> Result<'r, Self> { todo!() }
243/// # }
244/// ```
245///
246/// 2. **Push.** The structure is repeatedly pushed form fields; the latest
247/// context is provided with each `push`. If the structure contains
248/// children, it uses the first [`key()`] to identify a child to which it
249/// then `push`es the remaining `field` to, likely with a [`shift()`ed]
250/// name. Otherwise, the structure parses the `value` itself. The context
251/// is updated as needed.
252///
253/// ```rust
254/// # use rocket::form::prelude::*;
255/// # struct Foo;
256/// use rocket::form::{ValueField, DataField};
257///
258/// # #[rocket::async_trait]
259/// # impl<'r> FromForm<'r> for Foo {
260/// # type Context = std::convert::Infallible;
261/// # fn init(opts: Options) -> Self::Context { todo!() }
262/// fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) {
263/// todo!("modify context as necessary for `field`")
264/// }
265///
266/// async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) {
267/// todo!("modify context as necessary for `field`")
268/// }
269/// # fn finalize(ctxt: Self::Context) -> Result<'r, Self> { todo!() }
270/// # }
271/// ```
272///
273/// 3. **Finalization.** The structure is informed that there are no further
274/// fields. It systemizes the effects of previous `push`es via its context
275/// to return a parsed structure or generate [`Errors`].
276///
277/// ```rust
278/// # use rocket::form::prelude::*;
279/// # struct Foo;
280/// use rocket::form::Result;
281///
282/// # #[rocket::async_trait]
283/// # impl<'r> FromForm<'r> for Foo {
284/// # type Context = std::convert::Infallible;
285/// # fn init(opts: Options) -> Self::Context { todo!() }
286/// # fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) { todo!() }
287/// # async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) { todo!() }
288/// fn finalize(ctxt: Self::Context) -> Result<'r, Self> {
289/// todo!("inspect context to generate `Self` or `Errors`")
290/// }
291/// # }
292/// ```
293///
294/// These three stages make up the entirety of the `FromForm` trait.
295///
296/// ## Nesting and [`NameView`]
297///
298/// Each field name key typically identifies a unique child of a structure. As
299/// such, when processed left-to-right, the keys of a field jointly identify a
300/// unique leaf of a structure. The value of the field typically represents the
301/// desired value of the leaf.
302///
303/// A [`NameView`] captures and simplifies this "left-to-right" processing of a
304/// field's name by exposing a sliding-prefix view into a name. A [`shift()`]
305/// shifts the view one key to the right. Thus, a `Name` of `a.b.c` when viewed
306/// through a new [`NameView`] is `a`. Shifted once, the view is `a.b`.
307/// [`key()`] returns the last (or "current") key in the view. A nested
308/// structure can thus handle a field with a `NameView`, operate on the
309/// [`key()`], [`shift()`] the `NameView`, and pass the field with the shifted
310/// `NameView` to the next processor which handles `b` and so on.
311///
312/// [`shift()`]: NameView::shift()
313/// [`key()`]: NameView::key()
314///
315/// ## A Simple Example
316///
317/// The following example uses `f1=v1&f2=v2` to illustrate field/value pairs
318/// `(f1, v2)` and `(f2, v2)`. This is the same encoding used to send HTML forms
319/// over HTTP, though Rocket's push-parsers are unaware of any specific
320/// encoding, dealing only with logical `field`s, `index`es, and `value`s.
321///
322/// ### A Single Field (`T: FormFormField`)
323///
324/// The simplest example parses a single value of type `T` from a string with an
325/// optional default value: this is `impl<T: FromFormField> FromForm for T`:
326///
327/// 1. **Initialization.** The context stores form options and an `Option` of
328/// `Result<T, form::Error>` for storing the `result` of parsing `T`, which
329/// is initially set to `None`.
330///
331/// ```rust
332/// use rocket::form::{self, FromFormField};
333///
334/// struct Context<'r, T: FromFormField<'r>> {
335/// opts: form::Options,
336/// result: Option<form::Result<'r, T>>,
337/// }
338///
339/// # impl<'r, T: FromFormField<'r>> Context<'r, T> {
340/// fn init(opts: form::Options) -> Context<'r, T> {
341/// Context { opts, result: None }
342/// }
343/// # }
344/// ```
345///
346/// 2. **Push.** If `ctxt.result` is `None`, `T` is parsed from `field`, and
347/// the result is stored in `context.result`. Otherwise a field has already
348/// been parsed and nothing is done.
349///
350/// ```rust
351/// # use rocket::form::{self, ValueField, FromFormField};
352/// # struct Context<'r, T: FromFormField<'r>> {
353/// # opts: form::Options,
354/// # result: Option<form::Result<'r, T>>,
355/// # }
356/// # impl<'r, T: FromFormField<'r>> Context<'r, T> {
357/// fn push_value(ctxt: &mut Context<'r, T>, field: ValueField<'r>) {
358/// if ctxt.result.is_none() {
359/// ctxt.result = Some(T::from_value(field));
360/// }
361/// }
362/// # }
363/// ```
364///
365/// 3. **Finalization.** If `ctxt.result` is `None`, parsing is lenient, and
366/// `T` has a default, the default is returned. Otherwise a `Missing` error
367/// is returned. If `ctxt.result` is `Some(v)`, the result `v` is returned.
368///
369/// ```rust
370/// # use rocket::form::{self, FromFormField, error::{Errors, ErrorKind}};
371/// # struct Context<'r, T: FromFormField<'r>> {
372/// # opts: form::Options,
373/// # result: Option<form::Result<'r, T>>,
374/// # }
375/// # impl<'r, T: FromFormField<'r>> Context<'r, T> {
376/// fn finalize(ctxt: Context<'r, T>) -> form::Result<'r, T> {
377/// match ctxt.result {
378/// Some(result) => result,
379/// None if ctxt.opts.strict => Err(Errors::from(ErrorKind::Missing)),
380/// None => match T::default() {
381/// Some(default) => Ok(default),
382/// None => Err(Errors::from(ErrorKind::Missing)),
383/// }
384/// }
385/// }
386/// # }
387/// ```
388///
389/// This implementation is complete except for the following details:
390///
391/// * handling both `push_data` and `push_value`
392/// * checking for duplicate pushes when parsing is `strict`
393/// * tracking the field's name and value to generate a complete [`Error`]
394///
395/// # Implementing
396///
397/// Implementing `FromForm` should be a rare occurrence. Prefer instead to use
398/// Rocket's built-in derivation or, for custom types, implementing
399/// [`FromFormField`].
400///
401/// An implementation of `FromForm` consists of implementing the three stages
402/// outlined above. `FromForm` is an async trait, so implementations must be
403/// decorated with an attribute of `#[rocket::async_trait]`:
404///
405/// ```rust
406/// # #[macro_use] extern crate rocket;
407/// # struct MyType;
408/// # struct MyContext;
409/// use rocket::form::{self, FromForm, DataField, ValueField};
410///
411/// #[rocket::async_trait]
412/// impl<'r> FromForm<'r> for MyType {
413/// type Context = MyContext;
414///
415/// fn init(opts: form::Options) -> Self::Context {
416/// todo!()
417/// }
418///
419/// fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) {
420/// todo!()
421/// }
422///
423/// async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) {
424/// todo!()
425/// }
426///
427/// fn finalize(this: Self::Context) -> form::Result<'r, Self> {
428/// todo!()
429/// }
430/// }
431/// ```
432///
433/// The lifetime `'r` corresponds to the lifetime of the request.
434///
435/// ## A More Involved Example
436///
437/// We illustrate implementation of `FromForm` through an example. The example
438/// implements `FromForm` for a `Pair(A, B)` type where `A: FromForm` and `B:
439/// FromForm`, parseable from forms with at least two fields, one with a key of
440/// `0` and the other with a key of `1`. The field with key `0` is parsed as an
441/// `A` while the field with key `1` is parsed as a `B`. Specifically, to parse
442/// a `Pair(A, B)` from a field with prefix `pair`, a form with the following
443/// fields must be submitted:
444///
445/// * `pair[0]` - type A
446/// * `pair[1]` - type B
447///
448/// Examples include:
449///
450/// * `pair[0]=id&pair[1]=100` as `Pair(&str, usize)`
451/// * `pair[0]=id&pair[1]=100` as `Pair(&str, &str)`
452/// * `pair[0]=2012-10-12&pair[1]=100` as `Pair(time::Date, &str)`
453/// * `pair.0=2012-10-12&pair.1=100` as `Pair(time::Date, usize)`
454///
455/// ```rust
456/// use either::Either;
457/// use rocket::form::{self, FromForm, ValueField, DataField, Error, Errors};
458///
459/// /// A form guard parseable from fields `.0` and `.1`.
460/// struct Pair<A, B>(A, B);
461///
462/// // The parsing context. We'll be pushing fields with key `.0` to `left`
463/// // and fields with `.1` to `right`. We'll collect errors along the way.
464/// struct PairContext<'v, A: FromForm<'v>, B: FromForm<'v>> {
465/// left: A::Context,
466/// right: B::Context,
467/// errors: Errors<'v>,
468/// }
469///
470/// #[rocket::async_trait]
471/// impl<'v, A: FromForm<'v>, B: FromForm<'v>> FromForm<'v> for Pair<A, B> {
472/// type Context = PairContext<'v, A, B>;
473///
474/// // We initialize the `PairContext` as expected.
475/// fn init(opts: form::Options) -> Self::Context {
476/// PairContext {
477/// left: A::init(opts),
478/// right: B::init(opts),
479/// errors: Errors::new()
480/// }
481/// }
482///
483/// // For each value, we determine if the key is `.0` (left) or `.1`
484/// // (right) and push to the appropriate parser. If it was neither, we
485/// // store the error for emission on finalization. The parsers for `A` and
486/// // `B` will handle duplicate values and so on.
487/// fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
488/// match ctxt.context(field.name) {
489/// Ok(Either::Left(ctxt)) => A::push_value(ctxt, field.shift()),
490/// Ok(Either::Right(ctxt)) => B::push_value(ctxt, field.shift()),
491/// Err(e) => ctxt.errors.push(e),
492/// }
493/// }
494///
495/// // This is identical to `push_value` but for data fields.
496/// async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
497/// match ctxt.context(field.name) {
498/// Ok(Either::Left(ctxt)) => A::push_data(ctxt, field.shift()).await,
499/// Ok(Either::Right(ctxt)) => B::push_data(ctxt, field.shift()).await,
500/// Err(e) => ctxt.errors.push(e),
501/// }
502/// }
503///
504/// // Finally, we finalize `A` and `B`. If both returned `Ok` and we
505/// // encountered no errors during the push phase, we return our pair. If
506/// // there were errors, we return them. If `A` and/or `B` failed, we
507/// // return the commutative errors.
508/// fn finalize(mut ctxt: Self::Context) -> form::Result<'v, Self> {
509/// match (A::finalize(ctxt.left), B::finalize(ctxt.right)) {
510/// (Ok(l), Ok(r)) if ctxt.errors.is_empty() => Ok(Pair(l, r)),
511/// (Ok(_), Ok(_)) => Err(ctxt.errors),
512/// (left, right) => {
513/// if let Err(e) = left { ctxt.errors.extend(e); }
514/// if let Err(e) = right { ctxt.errors.extend(e); }
515/// Err(ctxt.errors)
516/// }
517/// }
518/// }
519/// }
520///
521/// impl<'v, A: FromForm<'v>, B: FromForm<'v>> PairContext<'v, A, B> {
522/// // Helper method used by `push_{value, data}`. Determines which context
523/// // we should push to based on the field name's key. If the key is
524/// // neither `0` nor `1`, we return an error.
525/// fn context(
526/// &mut self,
527/// name: form::name::NameView<'v>
528/// ) -> Result<Either<&mut A::Context, &mut B::Context>, Error<'v>> {
529/// use std::borrow::Cow;
530///
531/// match name.key().map(|k| k.as_str()) {
532/// Some("0") => Ok(Either::Left(&mut self.left)),
533/// Some("1") => Ok(Either::Right(&mut self.right)),
534/// _ => Err(Error::from(&[Cow::Borrowed("0"), Cow::Borrowed("1")])
535/// .with_entity(form::error::Entity::Index(0))
536/// .with_name(name)),
537/// }
538/// }
539/// }
540/// ```
541#[crate::async_trait]
542pub trait FromForm<'r>: Send + Sized {
543 /// The form guard's parsing context.
544 type Context: Send;
545
546 /// Initializes and returns the parsing context for `Self`.
547 fn init(opts: Options) -> Self::Context;
548
549 /// Processes the value field `field`.
550 fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>);
551
552 /// Processes the data field `field`.
553 async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>);
554
555 /// Processes the external form or field error `_error`.
556 ///
557 /// The default implementation does nothing, which is always correct.
558 fn push_error(_ctxt: &mut Self::Context, _error: Error<'r>) { }
559
560 /// Finalizes parsing. Returns the parsed value when successful or
561 /// collection of [`Errors`] otherwise.
562 fn finalize(ctxt: Self::Context) -> Result<'r, Self>;
563
564 /// Returns a default value, if any, to use when a value is desired and
565 /// parsing fails.
566 ///
567 /// The default implementation initializes `Self` with `opts` and finalizes
568 /// immediately, returning the value if finalization succeeds. This is
569 /// always correct and should likely not be changed. Returning a different
570 /// value may result in ambiguous parses.
571 fn default(opts: Options) -> Option<Self> {
572 Self::finalize(Self::init(opts)).ok()
573 }
574}
575
576#[doc(hidden)]
577pub struct VecContext<'v, T: FromForm<'v>> {
578 opts: Options,
579 last_key: Option<&'v Key>,
580 current: Option<T::Context>,
581 errors: Errors<'v>,
582 items: Vec<T>
583}
584
585impl<'v, T: FromForm<'v>> VecContext<'v, T> {
586 fn new(opts: Options) -> Self {
587 VecContext {
588 opts,
589 last_key: None,
590 current: None,
591 items: vec![],
592 errors: Errors::new(),
593 }
594 }
595
596 fn shift(&mut self) {
597 if let Some(current) = self.current.take() {
598 match T::finalize(current) {
599 Ok(v) => self.items.push(v),
600 Err(e) => self.errors.extend(e)
601 }
602 }
603 }
604
605 fn context(&mut self, name: &NameView<'v>) -> &mut T::Context {
606 let this_key = name.key();
607 let keys_match = match (self.last_key, this_key) {
608 (Some(k1), Some(k2)) => k1 == k2,
609 _ => false
610 };
611
612 if !keys_match {
613 self.shift();
614 self.current = Some(T::init(self.opts));
615 }
616
617 self.last_key = name.key();
618 self.current.as_mut().expect("must have current if last == index")
619 }
620}
621
622#[crate::async_trait]
623impl<'v, T: FromForm<'v> + 'v> FromForm<'v> for Vec<T> {
624 type Context = VecContext<'v, T>;
625
626 fn init(opts: Options) -> Self::Context {
627 VecContext::new(opts)
628 }
629
630 fn push_value(this: &mut Self::Context, field: ValueField<'v>) {
631 T::push_value(this.context(&field.name), field.shift());
632 }
633
634 async fn push_data(this: &mut Self::Context, field: DataField<'v, '_>) {
635 T::push_data(this.context(&field.name), field.shift()).await
636 }
637
638 fn finalize(mut this: Self::Context) -> Result<'v, Self> {
639 this.shift();
640 if !this.errors.is_empty() {
641 Err(this.errors)
642 } else if this.opts.strict && this.items.is_empty() {
643 Err(Errors::from(ErrorKind::Missing))
644 } else {
645 Ok(this.items)
646 }
647 }
648}
649
650// impl_strict_from_form_field_from_capped!(Vec<u8>);
651
652#[doc(hidden)]
653pub struct MapContext<'v, K, V> where K: FromForm<'v>, V: FromForm<'v> {
654 opts: Options,
655 /// Maps an index key (&str, map.key=foo, map.k:key) to its entry.
656 /// NOTE: `table`, `entries`, and `metadata` are always the same size.
657 table: IndexMap<&'v str, usize>,
658 /// The `FromForm` context for the (key, value) indexed by `table`.
659 entries: Vec<(K::Context, V::Context)>,
660 /// Recorded metadata for a given key/value pair.
661 metadata: Vec<NameView<'v>>,
662 /// Errors collected while finalizing keys and values.
663 errors: Errors<'v>,
664}
665
666impl<'v, K, V> MapContext<'v, K, V>
667 where K: FromForm<'v>, V: FromForm<'v>
668{
669 fn new(opts: Options) -> Self {
670 MapContext {
671 opts,
672 table: IndexMap::new(),
673 entries: vec![],
674 metadata: vec![],
675 errors: Errors::new(),
676 }
677 }
678
679 fn ctxt(&mut self, key: &'v str, name: NameView<'v>) -> &mut (K::Context, V::Context) {
680 match self.table.get(key) {
681 Some(i) => &mut self.entries[*i],
682 None => {
683 let i = self.entries.len();
684 self.table.insert(key, i);
685 self.entries.push((K::init(self.opts), V::init(self.opts)));
686 self.metadata.push(name);
687 &mut self.entries[i]
688 }
689 }
690 }
691
692 fn push(&mut self, name: NameView<'v>) -> Option<Either<&mut K::Context, &mut V::Context>> {
693 let index_pair = name.key()
694 .map(|k| k.indices())
695 .map(|mut i| (i.next(), i.next()))
696 .unwrap_or_default();
697
698 match index_pair {
699 (Some(key), None) => {
700 let is_new_key = !self.table.contains_key(key);
701 let (key_ctxt, val_ctxt) = self.ctxt(key, name);
702 if is_new_key {
703 K::push_value(key_ctxt, ValueField::from_value(key));
704 }
705
706 return Some(Either::Right(val_ctxt));
707 },
708 (Some(kind), Some(key)) => {
709 if kind.as_uncased().starts_with("k") {
710 return Some(Either::Left(&mut self.ctxt(key, name).0));
711 } else if kind.as_uncased().starts_with("v") {
712 return Some(Either::Right(&mut self.ctxt(key, name).1));
713 } else {
714 let error = Error::from(&[Cow::Borrowed("k"), Cow::Borrowed("v")])
715 .with_entity(Entity::Index(0))
716 .with_name(name);
717
718 self.errors.push(error);
719 }
720 }
721 _ => {
722 let error = Error::from(ErrorKind::Missing)
723 .with_entity(Entity::Key)
724 .with_name(name);
725
726 self.errors.push(error);
727 }
728 };
729
730 None
731 }
732
733 fn push_value(&mut self, field: ValueField<'v>) {
734 match self.push(field.name) {
735 Some(Either::Left(ctxt)) => K::push_value(ctxt, field.shift()),
736 Some(Either::Right(ctxt)) => V::push_value(ctxt, field.shift()),
737 _ => {}
738 }
739 }
740
741 async fn push_data(&mut self, field: DataField<'v, '_>) {
742 match self.push(field.name) {
743 Some(Either::Left(ctxt)) => K::push_data(ctxt, field.shift()).await,
744 Some(Either::Right(ctxt)) => V::push_data(ctxt, field.shift()).await,
745 _ => {}
746 }
747 }
748
749 fn finalize<T: std::iter::FromIterator<(K, V)>>(mut self) -> Result<'v, T> {
750 let map: T = self.entries.into_iter()
751 .zip(self.metadata.iter())
752 .zip(self.table.keys())
753 .filter_map(|(((k_ctxt, v_ctxt), name), idx)| {
754 let key = K::finalize(k_ctxt)
755 .map_err(|e| {
756 // FIXME: Fix `NameBuf` to take in `k` and add it.
757 // FIXME: Perhaps the `k` should come after: `map.0:k`.
758 let form_key = format!("k:{}", idx);
759 self.errors.extend(e.with_name((name.parent(), form_key)));
760 })
761 .ok();
762
763 let val = V::finalize(v_ctxt)
764 .map_err(|e| self.errors.extend(e.with_name((name.parent(), *idx))))
765 .ok();
766
767 Some((key?, val?))
768 })
769 .collect();
770
771 if !self.errors.is_empty() {
772 Err(self.errors)
773 } else if self.opts.strict && self.table.is_empty() {
774 Err(Errors::from(ErrorKind::Missing))
775 } else {
776 Ok(map)
777 }
778 }
779}
780
781#[crate::async_trait]
782impl<'v, K, V> FromForm<'v> for HashMap<K, V>
783 where K: FromForm<'v> + Eq + Hash, V: FromForm<'v>
784{
785 type Context = MapContext<'v, K, V>;
786
787 fn init(opts: Options) -> Self::Context {
788 MapContext::new(opts)
789 }
790
791 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
792 ctxt.push_value(field);
793 }
794
795 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
796 ctxt.push_data(field).await;
797 }
798
799 fn finalize(this: Self::Context) -> Result<'v, Self> {
800 this.finalize()
801 }
802}
803
804#[crate::async_trait]
805impl<'v, K, V> FromForm<'v> for BTreeMap<K, V>
806 where K: FromForm<'v> + Ord, V: FromForm<'v>
807{
808 type Context = MapContext<'v, K, V>;
809
810 fn init(opts: Options) -> Self::Context {
811 MapContext::new(opts)
812 }
813
814 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
815 ctxt.push_value(field);
816 }
817
818 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
819 ctxt.push_data(field).await;
820 }
821
822 fn finalize(this: Self::Context) -> Result<'v, Self> {
823 this.finalize()
824 }
825}
826
827#[crate::async_trait]
828impl<'v, T: FromForm<'v>> FromForm<'v> for Option<T> {
829 type Context = <T as FromForm<'v>>::Context;
830
831 fn init(_: Options) -> Self::Context {
832 T::init(Options { strict: true })
833 }
834
835 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
836 T::push_value(ctxt, field)
837 }
838
839 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
840 T::push_data(ctxt, field).await
841 }
842
843 fn finalize(this: Self::Context) -> Result<'v, Self> {
844 Ok(T::finalize(this).ok())
845 }
846}
847
848#[crate::async_trait]
849impl<'v, T: FromForm<'v>> FromForm<'v> for Result<'v, T> {
850 type Context = <T as FromForm<'v>>::Context;
851
852 fn init(opts: Options) -> Self::Context {
853 T::init(opts)
854 }
855
856 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
857 T::push_value(ctxt, field)
858 }
859
860 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
861 T::push_data(ctxt, field).await
862 }
863
864 fn finalize(this: Self::Context) -> Result<'v, Self> {
865 Ok(T::finalize(this))
866 }
867}
868
869#[doc(hidden)]
870pub struct PairContext<'v, A: FromForm<'v>, B: FromForm<'v>> {
871 left: A::Context,
872 right: B::Context,
873 errors: Errors<'v>,
874}
875
876impl<'v, A: FromForm<'v>, B: FromForm<'v>> PairContext<'v, A, B> {
877 fn context(
878 &mut self,
879 name: NameView<'v>
880 ) -> std::result::Result<Either<&mut A::Context, &mut B::Context>, Error<'v>> {
881 match name.key().map(|k| k.as_str()) {
882 Some("0") => Ok(Either::Left(&mut self.left)),
883 Some("1") => Ok(Either::Right(&mut self.right)),
884 _ => Err(Error::from(&[Cow::Borrowed("0"), Cow::Borrowed("1")])
885 .with_entity(Entity::Index(0))
886 .with_name(name)),
887 }
888 }
889}
890
891#[crate::async_trait]
892impl<'v, A: FromForm<'v>, B: FromForm<'v>> FromForm<'v> for (A, B) {
893 type Context = PairContext<'v, A, B>;
894
895 fn init(opts: Options) -> Self::Context {
896 PairContext {
897 left: A::init(opts),
898 right: B::init(opts),
899 errors: Errors::new()
900 }
901 }
902
903 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
904 match ctxt.context(field.name) {
905 Ok(Either::Left(ctxt)) => A::push_value(ctxt, field.shift()),
906 Ok(Either::Right(ctxt)) => B::push_value(ctxt, field.shift()),
907 Err(e) => ctxt.errors.push(e),
908 }
909 }
910
911 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
912 match ctxt.context(field.name) {
913 Ok(Either::Left(ctxt)) => A::push_data(ctxt, field.shift()).await,
914 Ok(Either::Right(ctxt)) => B::push_data(ctxt, field.shift()).await,
915 Err(e) => ctxt.errors.push(e),
916 }
917 }
918
919 fn finalize(mut ctxt: Self::Context) -> Result<'v, Self> {
920 match (A::finalize(ctxt.left), B::finalize(ctxt.right)) {
921 (Ok(key), Ok(val)) if ctxt.errors.is_empty() => Ok((key, val)),
922 (Ok(_), Ok(_)) => Err(ctxt.errors)?,
923 (left, right) => {
924 if let Err(e) = left { ctxt.errors.extend(e); }
925 if let Err(e) = right { ctxt.errors.extend(e); }
926 Err(ctxt.errors)?
927 }
928 }
929 }
930}
931
932#[crate::async_trait]
933impl<'v, T: FromForm<'v> + Sync> FromForm<'v> for Arc<T> {
934 type Context = <T as FromForm<'v>>::Context;
935
936 fn init(opts: Options) -> Self::Context {
937 T::init(opts)
938 }
939
940 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
941 T::push_value(ctxt, field)
942 }
943
944 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
945 T::push_data(ctxt, field).await
946 }
947
948 fn finalize(this: Self::Context) -> Result<'v, Self> {
949 T::finalize(this).map(Arc::new)
950 }
951}
952
953macro_rules! impl_via_proxy {
954 ($R:ident => struct $T:ident <$($G:ident),*> { $($f:ident : $F:ident),* }) => {
955 const _: () = {
956 use super::*;
957
958 mod proxy {
959 #[derive(rocket::FromForm)]
960 pub struct $T<$($G),*> {
961 $(pub $f : $F),*
962 }
963 }
964
965 #[crate::async_trait]
966 impl<'v, $($G: Send),*> FromForm<'v> for $R<$($G),*>
967 where proxy::$T<$($G),*>: FromForm<'v>
968 {
969 type Context = <proxy::$T<$($G),*> as FromForm<'v>>::Context;
970
971 fn init(opts: Options) -> Self::Context {
972 <proxy::$T<$($G),*>>::init(opts)
973 }
974
975 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
976 <proxy::$T<$($G),*>>::push_value(ctxt, field)
977 }
978
979 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
980 <proxy::$T<$($G),*>>::push_data(ctxt, field).await
981 }
982
983 fn finalize(this: Self::Context) -> Result<'v, Self> {
984 let proxy = <proxy::$T<$($G),*>>::finalize(this)?;
985 Ok($R {
986 $($f : proxy.$f),*
987 })
988 }
989 }
990 };
991 }
992}
993
994use std::ops::{Range, RangeFrom, RangeTo, RangeToInclusive};
995
996impl_via_proxy!(Range => struct Range<T> { start: T, end: T });
997impl_via_proxy!(RangeFrom => struct RangeFrom<T> { start: T });
998impl_via_proxy!(RangeTo => struct RangeTo<T> { end: T });
999impl_via_proxy!(RangeToInclusive => struct RangeToInclusive<T> { end: T });