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