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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! The Sycamore Router.

// Alias self to sycamore_router for proc-macros.
extern crate self as sycamore_router;

mod router;

pub use sycamore_router_macro::Route;

use std::str::FromStr;

pub use router::*;

/// Trait that is implemented for `enum`s that can match routes.
///
/// This trait should not be implemented manually. Use the [`Route`](derive@Route) derive macro
/// instead.
pub trait Route: Sized {
    /// Matches a route with the given path segments. Note that in general, empty segments should be
    /// filtered out before passed as an argument.
    ///
    /// It is likely that you are looking for the [`Route::match_path`] method instead.
    fn match_route(segments: &[&str]) -> Self;

    /// Matches a route with the given path.
    fn match_path(path: &str) -> Self {
        let segments = path
            .split('/')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>();
        Self::match_route(&segments)
    }
}

/// Represents an URL segment or segments.
#[derive(Clone)]
pub enum Segment {
    /// Match a specific segment.
    Param(String),
    /// Match an arbitrary segment that is captured.
    DynParam,
    /// Match an arbitrary amount of segments that are captured.
    DynSegments,
}

/// Represents a capture of an URL segment or segments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Capture<'a> {
    DynParam(&'a str),
    DynSegments(Vec<&'a str>),
}

impl<'a> Capture<'a> {
    pub fn as_dyn_param(&self) -> Option<&&'a str> {
        if let Self::DynParam(v) = self {
            Some(v)
        } else {
            None
        }
    }

    pub fn as_dyn_segments(&self) -> Option<&Vec<&'a str>> {
        if let Self::DynSegments(v) = self {
            Some(v)
        } else {
            None
        }
    }
}

/// A list of [`Segment`]s.
#[derive(Clone)]
pub struct RoutePath {
    segments: Vec<Segment>,
}

impl RoutePath {
    pub fn new(segments: Vec<Segment>) -> Self {
        Self { segments }
    }

    pub fn match_path<'a>(&self, path: &[&'a str]) -> Option<Vec<Capture<'a>>> {
        let mut paths = path.iter();
        let mut segments = self.segments.iter();
        let mut captures = Vec::new();

        while let Some(segment) = segments.next() {
            match segment {
                Segment::Param(param) => {
                    if paths.next() != Some(&param.as_str()) {
                        return None;
                    }
                }
                Segment::DynParam => {
                    if let Some(p) = paths.next() {
                        captures.push(Capture::DynParam(*p));
                    } else {
                        return None;
                    }
                }
                Segment::DynSegments => {
                    if let Some(next_segment) = segments.next() {
                        // Capture until match with Segment::Param.
                        match next_segment {
                            Segment::Param(next_param) => {
                                let mut capture = Vec::new();
                                for next_path in &mut paths {
                                    if next_path == next_param {
                                        captures.push(Capture::DynSegments(capture));
                                        break;
                                    } else {
                                        capture.push(next_path);
                                    }
                                }
                            }
                            _ => unreachable!("segment following DynSegments cannot be dynamic"),
                        }
                    } else {
                        // All remaining segments are captured.
                        let mut capture = Vec::new();
                        for next_path in &mut paths {
                            capture.push(*next_path);
                        }
                        captures.push(Capture::DynSegments(capture));
                    }
                }
            }
        }

        if paths.next().is_some() {
            return None; // Leftover segments in paths.
        }

        Some(captures)
    }
}

/// Fallible conversion between a param capture into a value.
///
/// Implemented for all types that implement [`FromStr`] by default.
pub trait TryFromParam: Sized {
    /// Creates a new value of this type from the given param. Returns `None` if the param cannot
    /// be converted into a value of this type.
    #[must_use]
    fn try_from_param(param: &str) -> Option<Self>;
}

impl<T> TryFromParam for T
where
    T: FromStr,
{
    fn try_from_param(param: &str) -> Option<Self> {
        param.parse().ok()
    }
}

/// Fallible conversion between a list of param captures into a value.
pub trait TryFromSegments: Sized {
    /// Sets the value of the capture variable with the value of `segments`. Returns `false` if
    /// unsuccessful (e.g. parsing error).
    #[must_use]
    fn try_from_segments(segments: &[&str]) -> Option<Self>;
}

impl<T> TryFromSegments for Vec<T>
where
    T: TryFromParam,
{
    fn try_from_segments(segments: &[&str]) -> Option<Self> {
        let mut tmp = Vec::with_capacity(segments.len());
        for segment in segments {
            let value = T::try_from_param(segment)?;
            tmp.push(value);
        }
        Some(tmp)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use Segment::*;

    fn check(path: &str, route: RoutePath, expected: Option<Vec<Capture>>) {
        let path = path
            .split('/')
            .filter(|s| !s.is_empty())
            .collect::<Vec<_>>();
        assert_eq!(route.match_path(&path), expected);
    }

    #[test]
    fn index_path() {
        check("/", RoutePath::new(Vec::new()), Some(Vec::new()));
    }

    #[test]
    fn static_path_single_segment() {
        check(
            "/path",
            RoutePath::new(vec![Param("path".to_string())]),
            Some(Vec::new()),
        );
    }

    #[test]
    fn static_path_multiple_segments() {
        check(
            "/my/static/path",
            RoutePath::new(vec![
                Param("my".to_string()),
                Param("static".to_string()),
                Param("path".to_string()),
            ]),
            Some(Vec::new()),
        );
    }

    #[test]
    fn do_not_match_if_leftover_segments() {
        check("/path", RoutePath::new(vec![]), None);
        check(
            "/my/static/path",
            RoutePath::new(vec![Param("my".to_string()), Param("static".to_string())]),
            None,
        );
    }

    #[test]
    fn dyn_param_single_segment() {
        check(
            "/abcdef",
            RoutePath::new(vec![DynParam]),
            Some(vec![Capture::DynParam("abcdef")]),
        );
    }

    #[test]
    fn dyn_param_with_leading_segment() {
        check(
            "/id/abcdef",
            RoutePath::new(vec![Param("id".to_string()), DynParam]),
            Some(vec![Capture::DynParam("abcdef")]),
        );
    }

    #[test]
    fn dyn_param_with_leading_and_trailing_segment() {
        check(
            "/id/abcdef/account",
            RoutePath::new(vec![
                Param("id".to_string()),
                DynParam,
                Param("account".to_string()),
            ]),
            Some(vec![Capture::DynParam("abcdef")]),
        );
    }

    #[test]
    fn dyn_param_final_missing_root() {
        check("/", RoutePath::new(vec![DynParam]), None);
    }

    #[test]
    fn dyn_param_final_missing() {
        check(
            "/id",
            RoutePath::new(vec![Param("id".to_string()), DynParam]),
            None,
        );
    }

    #[test]
    fn multiple_dyn_params() {
        check(
            "/a/b",
            RoutePath::new(vec![DynParam, DynParam]),
            Some(vec![Capture::DynParam("a"), Capture::DynParam("b")]),
        );
    }

    #[test]
    fn dyn_segments_at_root() {
        check(
            "/a/b/c",
            RoutePath::new(vec![DynSegments]),
            Some(vec![Capture::DynSegments(vec!["a", "b", "c"])]),
        );
    }

    #[test]
    fn dyn_segments_final() {
        check(
            "/id/a/b/c",
            RoutePath::new(vec![Param("id".to_string()), DynSegments]),
            Some(vec![Capture::DynSegments(vec!["a", "b", "c"])]),
        );
    }

    #[test]
    fn dyn_segments_capture_lazy() {
        check(
            "/id/a/b/c/end",
            RoutePath::new(vec![
                Param("id".to_string()),
                DynSegments,
                Param("end".to_string()),
            ]),
            Some(vec![Capture::DynSegments(vec!["a", "b", "c"])]),
        );
    }

    #[test]
    fn dyn_segments_can_capture_zero_segments() {
        check(
            "/",
            RoutePath::new(vec![DynSegments]),
            Some(vec![Capture::DynSegments(Vec::new())]),
        );
    }

    #[test]
    fn multiple_dyn_segments() {
        check(
            "/a/b/c/param/e/f/g",
            RoutePath::new(vec![DynSegments, Param("param".to_string()), DynSegments]),
            Some(vec![
                Capture::DynSegments(vec!["a", "b", "c"]),
                Capture::DynSegments(vec!["e", "f", "g"]),
            ]),
        );
    }

    mod integration {
        use crate::*;

        #[test]
        fn simple_router() {
            #[derive(Debug, PartialEq, Eq, Route)]
            enum Routes {
                #[to("/")]
                Home,
                #[to("/about")]
                About,
                #[not_found]
                NotFound,
            }

            assert_eq!(Routes::match_route(&[]), Routes::Home);
            assert_eq!(Routes::match_route(&["about"]), Routes::About);
            assert_eq!(Routes::match_route(&["404"]), Routes::NotFound);
            assert_eq!(
                Routes::match_route(&["about", "something"]),
                Routes::NotFound
            );
        }

        #[test]
        fn router_dyn_params() {
            #[derive(Debug, PartialEq, Eq, Route)]
            enum Routes {
                #[to("/account/<id>")]
                Account { id: u32 },
                #[not_found]
                NotFound,
            }

            assert_eq!(
                Routes::match_route(&["account", "123"]),
                Routes::Account { id: 123 }
            );
            assert_eq!(Routes::match_route(&["account", "-1"]), Routes::NotFound);
            assert_eq!(Routes::match_route(&["account", "abc"]), Routes::NotFound);
            assert_eq!(Routes::match_route(&["account"]), Routes::NotFound);
        }

        #[test]
        fn router_multiple_dyn_params() {
            #[derive(Debug, PartialEq, Eq, Route)]
            enum Routes {
                #[to("/hello/<name>/<age>")]
                Hello { name: String, age: u32 },
                #[not_found]
                NotFound,
            }

            assert_eq!(
                Routes::match_route(&["hello", "Bob", "21"]),
                Routes::Hello {
                    name: "Bob".to_string(),
                    age: 21
                }
            );
            assert_eq!(
                Routes::match_route(&["hello", "21", "Bob"]),
                Routes::NotFound
            );
            assert_eq!(Routes::match_route(&["hello"]), Routes::NotFound);
        }

        #[test]
        fn router_multiple_dyn_segments() {
            #[derive(Debug, PartialEq, Eq, Route)]
            enum Routes {
                #[to("/path/<path..>")]
                Path { path: Vec<String> },
                #[to("/numbers/<numbers..>")]
                Numbers { numbers: Vec<u32> },
                #[not_found]
                NotFound,
            }

            assert_eq!(
                Routes::match_route(&["path", "a", "b", "c"]),
                Routes::Path {
                    path: vec!["a".to_string(), "b".to_string(), "c".to_string()]
                }
            );
            assert_eq!(
                Routes::match_route(&["numbers", "1", "2", "3"]),
                Routes::Numbers {
                    numbers: vec![1, 2, 3]
                }
            );
            assert_eq!(
                Routes::match_route(&["path"]),
                Routes::Path { path: Vec::new() }
            );
        }

        #[test]
        fn router_multiple_dyn_segments_match_lazy() {
            #[derive(Debug, PartialEq, Eq, Route)]
            enum Routes {
                #[to("/path/<path..>/end")]
                Path { path: Vec<u32> },
                #[not_found]
                NotFound,
            }

            assert_eq!(
                Routes::match_route(&["path", "1", "2", "end"]),
                Routes::Path { path: vec![1, 2] }
            );
            assert_eq!(
                Routes::match_route(&["path", "end"]),
                Routes::Path { path: Vec::new() }
            );
            assert_eq!(
                Routes::match_route(&["path", "1", "end", "2"]),
                Routes::NotFound
            );
        }

        #[test]
        fn router_dyn_param_before_dyn_segment() {
            #[derive(Debug, PartialEq, Eq, Route)]
            enum Routes {
                #[to("/<param>/<segments..>")]
                Path {
                    param: String,
                    segments: Vec<String>,
                },
                #[not_found]
                NotFound,
            }

            assert_eq!(
                Routes::match_route(&["path", "1", "2"]),
                Routes::Path {
                    param: "path".to_string(),
                    segments: vec!["1".to_string(), "2".to_string()]
                }
            );
        }
    }
}