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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
use std::{
    borrow::{Borrow, Cow},
    fmt::{Display, Write},
    iter::FusedIterator,
    mem,
    ops::{AddAssign, Deref},
};

use ref_cast::{RefCastCustom, ref_cast_custom};

/// A borrowed route pattern made of `/`-separated segments.
///
/// A `Path` consists of `/`-separated segments, where each segment is one of:
/// - **`Static`**: a literal string (e.g. `users`)
/// - **`Param`**: a dynamic parameter in braces (e.g. `{id}`)
/// - **`CatchAll`**: a wildcard tail in braces with `*` (e.g. `{*rest}`)
/// - **`Group`**: a logical grouping in parentheses (e.g. `(auth)`), stripped when converting to a
///   `matchit` path
///
/// Create one from a string with [`Path::new`]. The root path `"/"` is stored
/// as an empty string and has no segments.
///
/// A trailing slash is significant, so `/users/` and `/users` are different
/// paths. It is represented by an empty final `Static` segment. No other
/// segment may be empty.
///
/// # Examples
///
/// ```
/// use topcoat_router::{Path, PathSegment};
///
/// let path = Path::new("/users/(group)/{id}");
/// assert_eq!(path.segments().count(), 3);
/// assert_eq!(path.to_matchit_path(), "/users/{id}");
///
/// let slashed = Path::new("/users/");
/// assert_eq!(slashed.segments().last(), Some(PathSegment::Static("")));
/// assert_eq!(slashed.to_matchit_path(), "/users/");
/// ```
#[derive(Debug, PartialEq, Eq, Hash, RefCastCustom)]
#[repr(transparent)]
pub struct Path {
    inner: str,
}

impl Path {
    // The root path "/".
    pub const ROOT: &Path = Path::new("/");

    /// Creates a `&Path` from a string slice.
    ///
    /// The root path `"/"` is stored as an empty string with no segments.
    ///
    /// Use [`from_str`](Path::from_str) to receive an error instead of a panic.
    /// This function also works in const contexts.
    ///
    /// # Panics
    ///
    /// Panics if `s` is not a well-formed path; see [`PathError`] for the
    /// conditions that are rejected.
    #[must_use]
    #[track_caller]
    pub const fn new(s: &str) -> &Self {
        match Self::from_str(s) {
            Ok(path) => path,
            Err(err) => panic!("{}", err.message()),
        }
    }

    /// Creates a `&Path` from a string slice, validating its segments.
    ///
    /// The root path `"/"` is stored as an empty string. Other paths contain
    /// `/`-prefixed [`PathSegment`]s. Only the final segment may be empty,
    /// representing a trailing slash.
    ///
    /// # Errors
    ///
    /// Returns [`PathError`] if `s` is not a valid path: it must be empty, be
    /// the root `"/"`, or be a sequence of `/`-prefixed valid segments.
    #[allow(clippy::should_implement_trait)]
    pub const fn from_str(s: &str) -> Result<&Self, PathError> {
        let s = match s.as_bytes() {
            [b'/'] => "",
            _ => s,
        };
        let bytes = s.as_bytes();
        let len = bytes.len();
        // The root path is empty and has no segments to validate.
        if len == 0 {
            return Ok(Self::new_unchecked(s));
        }
        if bytes[0] != b'/' {
            return Err(PathError::MissingLeadingSlash);
        }
        // Walk the `/`-separated segments, validating each `bytes[start..end)`.
        // The last segment may be empty, as long as it is not also the first:
        // that would be `//`, which is not the root with a trailing slash.
        let mut start = 1;
        let mut i = 1;
        while i <= len {
            if i == len || bytes[i] == b'/' {
                let trailing_slash = i == len && start == len && start > 1;
                if !trailing_slash && let Err(err) = validate_segment(bytes, start, i) {
                    return Err(err);
                }
                start = i + 1;
            }
            i += 1;
        }
        Ok(Self::new_unchecked(s))
    }

    /// Creates a `&Path` from a string slice without validating or normalizing it.
    ///
    /// The caller must provide a valid, normalized path, such as the string
    /// from another `Path`. In particular, use an empty string for the root.
    /// Other input can produce incorrect segment results.
    #[ref_cast_custom]
    #[must_use]
    pub const fn new_unchecked(s: &str) -> &Self;

    /// Returns an iterator over the [`PathSegment`]s of this path.
    ///
    /// The root path yields zero segments.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::{Path, PathSegment};
    ///
    /// let path = Path::new("/users/{id}/(auth)");
    /// let segs: Vec<_> = path.segments().collect();
    /// assert_eq!(
    ///     segs,
    ///     vec![
    ///         PathSegment::Static("users"),
    ///         PathSegment::Param("id"),
    ///         PathSegment::Group("auth"),
    ///     ]
    /// );
    /// ```
    pub fn segments(&self) -> PathSegments<'_> {
        PathSegments::new(self)
    }

    /// Converts this path to a `matchit`-compatible route string, stripping group
    /// segments.
    ///
    /// Group segments (e.g. `(auth)`) are used for layout matching but are not
    /// part of the URL that the router matches against. This method removes them
    /// and returns the remaining path.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::Path;
    ///
    /// let path = Path::new("/(auth)/dashboard/{id}");
    /// assert_eq!(path.to_matchit_path(), "/dashboard/{id}");
    ///
    /// let root = Path::new("/");
    /// assert_eq!(root.to_matchit_path(), "/");
    ///
    /// // A path made up entirely of group segments collapses to the root URL,
    /// // e.g. a page in a `(marketing)` group that should serve `/`.
    /// let group_root = Path::new("/(marketing)");
    /// assert_eq!(group_root.to_matchit_path(), "/");
    /// ```
    #[must_use]
    pub fn to_matchit_path(&self) -> Cow<'static, str> {
        if self.inner.is_empty() {
            return Cow::Borrowed("/");
        }
        let stripped = self
            .segments()
            .filter(|s| !s.is_group())
            .collect::<PathBuf>()
            .inner;
        // Stripping groups can leave nothing behind (e.g. `/(marketing)` or
        // `/(a)/(b)`). Such a path addresses the root URL, so normalize the empty
        // result back to "/": matchit rejects route paths that don't start with "/".
        if stripped.is_empty() {
            return Cow::Borrowed("/");
        }
        Cow::Owned(stripped)
    }

    /// Returns `true` if this path starts with the given prefix path.
    ///
    /// Compares segments using [`PathSegment`] equality, including groups.
    /// Parameters must match by name. They do not match arbitrary values as
    /// they do in [`matches`](Self::matches).
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::Path;
    ///
    /// let path = Path::new("/users/{id}/posts");
    /// assert!(path.starts_with(Path::new("/users/{id}")));
    /// assert!(!path.starts_with(Path::new("/posts/{id}")));
    /// ```
    #[must_use]
    pub fn starts_with(&self, other: &Path) -> bool {
        if self.inner.len() < other.inner.len() {
            return false;
        }
        self.segments().zip(other.segments()).all(|(a, b)| a == b)
    }

    /// Returns a new path with the segments of `other` appended to this one.
    ///
    /// Joining the root path onto either side leaves the other path unchanged.
    /// A trailing slash on this path is dropped when segments follow it.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::Path;
    ///
    /// let base = Path::new("/settings");
    /// assert_eq!(base.join(Path::new("/export")).as_str(), "/settings/export");
    /// assert_eq!(base.join(Path::ROOT).as_str(), "/settings");
    /// assert_eq!(Path::ROOT.join(base).as_str(), "/settings");
    /// assert_eq!(
    ///     Path::new("/settings/").join(Path::new("/export")).as_str(),
    ///     "/settings/export"
    /// );
    /// ```
    #[must_use]
    pub fn join(&self, other: &Path) -> PathBuf {
        let mut buf = self.to_owned();
        buf += other;
        buf
    }

    /// Returns `true` if `url`, a concrete URL path, matches this route path
    /// exactly.
    ///
    /// Each segment is matched against the corresponding URL segment:
    /// - **`Static`** segments must equal the URL segment.
    /// - **`Param`** segments match any single non-empty URL segment.
    /// - **`CatchAll`** segments match the remaining URL (including any `/` separators) and require
    ///   at least one segment to be present.
    /// - **`Group`** segments are ignored, as they are not part of the URL.
    ///
    /// A trailing `/` is significant: a path without one does not match a URL
    /// with one, and the other way around.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::Path;
    ///
    /// let path = Path::new("/users/{id}/posts");
    /// assert!(path.matches("/users/42/posts"));
    /// assert!(!path.matches("/users/42"));
    ///
    /// // Group segments are ignored.
    /// assert!(Path::new("/(auth)/dashboard").matches("/dashboard"));
    ///
    /// // A catch-all matches the remainder of the URL.
    /// assert!(Path::new("/files/{*rest}").matches("/files/a/b/c"));
    ///
    /// // A trailing slash has to match.
    /// assert!(Path::new("/users/").matches("/users/"));
    /// assert!(!Path::new("/users/").matches("/users"));
    /// assert!(!Path::new("/users").matches("/users/"));
    /// ```
    #[must_use]
    pub fn matches(&self, url: &str) -> bool {
        // Splits the `/`-separated URL body into its first segment and the
        // remainder after the separator, e.g. "users/42" into ("users",
        // Some("42")) and "users" into ("users", None): the remainder is `None`
        // once the body is used up without a separator left over.
        fn first_segment(rest: &str) -> (&str, Option<&str>) {
            match rest.split_once('/') {
                Some((head, tail)) => (head, Some(tail)),
                None => (rest, None),
            }
        }

        // Drop a single leading `/`; what remains is the `/`-separated body,
        // e.g. "users/42/posts". The root URL "/" has nothing left to consume,
        // while a trailing separator leaves an empty body behind.
        let body = url.strip_prefix('/').unwrap_or(url);
        let mut rest = (!body.is_empty()).then_some(body);
        for segment in self.segments() {
            match segment {
                // Groups exist only for layout matching and never appear in a URL.
                PathSegment::Group(_) => {}
                // A trailing slash matches when the URL ended in a separator
                // with nothing after it.
                PathSegment::Static("") => return rest == Some(""),
                PathSegment::Static(expected) => match rest.map(first_segment) {
                    Some((head, tail)) if head == expected => rest = tail,
                    _ => return false,
                },
                // A parameter matches any single non-empty segment. An empty
                // one (as in `/users//`) never routes, so reject it here too.
                PathSegment::Param(_) => match rest.map(first_segment) {
                    Some((head, tail)) if !head.is_empty() => rest = tail,
                    _ => return false,
                },
                // A catch-all swallows the whole remainder, so nothing can
                // follow it and there is never leftover URL to reject.
                PathSegment::CatchAll(_) => return rest.is_some_and(|rest| !rest.is_empty()),
            }
        }
        // Every route segment matched; the URL must also be used up.
        rest.is_none()
    }

    /// Returns the string backing this path.
    ///
    /// The root path is backed by the empty string rather than `"/"`, matching
    /// the normalization [`new`](Path::new) applies.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::Path;
    ///
    /// assert_eq!(Path::new("/users/{id}").as_str(), "/users/{id}");
    /// assert_eq!(Path::new("/").as_str(), "");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.inner
    }

    /// Returns `true` if this path ends in a `/`, which is to say its last
    /// segment is empty. The root path does not.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::Path;
    ///
    /// assert!(Path::new("/users/").has_trailing_slash());
    /// assert!(!Path::new("/users").has_trailing_slash());
    /// assert!(!Path::new("/").has_trailing_slash());
    /// ```
    #[must_use]
    pub fn has_trailing_slash(&self) -> bool {
        self.inner.ends_with('/')
    }

    /// Returns the length of the string backing this path.
    ///
    /// Measures bytes, not characters.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if `self` has no path segments, i.e. `self` is the root path `/`.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Display for Path {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl ToOwned for Path {
    type Owned = PathBuf;

    fn to_owned(&self) -> Self::Owned {
        PathBuf {
            inner: self.inner.to_owned(),
        }
    }
}

impl<'a> From<&'a Path> for Cow<'a, Path> {
    fn from(value: &'a Path) -> Self {
        Self::Borrowed(value)
    }
}

/// An iterator over the [`PathSegment`]s of a [`Path`], created by
/// [`Path::segments`].
#[derive(Debug, Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct PathSegments<'path> {
    /// The `/`-separated body left to walk, without a leading `/`.
    rest: &'path str,
    /// Whether the body is used up. It is tracked separately because the last
    /// segment leaves `rest` empty, which is also how the root path starts out.
    done: bool,
}

impl<'path> PathSegments<'path> {
    fn new(path: &'path Path) -> Self {
        match path.inner.strip_prefix('/') {
            Some(rest) => Self { rest, done: false },
            // The root path is backed by the empty string and has no segments.
            None => Self {
                rest: "",
                done: true,
            },
        }
    }

    /// Marks the body as used up and returns what was left of it, the segment
    /// at whichever end the caller was reading.
    fn last_segment(&mut self) -> &'path str {
        self.done = true;
        mem::take(&mut self.rest)
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        let segment = match self.rest.split_once('/') {
            Some((segment, rest)) => {
                self.rest = rest;
                segment
            }
            None => self.last_segment(),
        };
        // The path was validated on construction, so its segments need no
        // re-validation here.
        Some(PathSegment::new_unchecked(segment))
    }
}

impl DoubleEndedIterator for PathSegments<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        let segment = match self.rest.rsplit_once('/') {
            Some((rest, segment)) => {
                self.rest = rest;
                segment
            }
            None => self.last_segment(),
        };
        Some(PathSegment::new_unchecked(segment))
    }
}

impl FusedIterator for PathSegments<'_> {}

/// The reason a string could not be parsed into a [`Path`] by
/// [`Path::from_str`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathError {
    /// The path was non-empty but did not start with `/`.
    MissingLeadingSlash,
    /// A segment other than the last was empty, as produced by a doubled `/`.
    EmptySegment,
    /// A `{` parameter or catch-all segment was missing its closing `}`.
    MissingClosingBrace,
    /// A `(` group segment was missing its closing `)`.
    MissingClosingParen,
    /// A static segment contained a `{`, `}`, `(`, or `)`.
    UnexpectedBracket,
    /// A param, catch-all, or group name was empty.
    EmptyName,
    /// A name did not start with an ASCII letter or `_`.
    InvalidNameStart,
    /// A name contained a character other than an ASCII alphanumeric or `_`.
    InvalidNameChar,
}

impl PathError {
    /// A human-readable description of the error.
    const fn message(self) -> &'static str {
        match self {
            Self::MissingLeadingSlash => "invalid path: must be empty or start with `/`",
            Self::EmptySegment => "invalid path: empty segment",
            Self::MissingClosingBrace => "invalid path: missing closing `}`",
            Self::MissingClosingParen => "invalid path: missing closing `)`",
            Self::UnexpectedBracket => "invalid path: unexpected bracket in static segment",
            Self::EmptyName => "invalid path: segment name must not be empty",
            Self::InvalidNameStart => {
                "invalid path: segment name must start with a letter or underscore"
            }
            Self::InvalidNameChar => "invalid path: segment name contains an invalid character",
        }
    }
}

impl Display for PathError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.message())
    }
}

impl std::error::Error for PathError {}

/// An owned route path, similar to [`std::path::PathBuf`] but for URL paths.
///
/// `PathBuf` is the owned counterpart of [`Path`]. It can be built incrementally
/// by adding [`PathSegment`]s or whole [`Path`]s with `+=`, or collected from an
/// iterator of segments.
///
/// # Examples
///
/// ```
/// use topcoat_router::{PathBuf, PathSegment};
///
/// let mut buf = PathBuf::new();
/// buf += PathSegment::Static("users");
/// buf += PathSegment::Param("id");
/// assert_eq!(buf.to_string(), "/users/{id}");
/// ```
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct PathBuf {
    inner: String,
}

impl PathBuf {
    /// Creates a new empty `PathBuf`.
    #[must_use]
    pub fn new() -> Self {
        PathBuf::default()
    }
}

impl Borrow<Path> for PathBuf {
    fn borrow(&self) -> &Path {
        // A `PathBuf` only ever holds a valid path, so skip re-validation.
        Path::new_unchecked(&self.inner)
    }
}

impl From<PathBuf> for Cow<'static, Path> {
    fn from(value: PathBuf) -> Self {
        Self::Owned(value)
    }
}

impl Deref for PathBuf {
    type Target = Path;

    fn deref(&self) -> &Self::Target {
        // A `PathBuf` only ever holds a valid path, so skip re-validation.
        Path::new_unchecked(&self.inner)
    }
}

impl PathBuf {
    /// Drops a trailing slash so that appended segments do not produce an
    /// empty segment in the middle of the path.
    fn pop_trailing_slash(&mut self) {
        if self.inner.ends_with('/') {
            self.inner.pop();
        }
    }
}

impl AddAssign<PathSegment<'_>> for PathBuf {
    fn add_assign(&mut self, rhs: PathSegment<'_>) {
        self.pop_trailing_slash();
        write!(self.inner, "/{rhs}").unwrap();
    }
}

impl AddAssign<&Path> for PathBuf {
    fn add_assign(&mut self, rhs: &Path) {
        if rhs.is_empty() {
            return;
        }
        // Both sides hold a validated path whose root is the empty string, so
        // appending the raw string yields a valid path again.
        self.pop_trailing_slash();
        self.inner.push_str(&rhs.inner);
    }
}

impl<'a> FromIterator<PathSegment<'a>> for PathBuf {
    fn from_iter<T: IntoIterator<Item = PathSegment<'a>>>(iter: T) -> Self {
        let mut buf = PathBuf::new();
        for segment in iter {
            buf += segment;
        }
        buf
    }
}

/// Conversion into a route path, accepted by APIs that take a path prefix.
///
/// A `&'static str` is parsed with [`Path::new`] and panics when it is not a
/// well-formed path; [`Path`], [`PathBuf`], and `Cow<'static, Path>` values
/// convert as they are.
pub trait IntoPath {
    /// Converts the value into a route path.
    ///
    /// # Panics
    ///
    /// Panics if the value is a string that is not a well-formed path.
    #[track_caller]
    fn into_path(self) -> Cow<'static, Path>;
}

impl IntoPath for &'static str {
    #[track_caller]
    fn into_path(self) -> Cow<'static, Path> {
        Cow::Borrowed(Path::new(self))
    }
}

impl IntoPath for &'static Path {
    fn into_path(self) -> Cow<'static, Path> {
        Cow::Borrowed(self)
    }
}

impl IntoPath for PathBuf {
    fn into_path(self) -> Cow<'static, Path> {
        Cow::Owned(self)
    }
}

impl IntoPath for Cow<'static, Path> {
    fn into_path(self) -> Cow<'static, Path> {
        self
    }
}

impl Display for PathBuf {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

/// A single segment of a route [`Path`].
///
/// Topcoat paths use four segment types:
///
/// | Syntax      | Variant    | Example     | Description                                             |
/// |-------------|------------|-------------|---------------------------------------------------------|
/// | `foo`       | `Static`   | `users`     | Literal URL segment                                     |
/// | `{name}`    | `Param`    | `{id}`      | Dynamic parameter, extracted at request time            |
/// | `{*name}`   | `CatchAll` | `{*path}`   | Wildcard tail, matches the rest of the URL              |
/// | `(name)`    | `Group`    | `(auth)`    | Logical grouping for layout matching, stripped from URL |
///
/// Segment names (for `Param`, `CatchAll`, and `Group`) must be valid
/// identifiers: starting with a letter or underscore, containing only
/// ASCII alphanumerics and underscores.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PathSegment<'a> {
    /// A literal URL segment (e.g. `users`).
    Static(&'a str),
    /// A logical grouping segment (e.g. `(auth)`), stripped from the URL path.
    Group(&'a str),
    /// A dynamic parameter segment (e.g. `{id}`).
    Param(&'a str),
    /// A wildcard tail segment (e.g. `{*rest}`), matching the remainder of the URL.
    CatchAll(&'a str),
}

impl<'a> PathSegment<'a> {
    /// Parses a single path segment string into a [`PathSegment`].
    ///
    /// This is the panicking counterpart of [`from_str`](PathSegment::from_str).
    ///
    /// # Panics
    ///
    /// Panics if `s` is not a well-formed segment; see [`PathError`] for the
    /// conditions that are rejected.
    #[must_use]
    #[track_caller]
    pub fn new(s: &'a str) -> Self {
        match Self::from_str(s) {
            Ok(segment) => segment,
            Err(err) => panic!("{}", err.message()),
        }
    }

    /// Parses a single path segment string into a [`PathSegment`], validating it.
    ///
    /// Returns [`PathError`] if `s` is not a well-formed segment: an empty string,
    /// a `{...}`/`(...)` segment missing its closing bracket, a static segment that
    /// contains a bracket, or a name that is not a valid identifier.
    ///
    /// # Errors
    ///
    /// Returns [`PathError`] if `s` is not a well-formed segment.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &'a str) -> Result<Self, PathError> {
        // Validate first, then extract the variant from the now-known-valid input.
        validate_segment(s.as_bytes(), 0, s.len())?;
        Ok(Self::new_unchecked(s))
    }

    /// Parses a single path segment string into a [`PathSegment`] without
    /// validating it.
    ///
    /// The caller must provide a valid segment, such as one from
    /// [`Path::segments`]. Malformed input can produce an incorrect segment
    /// rather than an error.
    #[must_use]
    pub fn new_unchecked(s: &'a str) -> Self {
        if let Some(inner) = s.strip_prefix('{') {
            let inner = inner.strip_suffix('}').unwrap_or(inner);
            match inner.strip_prefix('*') {
                Some(name) => PathSegment::CatchAll(name),
                None => PathSegment::Param(inner),
            }
        } else if let Some(inner) = s.strip_prefix('(') {
            PathSegment::Group(inner.strip_suffix(')').unwrap_or(inner))
        } else {
            PathSegment::Static(s)
        }
    }

    /// Returns `true` if the segment is [`Static`].
    ///
    /// [`Static`]: PathSegment::Static
    #[must_use]
    pub fn is_static(&self) -> bool {
        matches!(self, Self::Static(..))
    }

    /// Returns `true` if the segment is [`Group`].
    ///
    /// [`Group`]: PathSegment::Group
    #[must_use]
    pub fn is_group(&self) -> bool {
        matches!(self, Self::Group(..))
    }

    /// Returns `true` if the segment is [`Param`].
    ///
    /// [`Param`]: PathSegment::Param
    #[must_use]
    pub fn is_param(&self) -> bool {
        matches!(self, Self::Param(..))
    }

    /// Returns `true` if the segment is [`CatchAll`].
    ///
    /// [`CatchAll`]: PathSegment::CatchAll
    #[must_use]
    pub fn is_catch_all(&self) -> bool {
        matches!(self, Self::CatchAll(..))
    }

    /// Returns the inner string if this is a [`Static`](PathSegment::Static) segment.
    #[must_use]
    pub fn as_static(&self) -> Option<&&'a str> {
        if let Self::Static(v) = self {
            Some(v)
        } else {
            None
        }
    }

    /// Returns the inner string if this is a [`Group`](PathSegment::Group) segment.
    #[must_use]
    pub fn as_group(&self) -> Option<&&'a str> {
        if let Self::Group(v) = self {
            Some(v)
        } else {
            None
        }
    }

    /// Returns the name this segment captures a value under, or `None` if it
    /// captures nothing.
    ///
    /// # Examples
    ///
    /// ```
    /// use topcoat_router::PathSegment;
    ///
    /// assert_eq!(PathSegment::Param("id").param_name(), Some("id"));
    /// assert_eq!(PathSegment::CatchAll("rest").param_name(), Some("rest"));
    /// assert_eq!(PathSegment::Static("users").param_name(), None);
    /// ```
    #[must_use]
    pub fn param_name(&self) -> Option<&'a str> {
        match *self {
            Self::Param(name) | Self::CatchAll(name) => Some(name),
            Self::Static(_) | Self::Group(_) => None,
        }
    }

    /// Returns the inner string if this is a [`Param`](PathSegment::Param) segment.
    #[must_use]
    pub fn as_param(&self) -> Option<&&'a str> {
        if let Self::Param(v) = self {
            Some(v)
        } else {
            None
        }
    }

    /// Returns the inner string if this is a [`CatchAll`](PathSegment::CatchAll) segment.
    #[must_use]
    pub fn as_catch_all(&self) -> Option<&&'a str> {
        if let Self::CatchAll(v) = self {
            Some(v)
        } else {
            None
        }
    }
}

/// Validates a single segment `bytes[start..end)` of a [`Path`]. Operates on
/// bytes (rather than a `&str` subslice) so it can run in the `const` context of
/// [`Path::from_str`], and is shared with [`PathSegment::from_str`].
const fn validate_segment(bytes: &[u8], start: usize, end: usize) -> Result<(), PathError> {
    if start >= end {
        return Err(PathError::EmptySegment);
    }
    match bytes[start] {
        b'{' => {
            if bytes[end - 1] != b'}' {
                return Err(PathError::MissingClosingBrace);
            }
            // The name sits between the braces; a leading `*` marks a catch-all.
            let mut name_start = start + 1;
            let name_end = end - 1;
            if name_start < name_end && bytes[name_start] == b'*' {
                name_start += 1;
            }
            validate_ident(bytes, name_start, name_end)
        }
        b'(' => {
            if bytes[end - 1] != b')' {
                return Err(PathError::MissingClosingParen);
            }
            validate_ident(bytes, start + 1, end - 1)
        }
        _ => {
            // A static segment must not contain any of the reserved brackets.
            let mut i = start;
            while i < end {
                match bytes[i] {
                    b'{' | b'}' | b'(' | b')' => return Err(PathError::UnexpectedBracket),
                    _ => {}
                }
                i += 1;
            }
            Ok(())
        }
    }
}

/// Validates that `bytes[start..end)` is a valid identifier: non-empty, starting
/// with an ASCII letter or `_`, and otherwise only ASCII alphanumerics or `_`.
const fn validate_ident(bytes: &[u8], start: usize, end: usize) -> Result<(), PathError> {
    if start >= end {
        return Err(PathError::EmptyName);
    }
    let first = bytes[start];
    if !first.is_ascii_alphabetic() && first != b'_' {
        return Err(PathError::InvalidNameStart);
    }
    let mut i = start + 1;
    while i < end {
        let ch = bytes[i];
        if !ch.is_ascii_alphanumeric() && ch != b'_' {
            return Err(PathError::InvalidNameChar);
        }
        i += 1;
    }
    Ok(())
}

impl Display for PathSegment<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Static(inner) => f.write_str(inner),
            Self::Param(inner) => write!(f, "{{{inner}}}"),
            Self::Group(inner) => write!(f, "({inner})"),
            Self::CatchAll(inner) => write!(f, "{{*{inner}}}"),
        }
    }
}

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

    // -- Path --

    #[test]
    fn path_root_slash_normalized() {
        let path = Path::new("/");
        assert_eq!(&path.inner, "");
        assert_eq!(path.to_matchit_path(), "/");
        assert_eq!(path.segments().count(), 0);
    }

    #[test]
    fn path_segments() {
        let path = Path::new("/dashboard/{id}/(auth)");
        let segs: Vec<_> = path.segments().collect();
        assert_eq!(
            segs,
            vec![
                PathSegment::Static("dashboard"),
                PathSegment::Param("id"),
                PathSegment::Group("auth"),
            ]
        );
    }

    #[test]
    fn path_single_segment() {
        let path = Path::new("/home");
        let segs: Vec<_> = path.segments().collect();
        assert_eq!(segs, vec![PathSegment::Static("home")]);
    }

    #[test]
    fn path_segments_from_the_back() {
        let path = Path::new("/dashboard/{id}/(auth)");
        let segs: Vec<_> = path.segments().rev().collect();
        assert_eq!(
            segs,
            vec![
                PathSegment::Group("auth"),
                PathSegment::Param("id"),
                PathSegment::Static("dashboard"),
            ]
        );
    }

    #[test]
    fn path_segments_from_both_ends_meet_in_the_middle() {
        let path = Path::new("/a/b/c");
        let mut segments = path.segments();

        assert_eq!(segments.next(), Some(PathSegment::Static("a")));
        assert_eq!(segments.next_back(), Some(PathSegment::Static("c")));
        assert_eq!(segments.next(), Some(PathSegment::Static("b")));
        // Both ends are exhausted once they meet.
        assert_eq!(segments.next(), None);
        assert_eq!(segments.next_back(), None);
    }

    #[test]
    fn root_path_yields_no_segments_from_either_end() {
        let mut segments = Path::new("/").segments();

        assert_eq!(segments.next(), None);
        assert_eq!(segments.next_back(), None);
    }

    #[test]
    fn trailing_slash_is_an_empty_last_segment() {
        let path = Path::new("/users/{id}/");
        let segs: Vec<_> = path.segments().collect();
        assert_eq!(
            segs,
            vec![
                PathSegment::Static("users"),
                PathSegment::Param("id"),
                PathSegment::Static(""),
            ]
        );
        assert_eq!(path.segments().next_back(), Some(PathSegment::Static("")));
        assert_eq!(path.as_str(), "/users/{id}/");
    }

    #[test]
    fn path_to_matchit_strips_groups() {
        let path = Path::new("/(auth)/dashboard/{id}");
        assert_eq!(path.to_matchit_path(), "/dashboard/{id}");
    }

    #[test]
    fn path_to_matchit_empty() {
        let path = Path::new("");
        assert_eq!(path.to_matchit_path(), "/");
    }

    #[test]
    fn path_to_matchit_group_only_is_root() {
        // A page inside a route group that should serve `/`.
        assert_eq!(Path::new("/(marketing)").to_matchit_path(), "/");
        // Nested groups collapse the same way.
        assert_eq!(Path::new("/(a)/(b)").to_matchit_path(), "/");
    }

    #[test]
    fn path_to_matchit_no_groups() {
        let path = Path::new("/users/{id}");
        assert_eq!(path.to_matchit_path(), "/users/{id}");
    }

    #[test]
    fn path_to_matchit_keeps_trailing_slash() {
        assert_eq!(Path::new("/users/").to_matchit_path(), "/users/");
        assert_eq!(
            Path::new("/(auth)/users/{id}/").to_matchit_path(),
            "/users/{id}/"
        );
        // A trailing slash after nothing but groups still addresses the root.
        assert_eq!(Path::new("/(marketing)/").to_matchit_path(), "/");
    }

    // -- join --

    #[test]
    fn join_appends_segments() {
        let joined = Path::new("/settings").join(Path::new("/(admin)/{id}"));
        assert_eq!(joined.as_str(), "/settings/(admin)/{id}");
        assert_eq!(joined.segments().count(), 3);
    }

    #[test]
    fn join_root_on_either_side_is_identity() {
        let path = Path::new("/settings");
        assert_eq!(&*path.join(Path::ROOT), path);
        assert_eq!(&*Path::ROOT.join(path), path);
        assert!(Path::ROOT.join(Path::ROOT).is_empty());
    }

    #[test]
    fn path_buf_add_assign_path() {
        let mut buf = PathBuf::new();
        buf += Path::new("/users");
        buf += PathSegment::Param("id");
        buf += Path::new("/posts");
        assert_eq!(buf.as_str(), "/users/{id}/posts");
    }

    #[test]
    fn join_drops_a_trailing_slash_when_segments_follow() {
        let base = Path::new("/settings/");
        assert_eq!(base.join(Path::new("/export")).as_str(), "/settings/export");
        assert_eq!(
            base.join(Path::new("/export/")).as_str(),
            "/settings/export/"
        );
        let mut buf = base.to_owned();
        buf += PathSegment::Param("id");
        assert_eq!(buf.as_str(), "/settings/{id}");
    }

    #[test]
    fn join_keeps_a_trailing_slash_when_nothing_follows() {
        let path = Path::new("/settings/");
        assert_eq!(&*path.join(Path::ROOT), path);
        assert_eq!(&*Path::ROOT.join(path), path);
    }

    #[test]
    fn path_starts_with_match() {
        let path = Path::new("/users/{id}/posts");
        let prefix = Path::new("/users/{id}");
        assert!(path.starts_with(prefix));
    }

    #[test]
    fn path_starts_with_no_match() {
        let path = Path::new("/users/{id}");
        let prefix = Path::new("/posts/{id}");
        assert!(!path.starts_with(prefix));
    }

    #[test]
    fn path_starts_with_longer_prefix() {
        let path = Path::new("/users");
        let prefix = Path::new("/users/{id}/posts");
        assert!(!path.starts_with(prefix));
    }

    #[test]
    fn path_starts_with_rejects_partial_segment() {
        // `/admin` is a string prefix of `/administrator`, but not a whole
        // segment, so it must not count as a path prefix.
        assert!(!Path::new("/administrator").starts_with(Path::new("/admin")));
    }

    #[test]
    fn path_starts_with_includes_groups() {
        let path = Path::new("/(auth)/dashboard");
        assert!(path.starts_with(Path::new("/(auth)")));
        // Groups are part of the logical path, so `/dashboard` is not a prefix
        // of `/(auth)/dashboard` even though both serve the URL `/dashboard`.
        assert!(!path.starts_with(Path::new("/dashboard")));
    }

    #[test]
    fn path_starts_with_distinguishes_param_names() {
        let path = Path::new("/users/{id}/posts");
        assert!(path.starts_with(Path::new("/users/{id}")));
        assert!(!path.starts_with(Path::new("/users/{user_id}")));
    }

    #[test]
    fn path_starts_with_trailing_slash() {
        // A slashed path lies under its slash-less prefix, but a slashed
        // prefix only covers itself.
        assert!(Path::new("/users/").starts_with(Path::new("/users")));
        assert!(Path::new("/users/").starts_with(Path::new("/users/")));
        assert!(!Path::new("/users").starts_with(Path::new("/users/")));
        assert!(!Path::new("/users/posts").starts_with(Path::new("/users/")));
    }

    #[test]
    fn path_display() {
        let path = Path::new("/users/{id}");
        assert_eq!(path.to_string(), "/users/{id}");
    }

    // -- Path matching --

    #[test]
    fn matches_static_exact() {
        assert!(Path::new("/users/list").matches("/users/list"));
    }

    #[test]
    fn matches_static_mismatch() {
        assert!(!Path::new("/users/list").matches("/users/all"));
    }

    #[test]
    fn matches_rejects_partial_segment() {
        assert!(!Path::new("/admin").matches("/administrator"));
        assert!(!Path::new("/administrator").matches("/admin"));
    }

    #[test]
    fn matches_is_case_sensitive() {
        assert!(!Path::new("/admin").matches("/Admin"));
    }

    #[test]
    fn matches_rejects_empty_segments() {
        // Doubled slashes produce empty URL segments, which never route.
        assert!(!Path::new("/admin").matches("//admin"));
        assert!(!Path::new("/users/{id}").matches("/users//"));
        assert!(!Path::new("/users/{id}/posts").matches("/users//posts"));
    }

    #[test]
    fn matches_treats_percent_encoding_as_opaque() {
        // Matching happens on the raw URL, where `%2F` is an ordinary part of
        // a segment, not a separator.
        assert!(!Path::new("/admin/users").matches("/admin%2Fusers"));
        assert!(Path::new("/{page}").matches("/admin%2Fusers"));
    }

    #[test]
    fn matches_param_captures_any_segment() {
        let path = Path::new("/users/{id}/posts");
        assert!(path.matches("/users/42/posts"));
        assert!(path.matches("/users/anything/posts"));
    }

    #[test]
    fn matches_rejects_too_few_segments() {
        assert!(!Path::new("/users/{id}/posts").matches("/users/42"));
    }

    #[test]
    fn matches_rejects_trailing_segments() {
        assert!(!Path::new("/users/{id}").matches("/users/42/posts"));
    }

    #[test]
    fn matches_ignores_groups() {
        assert!(Path::new("/(auth)/dashboard").matches("/dashboard"));
        assert!(Path::new("/(a)/{id}/(b)").matches("/42"));
    }

    #[test]
    fn matches_root() {
        assert!(Path::new("/").matches("/"));
        assert!(!Path::new("/").matches("/anything"));
    }

    #[test]
    fn matches_group_only_path_is_root() {
        assert!(Path::new("/(marketing)").matches("/"));
    }

    #[test]
    fn matches_trailing_slash_exactly() {
        assert!(!Path::new("/users").matches("/users/"));
        assert!(Path::new("/users/").matches("/users/"));
        assert!(!Path::new("/users/").matches("/users"));
        assert!(!Path::new("/users/").matches("/users//"));
        assert!(!Path::new("/users/").matches("/users/posts"));
        assert!(Path::new("/users/{id}/").matches("/users/42/"));
        assert!(!Path::new("/users/{id}/").matches("/users/42"));
        assert!(!Path::new("/users/{id}").matches("/users/"));
    }

    #[test]
    fn matches_root_rejects_doubled_slash() {
        assert!(!Path::new("/").matches("//"));
    }

    #[test]
    fn matches_catch_all() {
        let path = Path::new("/files/{*rest}");
        assert!(path.matches("/files/a"));
        assert!(path.matches("/files/a/b/c"));
    }

    #[test]
    fn matches_catch_all_requires_a_segment() {
        assert!(!Path::new("/files/{*rest}").matches("/files"));
        assert!(!Path::new("/files/{*rest}").matches("/files/"));
    }

    #[test]
    fn matches_catch_all_swallows_empty_segments() {
        // The remainder after `/files/` is `/`, a non-empty capture.
        assert!(Path::new("/files/{*rest}").matches("/files//"));
    }

    #[test]
    fn matches_non_origin_form_urls() {
        // An asterisk-form request (`OPTIONS *`) matches no route path. An
        // empty authority-form path is equivalent to the root URL.
        assert!(!Path::new("/").matches("*"));
        assert!(!Path::new("/admin").matches("*"));
        assert!(Path::new("/").matches(""));
        assert!(!Path::new("/admin").matches(""));
    }

    // -- Path validation --

    #[test]
    fn from_str_accepts_valid_paths() {
        for input in [
            "",
            "/",
            "/users",
            "/users/{id}",
            "/users/{id}/posts/{*rest}",
            "/(auth)/dashboard/{user_id}",
            "/{_private}",
            "/users/",
            "/users/{id}/",
            "/(marketing)/",
        ] {
            assert!(Path::from_str(input).is_ok(), "rejected `{input}`");
        }
    }

    #[test]
    fn from_str_reports_errors() {
        use PathError::*;
        let cases = [
            ("users", MissingLeadingSlash),
            ("//", EmptySegment),
            ("/users//", EmptySegment),
            ("/users//posts", EmptySegment),
            ("/foo{bar}", UnexpectedBracket),
            ("/{id", MissingClosingBrace),
            ("/(auth", MissingClosingParen),
            ("/{}", EmptyName),
            ("/{*}", EmptyName),
            ("/{0id}", InvalidNameStart),
            ("/{id-name}", InvalidNameChar),
            ("/(my-group)", InvalidNameChar),
        ];
        for (input, expected) in cases {
            assert_eq!(Path::from_str(input), Err(expected), "for `{input}`");
        }
    }

    #[test]
    fn new_validates_in_const_context() {
        // Compiles only because the path is valid; a malformed literal here would
        // be a compile-time error from the panic in `new`.
        const PATH: &Path = Path::new("/users/{id}/(auth)");
        assert_eq!(PATH.segments().count(), 3);
    }

    #[test]
    #[should_panic(expected = "unexpected bracket")]
    fn new_panics_on_invalid() {
        let _ = Path::new("/foo{bar}");
    }

    // -- PathBuf --

    #[test]
    fn pathbuf_new_is_empty() {
        let buf = PathBuf::new();
        assert_eq!(buf.to_string(), "");
    }

    #[test]
    fn pathbuf_add_assign() {
        let mut buf = PathBuf::new();
        buf += PathSegment::Static("users");
        buf += PathSegment::Param("id");
        assert_eq!(buf.to_string(), "/users/{id}");
    }

    #[test]
    fn pathbuf_add_assign_trailing_slash() {
        let mut buf = PathBuf::new();
        buf += PathSegment::Static("users");
        buf += PathSegment::Static("");
        assert_eq!(buf.to_string(), "/users/");
        assert_eq!(&*buf, Path::new("/users/"));
    }

    #[test]
    fn pathbuf_from_iterator() {
        let buf: PathBuf = vec![
            PathSegment::Static("api"),
            PathSegment::Static("v1"),
            PathSegment::Param("resource"),
        ]
        .into_iter()
        .collect();
        assert_eq!(buf.to_string(), "/api/v1/{resource}");
    }

    #[test]
    fn pathbuf_deref_to_path() {
        let mut buf = PathBuf::new();
        buf += PathSegment::Static("users");
        let path: &Path = &buf;
        let segs: Vec<_> = path.segments().collect();
        assert_eq!(segs, vec![PathSegment::Static("users")]);
    }

    #[test]
    fn pathbuf_to_owned_roundtrip() {
        let path = Path::new("/users/{id}");
        let buf = path.to_owned();
        assert_eq!(&*buf, path);
    }

    // -- PathSegment --

    #[test]
    fn static_segment() {
        let seg = PathSegment::new("dashboard");
        assert!(seg.is_static());
        assert_eq!(seg.as_static(), Some(&"dashboard"));
    }

    #[test]
    fn param_segment() {
        let seg = PathSegment::new("{id}");
        assert!(seg.is_param());
        assert_eq!(seg.as_param(), Some(&"id"));
    }

    #[test]
    fn param_with_underscore() {
        let seg = PathSegment::new("{user_id}");
        assert!(seg.is_param());
        assert_eq!(seg.as_param(), Some(&"user_id"));
    }

    #[test]
    fn catch_all_segment() {
        let seg = PathSegment::new("{*rest}");
        assert!(matches!(seg, PathSegment::CatchAll("rest")));
    }

    #[test]
    fn group_segment() {
        let seg = PathSegment::new("(auth)");
        assert!(seg.is_group());
        assert_eq!(seg.as_group(), Some(&"auth"));
    }

    #[test]
    fn only_param_and_catch_all_segments_capture() {
        assert_eq!(PathSegment::new("{id}").param_name(), Some("id"));
        assert_eq!(PathSegment::new("{*rest}").param_name(), Some("rest"));
        assert_eq!(PathSegment::new("users").param_name(), None);
        assert_eq!(PathSegment::new("(auth)").param_name(), None);
    }

    #[test]
    fn display_roundtrip() {
        for input in ["dashboard", "{id}", "{*rest}", "(auth)"] {
            assert_eq!(PathSegment::new(input).to_string(), input);
        }
    }

    #[test]
    #[should_panic(expected = "missing closing `}`")]
    fn param_missing_close() {
        let _ = PathSegment::new("{id");
    }

    #[test]
    #[should_panic(expected = "missing closing `)`")]
    fn group_missing_close() {
        let _ = PathSegment::new("(auth");
    }

    #[test]
    #[should_panic(expected = "empty segment")]
    fn empty_segment() {
        let _ = PathSegment::new("");
    }

    #[test]
    #[should_panic(expected = "unexpected bracket")]
    fn static_with_braces() {
        let _ = PathSegment::new("foo{bar}");
    }

    #[test]
    #[should_panic(expected = "name must not be empty")]
    fn param_empty_name() {
        let _ = PathSegment::new("{}");
    }

    #[test]
    #[should_panic(expected = "name must not be empty")]
    fn group_empty_name() {
        let _ = PathSegment::new("()");
    }

    #[test]
    #[should_panic(expected = "name must not be empty")]
    fn catch_all_empty_name() {
        let _ = PathSegment::new("{*}");
    }

    #[test]
    #[should_panic(expected = "must start with a letter or underscore")]
    fn param_invalid_start() {
        let _ = PathSegment::new("{0id}");
    }

    #[test]
    #[should_panic(expected = "contains an invalid character")]
    fn param_invalid_char() {
        let _ = PathSegment::new("{id-name}");
    }

    #[test]
    #[should_panic(expected = "must start with a letter or underscore")]
    fn group_invalid_start() {
        let _ = PathSegment::new("(0auth)");
    }

    #[test]
    #[should_panic(expected = "contains an invalid character")]
    fn group_invalid_char() {
        let _ = PathSegment::new("(my-group)");
    }

    #[test]
    fn underscore_leading_ident() {
        let seg = PathSegment::new("{_private}");
        assert!(seg.is_param());
        assert_eq!(seg.as_param(), Some(&"_private"));
    }
}