Skip to main content

rocket/form/
field.rs

1use crate::form::{name::NameView, error::{Error, ErrorKind, Entity}};
2use crate::http::{ContentType, RawStr};
3use crate::{Request, Data};
4use crate::fs::FileName;
5
6/// A form field with a string value.
7///
8/// Rocket preprocesses all form fields into either [`ValueField`]s or
9/// [`DataField`]s. All url-encoded form fields are value fields. Multipart
10/// fields with neither a Content-Type nor a file name are value fields if
11/// their contents are valid UTF-8. All other multipart fields are data fields.
12///
13/// Multipart values preserve their UTF-8 contents, including a leading byte
14/// order mark (BOM).
15#[derive(Debug, Clone)]
16pub struct ValueField<'r> {
17    /// The (decoded) name of the form field.
18    pub name: NameView<'r>,
19    /// The (decoded) value of the form field.
20    pub value: &'r str,
21}
22
23/// A multipart form field with an underlying data stream.
24///
25/// Rocket preprocesses all form fields into either [`ValueField`]s or
26/// [`DataField`]s. Multipart fields with a Content-Type or file name, or whose
27/// contents are not valid UTF-8, are preprocessed as a `DataField`.
28///
29/// Fields with a Content-Type or file name are streamed. Other fields are read
30/// into memory to determine whether their contents are valid UTF-8. In either
31/// case, the data can be read from the contained [`Data`] structure.
32pub struct DataField<'r, 'i> {
33    /// The (decoded) name of the form field.
34    pub name: NameView<'r>,
35    /// The form fields's file name.
36    pub file_name: Option<&'r FileName>,
37    /// The form field's Content-Type, or [`ContentType::Binary`] if none was
38    /// specified. This may not reflect the contents of `data`.
39    pub content_type: ContentType,
40    /// The request in which the form field was submitted.
41    pub request: &'r Request<'i>,
42    /// The raw data stream.
43    pub data: Data<'r>,
44}
45
46impl<'v> ValueField<'v> {
47    /// Parse a field string, where both the key and value are assumed to be
48    /// URL-decoded while preserving the `=` delimiter, into a `ValueField`.
49    ///
50    /// This implements 3.2, 3.3 of [section 5.1 of the WHATWG living standard].
51    ///
52    /// [section 5.1 of the WHATWG living standard]: https://url.spec.whatwg.org/#urlencoded-parsing
53    ///
54    /// # Example
55    ///
56    /// ```rust
57    /// use rocket::form::ValueField;
58    ///
59    /// let parsed = ValueField::parse("a cat=an A+ pet");
60    /// assert_eq!(parsed.name, "a cat");
61    /// assert_eq!(parsed.value, "an A+ pet");
62    ///
63    /// let parsed = ValueField::parse("a cat is an A+ pet");
64    /// assert_eq!(parsed.name, "a cat is an A+ pet");
65    /// assert_eq!(parsed.value, "");
66    ///
67    /// let parsed = ValueField::parse("cat.food=yum?");
68    /// assert_eq!(parsed.name, "cat");
69    /// assert_eq!(parsed.name.source(), "cat.food");
70    /// assert_eq!(parsed.value, "yum?");
71    /// ```
72    pub fn parse(field: &'v str) -> Self {
73        // WHATWG URL Living Standard 5.1 steps 3.2, 3.3.
74        let (name, val) = RawStr::new(field).split_at_byte(b'=');
75        ValueField::from((name.as_str(), val.as_str()))
76    }
77
78    /// Create a `ValueField` from a value, which is assumed to be URL-decoded.
79    /// The field `name` will be empty.
80    ///
81    /// This is equivalent to `ValueField::from(("", value))`. To create a
82    /// `ValueField` from both a `name` and a `value`, use
83    /// `ValueField::from((name, value))`.
84    ///
85    /// # Example
86    ///
87    /// ```rust
88    /// use rocket::form::ValueField;
89    ///
90    /// let parsed = ValueField::from_value("A+=kitten");
91    /// assert_eq!(parsed.name, "");
92    /// assert_eq!(parsed.value, "A+=kitten");
93    /// ```
94    pub fn from_value(value: &'v str) -> Self {
95        ValueField::from(("", value))
96    }
97
98    /// Shift the `name` of `self` and return `self` with the shifted `name`.
99    ///
100    /// See [`NameView::shift()`] for the details on name "shifting".
101    ///
102    /// # Example
103    ///
104    /// ```rust
105    /// use rocket::form::ValueField;
106    ///
107    /// let parsed = ValueField::parse("cat.food=yum?");
108    /// assert_eq!(parsed.name, "cat");
109    /// assert_eq!(parsed.name.source(), "cat.food");
110    /// assert_eq!(parsed.name.key_lossy(), "cat");
111    ///
112    /// let shifted = parsed.shift();
113    /// assert_eq!(shifted.name, "cat.food");
114    /// assert_eq!(shifted.name.key_lossy(), "food");
115    /// ```
116    pub fn shift(mut self) -> Self {
117        self.name.shift();
118        self
119    }
120
121    /// Creates a complete unexpected value field [`Error`] from `self`.
122    ///
123    /// The error will have the following properties:
124    ///   * `kind`: [`ErrorKind::Unexpected`]
125    ///   * `name`: [`self.name.source()`](NameView::source())
126    ///   * `value`: [`self.value`](ValueField::value)
127    ///   * `entity`: [`Entity::ValueField`]
128    ///
129    /// # Example
130    ///
131    /// ```rust
132    /// use rocket::form::ValueField;
133    /// use rocket::form::error::{ErrorKind, Entity};
134    ///
135    /// let field = ValueField::parse("cat.food=yum?");
136    /// let error = field.unexpected();
137    ///
138    /// assert_eq!(error.name.as_ref().unwrap(), "cat.food");
139    /// assert_eq!(error.value.as_ref().unwrap(), "yum?");
140    /// assert_eq!(error.kind, ErrorKind::Unexpected);
141    /// assert_eq!(error.entity, Entity::ValueField);
142    /// ```
143    pub fn unexpected(&self) -> Error<'v> {
144        Error::from(ErrorKind::Unexpected)
145            .with_name(self.name.source())
146            .with_value(self.value)
147            .with_entity(Entity::ValueField)
148    }
149
150    /// Creates a complete missing value field [`Error`] from `self`.
151    ///
152    /// The error will have the following properties:
153    ///   * `kind`: [`ErrorKind::Missing`]
154    ///   * `name`: [`self.name.source()`](NameView::source())
155    ///   * `value`: [`self.value`](ValueField::value)
156    ///   * `entity`: [`Entity::ValueField`]
157    ///
158    /// # Example
159    ///
160    /// ```rust
161    /// use rocket::form::ValueField;
162    /// use rocket::form::error::{ErrorKind, Entity};
163    ///
164    /// let field = ValueField::parse("cat.food=yum?");
165    /// let error = field.missing();
166    ///
167    /// assert_eq!(error.name.as_ref().unwrap(), "cat.food");
168    /// assert_eq!(error.value.as_ref().unwrap(), "yum?");
169    /// assert_eq!(error.kind, ErrorKind::Missing);
170    /// assert_eq!(error.entity, Entity::ValueField);
171    /// ```
172    pub fn missing(&self) -> Error<'v> {
173        Error::from(ErrorKind::Missing)
174            .with_name(self.name.source())
175            .with_value(self.value)
176            .with_entity(Entity::ValueField)
177    }
178}
179
180impl<'v> DataField<'v, '_> {
181    /// Shift the `name` of `self` and return `self` with the shifted `name`.
182    ///
183    /// This is identical to [`ValueField::shift()`] but for `DataField`s. See
184    /// [`NameView::shift()`] for the details on name "shifting".
185    ///
186    /// # Example
187    ///
188    /// ```rust
189    /// use rocket::form::DataField;
190    ///
191    /// fn push_data(field: DataField<'_, '_>) {
192    ///     let shifted = field.shift();
193    /// }
194    /// ```
195    pub fn shift(mut self) -> Self {
196        self.name.shift();
197        self
198    }
199
200    /// Creates a complete unexpected data field [`Error`] from `self`.
201    ///
202    /// The error will have the following properties:
203    ///   * `kind`: [`ErrorKind::Unexpected`]
204    ///   * `name`: [`self.name.source()`](NameView::source())
205    ///   * `value`: `None`
206    ///   * `entity`: [`Entity::DataField`]
207    ///
208    /// # Example
209    ///
210    /// ```rust
211    /// use rocket::form::DataField;
212    ///
213    /// fn push_data(field: DataField<'_, '_>) {
214    ///     let error = field.unexpected();
215    /// }
216    /// ```
217    pub fn unexpected(&self) -> Error<'v> {
218        Error::from(ErrorKind::Unexpected)
219            .with_name(self.name.source())
220            .with_entity(Entity::DataField)
221    }
222}
223
224impl<'a> From<(&'a str, &'a str)> for ValueField<'a> {
225    fn from((name, value): (&'a str, &'a str)) -> Self {
226        ValueField { name: NameView::new(name), value }
227    }
228}
229
230impl<'a, 'b> PartialEq<ValueField<'b>> for ValueField<'a> {
231    fn eq(&self, other: &ValueField<'b>) -> bool {
232        self.name == other.name && self.value == other.value
233    }
234}