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.5/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.
214///
215/// Data fields are subject to the receiving guard's data limit. For example,
216/// strings use `string`, byte slices use `bytes`, and [`TempFile`] uses `file`
217/// or `file/$ext`. See [`Limits`] for defaults.
218///
219/// [`TempFile`]: crate::fs::TempFile
220/// [`Limits`]: crate::data::Limits
221///
222/// [field wire format]: crate::form#field-wire-format
223///
224/// Parsing is split into 3 stages. After preprocessing, the three stages are:
225///
226/// 1. **Initialization.** The type sets up a context for later `push`es.
227///
228/// ```rust
229/// # use rocket::form::prelude::*;
230/// # struct Foo;
231/// use rocket::form::Options;
232///
233/// # #[rocket::async_trait]
234/// # impl<'r> FromForm<'r> for Foo {
235/// # type Context = std::convert::Infallible;
236/// fn init(opts: Options) -> Self::Context {
237/// todo!("return a context for storing parse state")
238/// }
239/// # fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) { todo!() }
240/// # async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) { todo!() }
241/// # fn finalize(ctxt: Self::Context) -> Result<'r, Self> { todo!() }
242/// # }
243/// ```
244///
245/// 2. **Push.** The structure is repeatedly pushed form fields; the latest
246/// context is provided with each `push`. If the structure contains
247/// children, it uses the first [`key()`] to identify a child to which it
248/// then `push`es the remaining `field` to, likely with a [`shift()`ed]
249/// name. Otherwise, the structure parses the `value` itself. The context
250/// is updated as needed.
251///
252/// ```rust
253/// # use rocket::form::prelude::*;
254/// # struct Foo;
255/// use rocket::form::{ValueField, DataField};
256///
257/// # #[rocket::async_trait]
258/// # impl<'r> FromForm<'r> for Foo {
259/// # type Context = std::convert::Infallible;
260/// # fn init(opts: Options) -> Self::Context { todo!() }
261/// fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) {
262/// todo!("modify context as necessary for `field`")
263/// }
264///
265/// async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) {
266/// todo!("modify context as necessary for `field`")
267/// }
268/// # fn finalize(ctxt: Self::Context) -> Result<'r, Self> { todo!() }
269/// # }
270/// ```
271///
272/// 3. **Finalization.** The structure is informed that there are no further
273/// fields. It systemizes the effects of previous `push`es via its context
274/// to return a parsed structure or generate [`Errors`].
275///
276/// ```rust
277/// # use rocket::form::prelude::*;
278/// # struct Foo;
279/// use rocket::form::Result;
280///
281/// # #[rocket::async_trait]
282/// # impl<'r> FromForm<'r> for Foo {
283/// # type Context = std::convert::Infallible;
284/// # fn init(opts: Options) -> Self::Context { todo!() }
285/// # fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) { todo!() }
286/// # async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) { todo!() }
287/// fn finalize(ctxt: Self::Context) -> Result<'r, Self> {
288/// todo!("inspect context to generate `Self` or `Errors`")
289/// }
290/// # }
291/// ```
292///
293/// These three stages make up the entirety of the `FromForm` trait.
294///
295/// ## Nesting and [`NameView`]
296///
297/// Each field name key typically identifies a unique child of a structure. As
298/// such, when processed left-to-right, the keys of a field jointly identify a
299/// unique leaf of a structure. The value of the field typically represents the
300/// desired value of the leaf.
301///
302/// A [`NameView`] captures and simplifies this "left-to-right" processing of a
303/// field's name by exposing a sliding-prefix view into a name. A [`shift()`]
304/// shifts the view one key to the right. Thus, a `Name` of `a.b.c` when viewed
305/// through a new [`NameView`] is `a`. Shifted once, the view is `a.b`.
306/// [`key()`] returns the last (or "current") key in the view. A nested
307/// structure can thus handle a field with a `NameView`, operate on the
308/// [`key()`], [`shift()`] the `NameView`, and pass the field with the shifted
309/// `NameView` to the next processor which handles `b` and so on.
310///
311/// [`shift()`]: NameView::shift()
312/// [`key()`]: NameView::key()
313///
314/// ## A Simple Example
315///
316/// The following example uses `f1=v1&f2=v2` to illustrate field/value pairs
317/// `(f1, v2)` and `(f2, v2)`. This is the same encoding used to send HTML forms
318/// over HTTP, though Rocket's push-parsers are unaware of any specific
319/// encoding, dealing only with logical `field`s, `index`es, and `value`s.
320///
321/// ### A Single Field (`T: FormFormField`)
322///
323/// The simplest example parses a single value of type `T` from a string with an
324/// optional default value: this is `impl<T: FromFormField> FromForm for T`:
325///
326/// 1. **Initialization.** The context stores form options and an `Option` of
327/// `Result<T, form::Error>` for storing the `result` of parsing `T`, which
328/// is initially set to `None`.
329///
330/// ```rust
331/// use rocket::form::{self, FromFormField};
332///
333/// struct Context<'r, T: FromFormField<'r>> {
334/// opts: form::Options,
335/// result: Option<form::Result<'r, T>>,
336/// }
337///
338/// # impl<'r, T: FromFormField<'r>> Context<'r, T> {
339/// fn init(opts: form::Options) -> Context<'r, T> {
340/// Context { opts, result: None }
341/// }
342/// # }
343/// ```
344///
345/// 2. **Push.** If `ctxt.result` is `None`, `T` is parsed from `field`, and
346/// the result is stored in `context.result`. Otherwise a field has already
347/// been parsed and nothing is done.
348///
349/// ```rust
350/// # use rocket::form::{self, ValueField, FromFormField};
351/// # struct Context<'r, T: FromFormField<'r>> {
352/// # opts: form::Options,
353/// # result: Option<form::Result<'r, T>>,
354/// # }
355/// # impl<'r, T: FromFormField<'r>> Context<'r, T> {
356/// fn push_value(ctxt: &mut Context<'r, T>, field: ValueField<'r>) {
357/// if ctxt.result.is_none() {
358/// ctxt.result = Some(T::from_value(field));
359/// }
360/// }
361/// # }
362/// ```
363///
364/// 3. **Finalization.** If `ctxt.result` is `None`, parsing is lenient, and
365/// `T` has a default, the default is returned. Otherwise a `Missing` error
366/// is returned. If `ctxt.result` is `Some(v)`, the result `v` is returned.
367///
368/// ```rust
369/// # use rocket::form::{self, FromFormField, error::{Errors, ErrorKind}};
370/// # struct Context<'r, T: FromFormField<'r>> {
371/// # opts: form::Options,
372/// # result: Option<form::Result<'r, T>>,
373/// # }
374/// # impl<'r, T: FromFormField<'r>> Context<'r, T> {
375/// fn finalize(ctxt: Context<'r, T>) -> form::Result<'r, T> {
376/// match ctxt.result {
377/// Some(result) => result,
378/// None if ctxt.opts.strict => Err(Errors::from(ErrorKind::Missing)),
379/// None => match T::default() {
380/// Some(default) => Ok(default),
381/// None => Err(Errors::from(ErrorKind::Missing)),
382/// }
383/// }
384/// }
385/// # }
386/// ```
387///
388/// This implementation is complete except for the following details:
389///
390/// * handling both `push_data` and `push_value`
391/// * checking for duplicate pushes when parsing is `strict`
392/// * tracking the field's name and value to generate a complete [`Error`]
393///
394/// # Implementing
395///
396/// Implementing `FromForm` should be a rare occurrence. Prefer instead to use
397/// Rocket's built-in derivation or, for custom types, implementing
398/// [`FromFormField`].
399///
400/// An implementation of `FromForm` consists of implementing the three stages
401/// outlined above. `FromForm` is an async trait, so implementations must be
402/// decorated with an attribute of `#[rocket::async_trait]`:
403///
404/// ```rust
405/// # #[macro_use] extern crate rocket;
406/// # struct MyType;
407/// # struct MyContext;
408/// use rocket::form::{self, FromForm, DataField, ValueField};
409///
410/// #[rocket::async_trait]
411/// impl<'r> FromForm<'r> for MyType {
412/// type Context = MyContext;
413///
414/// fn init(opts: form::Options) -> Self::Context {
415/// todo!()
416/// }
417///
418/// fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>) {
419/// todo!()
420/// }
421///
422/// async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>) {
423/// todo!()
424/// }
425///
426/// fn finalize(this: Self::Context) -> form::Result<'r, Self> {
427/// todo!()
428/// }
429/// }
430/// ```
431///
432/// The lifetime `'r` corresponds to the lifetime of the request.
433///
434/// ## A More Involved Example
435///
436/// We illustrate implementation of `FromForm` through an example. The example
437/// implements `FromForm` for a `Pair(A, B)` type where `A: FromForm` and `B:
438/// FromForm`, parseable from forms with at least two fields, one with a key of
439/// `0` and the other with a key of `1`. The field with key `0` is parsed as an
440/// `A` while the field with key `1` is parsed as a `B`. Specifically, to parse
441/// a `Pair(A, B)` from a field with prefix `pair`, a form with the following
442/// fields must be submitted:
443///
444/// * `pair[0]` - type A
445/// * `pair[1]` - type B
446///
447/// Examples include:
448///
449/// * `pair[0]=id&pair[1]=100` as `Pair(&str, usize)`
450/// * `pair[0]=id&pair[1]=100` as `Pair(&str, &str)`
451/// * `pair[0]=2012-10-12&pair[1]=100` as `Pair(time::Date, &str)`
452/// * `pair.0=2012-10-12&pair.1=100` as `Pair(time::Date, usize)`
453///
454/// ```rust
455/// use either::Either;
456/// use rocket::form::{self, FromForm, ValueField, DataField, Error, Errors};
457///
458/// /// A form guard parseable from fields `.0` and `.1`.
459/// struct Pair<A, B>(A, B);
460///
461/// // The parsing context. We'll be pushing fields with key `.0` to `left`
462/// // and fields with `.1` to `right`. We'll collect errors along the way.
463/// struct PairContext<'v, A: FromForm<'v>, B: FromForm<'v>> {
464/// left: A::Context,
465/// right: B::Context,
466/// errors: Errors<'v>,
467/// }
468///
469/// #[rocket::async_trait]
470/// impl<'v, A: FromForm<'v>, B: FromForm<'v>> FromForm<'v> for Pair<A, B> {
471/// type Context = PairContext<'v, A, B>;
472///
473/// // We initialize the `PairContext` as expected.
474/// fn init(opts: form::Options) -> Self::Context {
475/// PairContext {
476/// left: A::init(opts),
477/// right: B::init(opts),
478/// errors: Errors::new()
479/// }
480/// }
481///
482/// // For each value, we determine if the key is `.0` (left) or `.1`
483/// // (right) and push to the appropriate parser. If it was neither, we
484/// // store the error for emission on finalization. The parsers for `A` and
485/// // `B` will handle duplicate values and so on.
486/// fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
487/// match ctxt.context(field.name) {
488/// Ok(Either::Left(ctxt)) => A::push_value(ctxt, field.shift()),
489/// Ok(Either::Right(ctxt)) => B::push_value(ctxt, field.shift()),
490/// Err(e) => ctxt.errors.push(e),
491/// }
492/// }
493///
494/// // This is identical to `push_value` but for data fields.
495/// async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
496/// match ctxt.context(field.name) {
497/// Ok(Either::Left(ctxt)) => A::push_data(ctxt, field.shift()).await,
498/// Ok(Either::Right(ctxt)) => B::push_data(ctxt, field.shift()).await,
499/// Err(e) => ctxt.errors.push(e),
500/// }
501/// }
502///
503/// // Finally, we finalize `A` and `B`. If both returned `Ok` and we
504/// // encountered no errors during the push phase, we return our pair. If
505/// // there were errors, we return them. If `A` and/or `B` failed, we
506/// // return the commutative errors.
507/// fn finalize(mut ctxt: Self::Context) -> form::Result<'v, Self> {
508/// match (A::finalize(ctxt.left), B::finalize(ctxt.right)) {
509/// (Ok(l), Ok(r)) if ctxt.errors.is_empty() => Ok(Pair(l, r)),
510/// (Ok(_), Ok(_)) => Err(ctxt.errors),
511/// (left, right) => {
512/// if let Err(e) = left { ctxt.errors.extend(e); }
513/// if let Err(e) = right { ctxt.errors.extend(e); }
514/// Err(ctxt.errors)
515/// }
516/// }
517/// }
518/// }
519///
520/// impl<'v, A: FromForm<'v>, B: FromForm<'v>> PairContext<'v, A, B> {
521/// // Helper method used by `push_{value, data}`. Determines which context
522/// // we should push to based on the field name's key. If the key is
523/// // neither `0` nor `1`, we return an error.
524/// fn context(
525/// &mut self,
526/// name: form::name::NameView<'v>
527/// ) -> Result<Either<&mut A::Context, &mut B::Context>, Error<'v>> {
528/// use std::borrow::Cow;
529///
530/// match name.key().map(|k| k.as_str()) {
531/// Some("0") => Ok(Either::Left(&mut self.left)),
532/// Some("1") => Ok(Either::Right(&mut self.right)),
533/// _ => Err(Error::from(&[Cow::Borrowed("0"), Cow::Borrowed("1")])
534/// .with_entity(form::error::Entity::Index(0))
535/// .with_name(name)),
536/// }
537/// }
538/// }
539/// ```
540#[crate::async_trait]
541pub trait FromForm<'r>: Send + Sized {
542 /// The form guard's parsing context.
543 type Context: Send;
544
545 /// Initializes and returns the parsing context for `Self`.
546 fn init(opts: Options) -> Self::Context;
547
548 /// Processes the value field `field`.
549 fn push_value(ctxt: &mut Self::Context, field: ValueField<'r>);
550
551 /// Processes the data field `field`.
552 async fn push_data(ctxt: &mut Self::Context, field: DataField<'r, '_>);
553
554 /// Processes the external form or field error `_error`.
555 ///
556 /// The default implementation does nothing, which is always correct.
557 fn push_error(_ctxt: &mut Self::Context, _error: Error<'r>) { }
558
559 /// Finalizes parsing. Returns the parsed value when successful or
560 /// collection of [`Errors`] otherwise.
561 fn finalize(ctxt: Self::Context) -> Result<'r, Self>;
562
563 /// Returns a default value, if any, to use when a value is desired and
564 /// parsing fails.
565 ///
566 /// The default implementation initializes `Self` with `opts` and finalizes
567 /// immediately, returning the value if finalization succeeds. This is
568 /// always correct and should likely not be changed. Returning a different
569 /// value may result in ambiguous parses.
570 fn default(opts: Options) -> Option<Self> {
571 Self::finalize(Self::init(opts)).ok()
572 }
573}
574
575#[doc(hidden)]
576pub struct VecContext<'v, T: FromForm<'v>> {
577 opts: Options,
578 last_key: Option<&'v Key>,
579 current: Option<T::Context>,
580 errors: Errors<'v>,
581 items: Vec<T>
582}
583
584impl<'v, T: FromForm<'v>> VecContext<'v, T> {
585 fn new(opts: Options) -> Self {
586 VecContext {
587 opts,
588 last_key: None,
589 current: None,
590 items: vec![],
591 errors: Errors::new(),
592 }
593 }
594
595 fn shift(&mut self) {
596 if let Some(current) = self.current.take() {
597 match T::finalize(current) {
598 Ok(v) => self.items.push(v),
599 Err(e) => self.errors.extend(e)
600 }
601 }
602 }
603
604 fn context(&mut self, name: &NameView<'v>) -> &mut T::Context {
605 let this_key = name.key();
606 let keys_match = match (self.last_key, this_key) {
607 (Some(k1), Some(k2)) => k1 == k2,
608 _ => false
609 };
610
611 if !keys_match {
612 self.shift();
613 self.current = Some(T::init(self.opts));
614 }
615
616 self.last_key = name.key();
617 self.current.as_mut().expect("must have current if last == index")
618 }
619}
620
621#[crate::async_trait]
622impl<'v, T: FromForm<'v> + 'v> FromForm<'v> for Vec<T> {
623 type Context = VecContext<'v, T>;
624
625 fn init(opts: Options) -> Self::Context {
626 VecContext::new(opts)
627 }
628
629 fn push_value(this: &mut Self::Context, field: ValueField<'v>) {
630 T::push_value(this.context(&field.name), field.shift());
631 }
632
633 async fn push_data(this: &mut Self::Context, field: DataField<'v, '_>) {
634 T::push_data(this.context(&field.name), field.shift()).await
635 }
636
637 fn finalize(mut this: Self::Context) -> Result<'v, Self> {
638 this.shift();
639 if !this.errors.is_empty() {
640 Err(this.errors)
641 } else if this.opts.strict && this.items.is_empty() {
642 Err(Errors::from(ErrorKind::Missing))
643 } else {
644 Ok(this.items)
645 }
646 }
647}
648
649// impl_strict_from_form_field_from_capped!(Vec<u8>);
650
651#[doc(hidden)]
652pub struct MapContext<'v, K, V> where K: FromForm<'v>, V: FromForm<'v> {
653 opts: Options,
654 /// Maps an index key (&str, map.key=foo, map.k:key) to its entry.
655 /// NOTE: `table`, `entries`, and `metadata` are always the same size.
656 table: IndexMap<&'v str, usize>,
657 /// The `FromForm` context for the (key, value) indexed by `table`.
658 entries: Vec<(K::Context, V::Context)>,
659 /// Recorded metadata for a given key/value pair.
660 metadata: Vec<NameView<'v>>,
661 /// Errors collected while finalizing keys and values.
662 errors: Errors<'v>,
663}
664
665impl<'v, K, V> MapContext<'v, K, V>
666 where K: FromForm<'v>, V: FromForm<'v>
667{
668 fn new(opts: Options) -> Self {
669 MapContext {
670 opts,
671 table: IndexMap::new(),
672 entries: vec![],
673 metadata: vec![],
674 errors: Errors::new(),
675 }
676 }
677
678 fn ctxt(&mut self, key: &'v str, name: NameView<'v>) -> &mut (K::Context, V::Context) {
679 match self.table.get(key) {
680 Some(i) => &mut self.entries[*i],
681 None => {
682 let i = self.entries.len();
683 self.table.insert(key, i);
684 self.entries.push((K::init(self.opts), V::init(self.opts)));
685 self.metadata.push(name);
686 &mut self.entries[i]
687 }
688 }
689 }
690
691 fn push(&mut self, name: NameView<'v>) -> Option<Either<&mut K::Context, &mut V::Context>> {
692 let index_pair = name.key()
693 .map(|k| k.indices())
694 .map(|mut i| (i.next(), i.next()))
695 .unwrap_or_default();
696
697 match index_pair {
698 (Some(key), None) => {
699 let is_new_key = !self.table.contains_key(key);
700 let (key_ctxt, val_ctxt) = self.ctxt(key, name);
701 if is_new_key {
702 K::push_value(key_ctxt, ValueField::from_value(key));
703 }
704
705 return Some(Either::Right(val_ctxt));
706 },
707 (Some(kind), Some(key)) => {
708 if kind.as_uncased().starts_with("k") {
709 return Some(Either::Left(&mut self.ctxt(key, name).0));
710 } else if kind.as_uncased().starts_with("v") {
711 return Some(Either::Right(&mut self.ctxt(key, name).1));
712 } else {
713 let error = Error::from(&[Cow::Borrowed("k"), Cow::Borrowed("v")])
714 .with_entity(Entity::Index(0))
715 .with_name(name);
716
717 self.errors.push(error);
718 }
719 }
720 _ => {
721 let error = Error::from(ErrorKind::Missing)
722 .with_entity(Entity::Key)
723 .with_name(name);
724
725 self.errors.push(error);
726 }
727 };
728
729 None
730 }
731
732 fn push_value(&mut self, field: ValueField<'v>) {
733 match self.push(field.name) {
734 Some(Either::Left(ctxt)) => K::push_value(ctxt, field.shift()),
735 Some(Either::Right(ctxt)) => V::push_value(ctxt, field.shift()),
736 _ => {}
737 }
738 }
739
740 async fn push_data(&mut self, field: DataField<'v, '_>) {
741 match self.push(field.name) {
742 Some(Either::Left(ctxt)) => K::push_data(ctxt, field.shift()).await,
743 Some(Either::Right(ctxt)) => V::push_data(ctxt, field.shift()).await,
744 _ => {}
745 }
746 }
747
748 fn finalize<T: std::iter::FromIterator<(K, V)>>(mut self) -> Result<'v, T> {
749 let map: T = self.entries.into_iter()
750 .zip(self.metadata.iter())
751 .zip(self.table.keys())
752 .filter_map(|(((k_ctxt, v_ctxt), name), idx)| {
753 let key = K::finalize(k_ctxt)
754 .map_err(|e| {
755 // FIXME: Fix `NameBuf` to take in `k` and add it.
756 // FIXME: Perhaps the `k` should come after: `map.0:k`.
757 let form_key = format!("k:{}", idx);
758 self.errors.extend(e.with_name((name.parent(), form_key)));
759 })
760 .ok();
761
762 let val = V::finalize(v_ctxt)
763 .map_err(|e| self.errors.extend(e.with_name((name.parent(), *idx))))
764 .ok();
765
766 Some((key?, val?))
767 })
768 .collect();
769
770 if !self.errors.is_empty() {
771 Err(self.errors)
772 } else if self.opts.strict && self.table.is_empty() {
773 Err(Errors::from(ErrorKind::Missing))
774 } else {
775 Ok(map)
776 }
777 }
778}
779
780#[crate::async_trait]
781impl<'v, K, V> FromForm<'v> for HashMap<K, V>
782 where K: FromForm<'v> + Eq + Hash, V: FromForm<'v>
783{
784 type Context = MapContext<'v, K, V>;
785
786 fn init(opts: Options) -> Self::Context {
787 MapContext::new(opts)
788 }
789
790 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
791 ctxt.push_value(field);
792 }
793
794 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
795 ctxt.push_data(field).await;
796 }
797
798 fn finalize(this: Self::Context) -> Result<'v, Self> {
799 this.finalize()
800 }
801}
802
803#[crate::async_trait]
804impl<'v, K, V> FromForm<'v> for BTreeMap<K, V>
805 where K: FromForm<'v> + Ord, V: FromForm<'v>
806{
807 type Context = MapContext<'v, K, V>;
808
809 fn init(opts: Options) -> Self::Context {
810 MapContext::new(opts)
811 }
812
813 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
814 ctxt.push_value(field);
815 }
816
817 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
818 ctxt.push_data(field).await;
819 }
820
821 fn finalize(this: Self::Context) -> Result<'v, Self> {
822 this.finalize()
823 }
824}
825
826#[crate::async_trait]
827impl<'v, T: FromForm<'v>> FromForm<'v> for Option<T> {
828 type Context = <T as FromForm<'v>>::Context;
829
830 fn init(_: Options) -> Self::Context {
831 T::init(Options { strict: true })
832 }
833
834 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
835 T::push_value(ctxt, field)
836 }
837
838 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
839 T::push_data(ctxt, field).await
840 }
841
842 fn finalize(this: Self::Context) -> Result<'v, Self> {
843 Ok(T::finalize(this).ok())
844 }
845}
846
847#[crate::async_trait]
848impl<'v, T: FromForm<'v>> FromForm<'v> for Result<'v, T> {
849 type Context = <T as FromForm<'v>>::Context;
850
851 fn init(opts: Options) -> Self::Context {
852 T::init(opts)
853 }
854
855 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
856 T::push_value(ctxt, field)
857 }
858
859 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
860 T::push_data(ctxt, field).await
861 }
862
863 fn finalize(this: Self::Context) -> Result<'v, Self> {
864 Ok(T::finalize(this))
865 }
866}
867
868#[doc(hidden)]
869pub struct PairContext<'v, A: FromForm<'v>, B: FromForm<'v>> {
870 left: A::Context,
871 right: B::Context,
872 errors: Errors<'v>,
873}
874
875impl<'v, A: FromForm<'v>, B: FromForm<'v>> PairContext<'v, A, B> {
876 fn context(
877 &mut self,
878 name: NameView<'v>
879 ) -> std::result::Result<Either<&mut A::Context, &mut B::Context>, Error<'v>> {
880 match name.key().map(|k| k.as_str()) {
881 Some("0") => Ok(Either::Left(&mut self.left)),
882 Some("1") => Ok(Either::Right(&mut self.right)),
883 _ => Err(Error::from(&[Cow::Borrowed("0"), Cow::Borrowed("1")])
884 .with_entity(Entity::Index(0))
885 .with_name(name)),
886 }
887 }
888}
889
890#[crate::async_trait]
891impl<'v, A: FromForm<'v>, B: FromForm<'v>> FromForm<'v> for (A, B) {
892 type Context = PairContext<'v, A, B>;
893
894 fn init(opts: Options) -> Self::Context {
895 PairContext {
896 left: A::init(opts),
897 right: B::init(opts),
898 errors: Errors::new()
899 }
900 }
901
902 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
903 match ctxt.context(field.name) {
904 Ok(Either::Left(ctxt)) => A::push_value(ctxt, field.shift()),
905 Ok(Either::Right(ctxt)) => B::push_value(ctxt, field.shift()),
906 Err(e) => ctxt.errors.push(e),
907 }
908 }
909
910 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
911 match ctxt.context(field.name) {
912 Ok(Either::Left(ctxt)) => A::push_data(ctxt, field.shift()).await,
913 Ok(Either::Right(ctxt)) => B::push_data(ctxt, field.shift()).await,
914 Err(e) => ctxt.errors.push(e),
915 }
916 }
917
918 fn finalize(mut ctxt: Self::Context) -> Result<'v, Self> {
919 match (A::finalize(ctxt.left), B::finalize(ctxt.right)) {
920 (Ok(key), Ok(val)) if ctxt.errors.is_empty() => Ok((key, val)),
921 (Ok(_), Ok(_)) => Err(ctxt.errors)?,
922 (left, right) => {
923 if let Err(e) = left { ctxt.errors.extend(e); }
924 if let Err(e) = right { ctxt.errors.extend(e); }
925 Err(ctxt.errors)?
926 }
927 }
928 }
929}
930
931#[crate::async_trait]
932impl<'v, T: FromForm<'v> + Sync> FromForm<'v> for Arc<T> {
933 type Context = <T as FromForm<'v>>::Context;
934
935 fn init(opts: Options) -> Self::Context {
936 T::init(opts)
937 }
938
939 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
940 T::push_value(ctxt, field)
941 }
942
943 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
944 T::push_data(ctxt, field).await
945 }
946
947 fn finalize(this: Self::Context) -> Result<'v, Self> {
948 T::finalize(this).map(Arc::new)
949 }
950}
951
952macro_rules! impl_via_proxy {
953 ($R:ident => struct $T:ident <$($G:ident),*> { $($f:ident : $F:ident),* }) => {
954 const _: () = {
955 use super::*;
956
957 mod proxy {
958 #[derive(rocket::FromForm)]
959 pub struct $T<$($G),*> {
960 $(pub $f : $F),*
961 }
962 }
963
964 #[crate::async_trait]
965 impl<'v, $($G: Send),*> FromForm<'v> for $R<$($G),*>
966 where proxy::$T<$($G),*>: FromForm<'v>
967 {
968 type Context = <proxy::$T<$($G),*> as FromForm<'v>>::Context;
969
970 fn init(opts: Options) -> Self::Context {
971 <proxy::$T<$($G),*>>::init(opts)
972 }
973
974 fn push_value(ctxt: &mut Self::Context, field: ValueField<'v>) {
975 <proxy::$T<$($G),*>>::push_value(ctxt, field)
976 }
977
978 async fn push_data(ctxt: &mut Self::Context, field: DataField<'v, '_>) {
979 <proxy::$T<$($G),*>>::push_data(ctxt, field).await
980 }
981
982 fn finalize(this: Self::Context) -> Result<'v, Self> {
983 let proxy = <proxy::$T<$($G),*>>::finalize(this)?;
984 Ok($R {
985 $($f : proxy.$f),*
986 })
987 }
988 }
989 };
990 }
991}
992
993use std::ops::{Range, RangeFrom, RangeTo, RangeToInclusive};
994
995impl_via_proxy!(Range => struct Range<T> { start: T, end: T });
996impl_via_proxy!(RangeFrom => struct RangeFrom<T> { start: T });
997impl_via_proxy!(RangeTo => struct RangeTo<T> { end: T });
998impl_via_proxy!(RangeToInclusive => struct RangeToInclusive<T> { end: T });