topcoat-router 0.9.0

A modular, batteries-included Rust web framework for server-rendered apps.
Documentation
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use std::{iter::FusedIterator, slice};

use percent_encoding::percent_decode_str;
use topcoat_core::context::{Cx, request_context};

use crate::{Path, PathSegment, PathSegments, endpoint};

/// A typed view of a path parameter declared by the `path_param!` macro.
///
/// This trait is implemented by the macro and is not meant to be implemented by
/// hand. Read the value with the [`path_param`] free function rather than
/// calling the trait method directly.
pub trait PathParam {
    /// The value produced for a request bound to lifetime `'cx`.
    ///
    /// The output depends on whether the declaration is parsed and whether it
    /// captures one segment or the rest of the path. See the `path_param!`
    /// macro for each form.
    type Output<'cx>;

    /// Reads the parameter from the request `cx` belongs to.
    ///
    /// Call [`path_param::<T>(cx)`](path_param) instead: this method is sealed
    /// behind [`PathParamSealed`] and cannot be invoked directly.
    #[doc(hidden)]
    #[track_caller]
    fn path_param(cx: &Cx, _: PathParamSealed) -> Self::Output<'_>;
}

/// Reads a typed path parameter from the matched route's path.
///
/// See the `path_param!` macro for details.
///
/// # Panics
///
/// Panics if the matched route's path does not capture the parameter.
#[inline]
#[must_use]
#[track_caller]
pub fn path_param<T: PathParam + ?Sized>(cx: &Cx) -> T::Output<'_> {
    T::path_param(cx, PathParamSealed::new())
}

/// Iterates over the raw path parameters captured by the matched route, as
/// `(name, value)` pairs.
///
/// The names come from the matched endpoint's path, so the pairs arrive in the
/// order that path declares them.
///
/// # Panics
///
/// Panics if the request matched no endpoint.
#[inline]
#[track_caller]
pub fn raw_path_params(cx: &Cx) -> RawPathParamsIter<'_> {
    let params = request_context::<RawPathParams>(cx);
    RawPathParamsIter {
        segments: ParamSegments::new(endpoint(cx).path()),
        values: params.values.iter(),
        catch_all: &params.catch_all,
    }
}

/// Reads one decoded segment for an implementation generated by
/// the `path_param!` macro.
#[doc(hidden)]
#[must_use]
#[track_caller]
pub fn path_param_segment<'cx>(cx: &'cx Cx, name: &str) -> &'cx str {
    match find(cx, name) {
        Some(RawPathParamValue::Segment(value)) => value,
        Some(RawPathParamValue::CatchAll { .. }) => {
            panic!("path parameter \"{name}\" captured multiple segments")
        }
        None => panic!("path parameter \"{name}\" was not found in request path"),
    }
}

/// Reads decoded catch-all segments for an implementation generated by
/// the `path_param!` macro.
#[doc(hidden)]
#[track_caller]
pub fn path_param_segments<'cx>(cx: &'cx Cx, name: &str) -> CatchAllSegments<'cx> {
    match find(cx, name) {
        Some(RawPathParamValue::CatchAll { segments, .. }) => segments,
        Some(RawPathParamValue::Segment(_)) => {
            panic!("path parameter \"{name}\" captured one segment")
        }
        None => panic!("path parameter \"{name}\" was not found in request path"),
    }
}

/// Returns the value the matched route captured for `name`.
#[track_caller]
fn find<'cx>(cx: &'cx Cx, name: &str) -> Option<RawPathParamValue<'cx>> {
    raw_path_params(cx).find_map(|(param, value)| (param == name).then_some(value))
}

/// A value captured by the matched route.
///
/// Which form a parameter takes is fixed by the path that declares it: `{name}`
/// captures one segment, `{*name}` captures the rest of the path.
#[derive(Debug, Clone)]
pub enum RawPathParamValue<'params> {
    /// A single URL segment, percent-decoded.
    Segment(&'params str),
    /// The rest of the URL, captured by a catch-all.
    CatchAll {
        /// The tail as it appeared in the URL, with its `/` separators and
        /// percent escapes left alone.
        tail: &'params str,
        /// The tail's segments, each decoded on its own, so an encoded slash
        /// stays inside its segment instead of becoming a separator.
        segments: CatchAllSegments<'params>,
    },
}

impl<'params> RawPathParamValue<'params> {
    /// Returns the value as a single string: the decoded segment, or the
    /// catch-all tail as the URL spelled it.
    #[must_use]
    pub fn as_str(&self) -> &'params str {
        match self {
            Self::Segment(value) => value,
            Self::CatchAll { tail, .. } => tail,
        }
    }
}

/// Decoded segments captured by a catch-all path parameter.
///
/// This iterator yields one `&str` per URL segment. An encoded slash remains
/// part of its segment instead of becoming a separator.
#[derive(Debug, Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct CatchAllSegments<'params> {
    inner: slice::Iter<'params, Box<str>>,
}

impl<'params> CatchAllSegments<'params> {
    fn new(segments: &'params [Box<str>]) -> Self {
        Self {
            inner: segments.iter(),
        }
    }
}

impl<'params> Iterator for CatchAllSegments<'params> {
    type Item = &'params str;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(Box::as_ref)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl DoubleEndedIterator for CatchAllSegments<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(Box::as_ref)
    }
}

impl ExactSizeIterator for CatchAllSegments<'_> {}
impl FusedIterator for CatchAllSegments<'_> {}

/// The values a matched route captured, in the order the endpoint's path
/// declares them.
///
/// The path names the values and says how each one captures, so only the values
/// themselves are held here. Read them with [`raw_path_params`].
#[derive(Debug, Clone, Default)]
pub struct RawPathParams {
    /// One value per capturing segment of the endpoint's path: a decoded URL
    /// segment for a parameter, the encoded tail for a catch-all.
    values: Vec<Box<str>>,
    /// The catch-all tail split into separately decoded segments, empty unless
    /// the path ends in a catch-all.
    catch_all: Box<[Box<str>]>,
}

impl RawPathParams {
    /// Captures the values a match against `path` produced.
    ///
    /// `values` must yield one value per capturing segment of `path`, in the
    /// order those segments appear, which is the order a match reports them in.
    /// Everything is decoded here so that reading a parameter later never has
    /// to allocate.
    pub(crate) fn from_match<'values>(
        path: &Path,
        values: impl IntoIterator<Item = &'values str>,
    ) -> Self {
        let mut values = values.into_iter();
        let mut params = Self::default();
        for (segment, value) in ParamSegments::new(path).zip(values.by_ref()) {
            match segment {
                // A catch-all ends the path, so there is only ever one of them
                // and it owns the segment list.
                PathSegment::CatchAll(_) => {
                    params.catch_all = value.split('/').map(decode).collect();
                    params.values.push(Box::from(value));
                }
                _ => params.values.push(decode(value)),
            }
        }
        debug_assert!(
            values.next().is_none(),
            "the match captured more values than `{path}` declares parameters"
        );
        params
    }
}

/// An iterator over the raw path parameters captured by a route, created by
/// [`raw_path_params`].
#[derive(Debug, Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct RawPathParamsIter<'params> {
    segments: ParamSegments<'params>,
    values: slice::Iter<'params, Box<str>>,
    catch_all: &'params [Box<str>],
}

impl<'params> RawPathParamsIter<'params> {
    /// Pairs a capturing segment with the value it captured.
    fn pair(
        &self,
        segment: &PathSegment<'params>,
        value: &'params str,
    ) -> Option<(&'params str, RawPathParamValue<'params>)> {
        let name = segment.param_name()?;
        let value = match segment {
            PathSegment::CatchAll(_) => RawPathParamValue::CatchAll {
                tail: value,
                segments: CatchAllSegments::new(self.catch_all),
            },
            // Every other capturing segment captures a single segment.
            _ => RawPathParamValue::Segment(value),
        };
        Some((name, value))
    }
}

impl<'params> Iterator for RawPathParamsIter<'params> {
    type Item = (&'params str, RawPathParamValue<'params>);

    fn next(&mut self) -> Option<Self::Item> {
        let segment = self.segments.next()?;
        let value = self.values.next()?;
        self.pair(&segment, value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.values.size_hint()
    }
}

impl DoubleEndedIterator for RawPathParamsIter<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        let segment = self.segments.next_back()?;
        let value = self.values.next_back()?;
        self.pair(&segment, value)
    }
}

impl ExactSizeIterator for RawPathParamsIter<'_> {}
impl FusedIterator for RawPathParamsIter<'_> {}

/// The capturing segments of a path, in the order they appear, which is the
/// order their values were captured in.
#[derive(Debug, Clone)]
struct ParamSegments<'path>(PathSegments<'path>);

impl<'path> ParamSegments<'path> {
    fn new(path: &'path Path) -> Self {
        Self(path.segments())
    }
}

impl<'path> Iterator for ParamSegments<'path> {
    type Item = PathSegment<'path>;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.find(|segment| segment.param_name().is_some())
    }
}

impl DoubleEndedIterator for ParamSegments<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.rfind(|segment| segment.param_name().is_some())
    }
}

impl FusedIterator for ParamSegments<'_> {}

fn decode(value: &str) -> Box<str> {
    percent_decode_str(value)
        .decode_utf8_lossy()
        .into_owned()
        .into_boxed_str()
}

/// A guard that limits [`PathParam::path_param`] to being called through the
/// [`path_param`] free function.
///
/// It cannot be constructed outside this crate, so the only way to invoke the
/// trait method is via [`path_param`].
#[doc(hidden)]
#[derive(Debug)]
pub struct PathParamSealed(());

impl PathParamSealed {
    pub(crate) fn new() -> Self {
        Self(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::router::test_matched_cx;

    /// Builds the request context of a match of `values` against `path`, as the
    /// router assembles one.
    fn matched<'values>(path: &str, values: impl IntoIterator<Item = &'values str>) -> Cx {
        let path = Path::new(path);
        let params = RawPathParams::from_match(path, values);
        test_matched_cx(path).with(params)
    }

    /// Collects the pairs an iteration yields, with each value as one string.
    fn pairs(cx: &Cx) -> Vec<(&str, &str)> {
        raw_path_params(cx)
            .map(|(name, value)| (name, value.as_str()))
            .collect()
    }

    #[test]
    fn decodes_a_single_segment() {
        let cx = matched("/users/{id}", ["a%20b"]);

        assert_eq!(path_param_segment(&cx, "id"), "a b");
        assert_eq!(pairs(&cx), [("id", "a b")]);
    }

    #[test]
    fn keeps_a_catch_all_tail_raw() {
        let cx = matched("/docs/{*path}", ["guides/getting%2Fstarted"]);

        assert_eq!(pairs(&cx), [("path", "guides/getting%2Fstarted")]);
        // Only the separators the URL spelled out split the tail, so an encoded
        // slash stays inside its segment.
        assert_eq!(
            path_param_segments(&cx, "path").collect::<Vec<_>>(),
            ["guides", "getting/started"]
        );
    }

    #[test]
    fn reads_a_single_segment_catch_all() {
        let cx = matched("/docs/{*path}", ["readme.md"]);

        assert_eq!(
            path_param_segments(&cx, "path").collect::<Vec<_>>(),
            ["readme.md"]
        );
    }

    #[test]
    fn iteration_carries_both_views_of_a_catch_all() {
        let cx = matched("/docs/{*path}", ["a/b%2Fc"]);

        let (name, value) = raw_path_params(&cx).next().unwrap();
        let RawPathParamValue::CatchAll { tail, segments } = value else {
            panic!("a catch-all segment captures a catch-all value");
        };
        assert_eq!(name, "path");
        assert_eq!(tail, "a/b%2Fc");
        assert_eq!(segments.collect::<Vec<_>>(), ["a", "b/c"]);
    }

    #[test]
    fn only_capturing_segments_are_named() {
        let cx = matched("/users/(auth)/{id}/docs/{*path}", ["42", "a/b"]);

        // Static and group segments capture nothing, so they name no value.
        assert_eq!(pairs(&cx), [("id", "42"), ("path", "a/b")]);
    }

    #[test]
    fn iterates_from_either_end() {
        let cx = matched("/users/{id}/docs/{*path}", ["42", "a/b"]);
        let params = raw_path_params(&cx);

        assert_eq!(params.len(), 2);
        assert_eq!(
            params
                .rev()
                .map(|(name, value)| (name, value.as_str()))
                .collect::<Vec<_>>(),
            [("path", "a/b"), ("id", "42")]
        );
    }

    #[test]
    fn a_path_without_parameters_captures_nothing() {
        let cx = matched("/users", []);

        assert_eq!(raw_path_params(&cx).count(), 0);
        assert!(find(&cx, "id").is_none());
    }

    #[test]
    fn missing_parameter_is_absent() {
        let cx = matched("/users/{id}", ["42"]);

        assert!(find(&cx, "slug").is_none());
    }

    #[test]
    #[should_panic(expected = "was not found in request path")]
    fn reading_a_missing_parameter_panics() {
        let cx = matched("/users/{id}", ["42"]);

        let _ = path_param_segment(&cx, "slug");
    }

    #[test]
    #[should_panic(expected = "captured multiple segments")]
    fn reading_a_catch_all_as_one_segment_panics() {
        let cx = matched("/docs/{*path}", ["a/b"]);

        let _ = path_param_segment(&cx, "path");
    }

    #[test]
    #[should_panic(expected = "captured one segment")]
    fn reading_one_segment_as_a_catch_all_panics() {
        let cx = matched("/users/{id}", ["42"]);

        let _ = path_param_segments(&cx, "id");
    }

    #[test]
    fn segments_count_without_consuming() {
        let cx = matched("/docs/{*path}", ["a/b/c"]);
        let segments = path_param_segments(&cx, "path");

        assert_eq!(segments.len(), 3);
        assert_eq!(segments.rev().collect::<Vec<_>>(), ["c", "b", "a"]);
    }
}