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
use std::borrow::Cow;
use std::str::FromStr;
use super::query::{QueryParamRange, QueryParser};
use crate::error::{Error, ResultExt};
use crate::util::UriEncoding;
pub struct PathParam<'a, 'b> {
encoding: UriEncoding,
source: &'a str,
param: Option<&'a via_router::PathParam>,
name: &'b str,
}
#[derive(Clone, Copy)]
pub struct PathParams<'a> {
path: &'a str,
spans: &'a [via_router::PathParam],
}
pub struct QueryParam<'a, 'b> {
encoding: UriEncoding,
source: Option<&'a str>,
range: Option<QueryParamRange>,
name: &'b str,
}
pub struct QueryParams<'a> {
query: Option<&'a str>,
spans: Vec<(Cow<'a, str>, Option<QueryParamRange>)>,
}
pub(crate) fn get<'a>(
spans: &'a [via_router::PathParam],
name: &str,
) -> Option<&'a via_router::PathParam> {
spans.iter().find(|param| name == param.ident())
}
fn query_pos_for_key(
predicate: &str,
key: &str,
value: &Option<[Option<usize>; 2]>,
) -> Option<[Option<usize>; 2]> {
if key == predicate {
value.as_ref().copied()
} else {
None
}
}
impl<'a> PathParams<'a> {
pub fn get<'b>(&self, name: &'b str) -> PathParam<'a, 'b> {
PathParam::new(self.path, get(self.spans, name), name)
}
}
impl<'a> PathParams<'a> {
pub(crate) fn new(path: &'a str, spans: &'a [via_router::PathParam]) -> Self {
Self { path, spans }
}
}
impl<'a> QueryParams<'a> {
pub(crate) fn new(query: Option<&'a str>) -> Self {
let spans = query
.map(|input| QueryParser::new(input).collect())
.unwrap_or_default();
Self { query, spans }
}
pub fn all<'b>(&self, name: &'b str) -> impl Iterator<Item = QueryParam<'a, 'b>> {
self.spans.iter().filter_map(move |(key, value)| {
let value = value.as_ref();
if key.as_ref() == name {
Some(QueryParam::new(self.query, value.copied(), name))
} else {
None
}
})
}
pub fn contains(&self, name: &str) -> bool {
self.spans.iter().any(|(key, _)| key.as_ref() == name)
}
pub fn first<'b>(&self, name: &'b str) -> QueryParam<'a, 'b> {
let range = self
.spans
.iter()
.find_map(|(key, value)| query_pos_for_key(name, key, value));
QueryParam::new(self.query, range, name)
}
pub fn last<'b>(&self, name: &'b str) -> QueryParam<'a, 'b> {
let range = self
.spans
.iter()
.rev()
.find_map(|(key, value)| query_pos_for_key(name, key, value));
QueryParam::new(self.query, range, name)
}
}
impl<'a, 'b> PathParam<'a, 'b> {
#[inline]
pub(crate) fn new(
source: &'a str,
param: Option<&'a via_router::PathParam>,
name: &'b str,
) -> Self {
Self {
encoding: UriEncoding::Unencoded,
source,
param,
name,
}
}
/// Returns a new `Param` that will percent-decode the parameter value with
/// when the parameter is converted to a result.
///
#[inline]
pub fn percent_decode(self) -> Self {
Self {
encoding: UriEncoding::Percent,
..self
}
}
/// Calls [`str::parse`] on the parameter value if it exists and returns the
/// result. If the param is encoded, it will be decoded before it is parsed.
///
pub fn parse<U>(self) -> Result<U, Error>
where
U: FromStr,
Error: From<U::Err>,
{
self.into_result()
.and_then(|value| value.as_ref().parse().or_bad_request())
}
pub fn ok(self) -> Result<Option<Cow<'a, str>>, Error> {
self.param
.and_then(|param| param.slice(self.source))
.map(|value| self.encoding.decode_as(self.name, value))
.transpose()
}
/// Converts `self` into `Result<Option<T>, Error>` by calling the provided
/// closure.
///
/// This provides a way to apply a fallible operation to the optional value
/// contained in `self` without bailing out of lazy evaluation.
///
/// If an error occurs during the conversion, a 400 Bad Request response is
/// returned.
///
/// # Example
///
/// ```
/// use uuid::Uuid;
/// use via::{Next, Request, Response};
///
/// async fn hello(request: Request, _: Next) -> via::Result {
/// // Parse errors occur when the conversion is performed.
/// let id_opt: Option<Uuid> = request.param("id").ok_and_then(str::parse)?;
///
/// if let Some(id) = id_opt {
/// Response::build().text(format!("Hello, {}!", id))
/// } else {
/// Response::build().status(404).text("not found.")
/// }
/// }
/// ```
pub fn ok_and_then<F, T, E>(self, op: F) -> Result<Option<T>, Error>
where
F: FnOnce(&str) -> Result<T, E>,
Error: From<E>,
{
self.ok().and_then(|optional| {
optional
.as_deref()
.map(|value| op(value).or_bad_request())
.transpose()
})
}
}
impl<'a, 'b> ResultExt for PathParam<'a, 'b> {
type Output = Cow<'a, str>;
/// Returns a result with the parameter value if it exists.
#[inline]
fn into_result(self) -> Result<Self::Output, Error> {
self.param
.and_then(|param| param.slice(self.source))
.ok_or_else(|| Error::require_path_param(self.name))
.and_then(|value| self.encoding.decode_as(self.name, value))
}
}
impl<'a, 'b> QueryParam<'a, 'b> {
#[inline]
pub(crate) fn new(
source: Option<&'a str>,
range: Option<[Option<usize>; 2]>,
name: &'b str,
) -> Self {
Self {
encoding: UriEncoding::Unencoded,
source,
range,
name,
}
}
/// Returns a new `Param` that will percent-decode the parameter value with
/// when the parameter is converted to a result.
///
#[inline]
pub fn percent_decode(self) -> Self {
Self {
encoding: UriEncoding::Percent,
..self
}
}
/// Calls [`str::parse`] on the parameter value if it exists and returns the
/// result. If the param is encoded, it will be decoded before it is parsed.
///
pub fn parse<U>(self) -> Result<U, Error>
where
U: FromStr,
Error: From<U::Err>,
{
self.into_result()
.and_then(|value| value.as_ref().parse().or_bad_request())
}
pub fn ok(self) -> Result<Option<Cow<'a, str>>, Error> {
self.slice()
.map(|value| self.encoding.decode_as(self.name, value))
.transpose()
}
/// Converts `self` into `Result<Option<T>, Error>` by calling the provided
/// closure.
///
/// This provides a way to apply a fallible operation to the optional value
/// contained in `self` without bailing out of lazy evaluation.
///
/// If an error occurs during the conversion, a 400 Bad Request response is
/// returned.
///
/// # Example
///
/// ```
/// use uuid::Uuid;
/// use via::{Next, Request, Response};
///
/// async fn hello(request: Request, _: Next) -> via::Result {
/// // Parse errors occur when the conversion is performed.
/// let id_opt: Option<Uuid> = request.param("id").ok_and_then(str::parse)?;
///
/// if let Some(id) = id_opt {
/// Response::build().text(format!("Hello, {}!", id))
/// } else {
/// Response::build().status(404).text("not found.")
/// }
/// }
/// ```
pub fn ok_and_then<F, T, E>(self, op: F) -> Result<Option<T>, Error>
where
F: FnOnce(&str) -> Result<T, E>,
Error: From<E>,
{
self.ok().and_then(|option| {
option
.as_deref()
.map(|value| op(value).or_bad_request())
.transpose()
})
}
}
impl<'a, 'b> QueryParam<'a, 'b> {
/// Returns a new `Param` that will percent-decode the parameter value with
/// when the parameter is converted to a result.
///
#[inline]
fn slice(&self) -> Option<&'a str> {
self.source
.zip(self.range)
.and_then(|(source, span)| match span {
[Some(from), Some(to)] if from == to => None,
[Some(from), Some(to)] => source.get(from..to),
[Some(from), None] => source.get(from..),
[None, _] => None,
})
}
}
impl<'a, 'b> ResultExt for QueryParam<'a, 'b> {
type Output = Cow<'a, str>;
/// Returns a result with the parameter value if it exists.
#[inline]
fn into_result(self) -> Result<Self::Output, Error> {
self.slice()
.ok_or_else(|| Error::require_query_param(self.name))
.and_then(|value| self.encoding.decode_as(self.name, value))
}
}