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
//! Path Component
//!
//! See [[RFC3986, Section 3.3](https://tools.ietf.org/html/rfc3986#section-3.3)].

use std::borrow::Cow;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt::{self, Display, Formatter, Write};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::str;

use crate::utility::{
    get_percent_encoded_value, normalize_string, percent_encoded_equality, percent_encoded_hash,
    UNRESERVED_CHAR_MAP,
};

/// A map of byte characters that determines if a character is a valid path character.
#[cfg_attr(rustfmt, rustfmt_skip)]
const PATH_CHAR_MAP: [u8; 256] = [
 // 0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // 0
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // 1
    0, b'!',    0,    0, b'$', b'%', b'&',b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.',    0, // 2
 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';',    0, b'=',    0,    0, // 3
 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', // 4
 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', b'Z',    0,    0,    0,    0, b'_', // 5
    0, b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', // 6
 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z',    0,    0,    0, b'~',    0, // 7
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // 8
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // 9
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // A
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // B
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // C
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // D
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // E
    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0, // F
];

/// The path component as defined in
/// [[RFC3986, Section 3.3](https://tools.ietf.org/html/rfc3986#section-3.3)].
///
/// A path is composed of a sequence of segments. It is also either absolute or relative, where an
/// absolute path starts with a `'/'`. A URI with an authority *always* has an absolute path
/// regardless of whether the path was empty (i.e. "http://example.com" has a single empty
/// path segment and is absolute).
///
/// Each segment in the path is case-sensitive. Furthermore, percent-encoding plays no role in
/// equality checking for characters in the unreserved character set meaning that `"segment"` and
/// `"s%65gment"` identical. Both of these attributes are reflected in the equality and hash
/// functions.
///
/// However, be aware that just because percent-encoding plays no role in equality checking does not
/// mean that either the path or a given segment is normalized. If the path or a segment needs to be
/// normalized, use either the [`Path::normalize`] or [`Segment::normalize`] functions,
/// respectively.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Path<'path> {
    /// whether the path is absolute. Specifically, a path is absolute if it starts with a
    /// `'/'`.
    absolute: bool,

    /// The total number of double dot segments in the path.
    double_dot_segment_count: u16,

    /// The number of double dot segments consecutive from the beginning of the path.
    leading_double_dot_segment_count: u16,

    /// The sequence of segments that compose the path.
    segments: Vec<Segment<'path>>,

    /// The total number of single dot segments in the path.
    single_dot_segment_count: u16,

    /// The total number of unnormalized segments in the path.
    unnormalized_count: u16,
}

impl<'path> Path<'path> {
    /// Clears all segments from the path leaving a single empty segment.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let mut path = Path::try_from("/my/path").unwrap();
    /// assert_eq!(path, "/my/path");
    /// path.clear();
    /// assert_eq!(path, "/");
    /// ```
    pub fn clear(&mut self) {
        self.segments.clear();
        self.segments.push(Segment::empty());
    }

    /// Converts the [`Path`] into an owned copy.
    ///
    /// If you construct the path from a source with a non-static lifetime, you may run into
    /// lifetime problems due to the way the struct is designed. Calling this function will ensure
    /// that the returned value has a static lifetime.
    ///
    /// This is different from just cloning. Cloning the path will just copy the references, and
    /// thus the lifetime will remain the same.
    pub fn into_owned(self) -> Path<'static> {
        let segments = self
            .segments
            .into_iter()
            .map(|segment| segment.into_owned())
            .collect::<Vec<Segment<'static>>>();

        Path {
            absolute: self.absolute,
            double_dot_segment_count: self.double_dot_segment_count,
            leading_double_dot_segment_count: self.leading_double_dot_segment_count,
            segments,
            single_dot_segment_count: self.single_dot_segment_count,
            unnormalized_count: self.unnormalized_count,
        }
    }

    /// Returns whether the path is absolute (i.e. it starts with a `'/'`).
    ///
    /// Any path following an [`Authority`] will *always* be parsed to be absolute.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let path = Path::try_from("/my/path").unwrap();
    /// assert_eq!(path.is_absolute(), true);
    /// ```
    pub fn is_absolute(&self) -> bool {
        self.absolute
    }

    /// Returns whether the path is normalized either as or as not a reference.
    ///
    /// See [`Path::normalize`] for a full description of what path normalization entails.
    ///
    /// Although this function does not operate in constant-time in general, it will be
    /// constant-time in the vast majority of cases.
    ///
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let path = Path::try_from("/my/path").unwrap();
    /// assert!(path.is_normalized(false));
    ///
    /// let path = Path::try_from("/my/p%61th").unwrap();
    /// assert!(!path.is_normalized(false));
    ///
    /// let path = Path::try_from("..").unwrap();
    /// assert!(path.is_normalized(true));
    ///
    /// let path = Path::try_from("../.././.").unwrap();
    /// assert!(!path.is_normalized(true));
    /// ```
    pub fn is_normalized(&self, as_reference: bool) -> bool {
        if self.unnormalized_count != 0 {
            return false;
        }

        if self.absolute || !as_reference {
            self.single_dot_segment_count == 0 && self.double_dot_segment_count == 0
        } else {
            (self.single_dot_segment_count == 0
                || (self.single_dot_segment_count == 1
                    && self.segments[0].is_single_dot_segment()
                    && self.segments.len() > 1
                    && self.segments[1].contains(':')))
                && self.double_dot_segment_count == self.leading_double_dot_segment_count
        }
    }

    /// Returns whether the path is relative (i.e. it does not start with a `'/'`).
    ///
    /// Any path following an [`Authority`] will *always* be parsed to be absolute.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let path = Path::try_from("my/path").unwrap();
    /// assert_eq!(path.is_relative(), true);
    /// ```
    pub fn is_relative(&self) -> bool {
        !self.absolute
    }

    /// Creates a path with no segments on it.
    ///
    /// This is only used to avoid allocations for temporary paths. Any path created using this
    /// function is **not** valid!
    pub(crate) unsafe fn new_with_no_segments(absolute: bool) -> Path<'static> {
        Path {
            absolute: absolute,
            double_dot_segment_count: 0,
            leading_double_dot_segment_count: 0,
            segments: Vec::new(),
            single_dot_segment_count: 0,
            unnormalized_count: 0,
        }
    }

    /// Normalizes the path and all of its segments.
    ///
    /// There are two components to path normalization, the normalization of each segment
    /// individually and the removal of unnecessary dot segments. It is also guaranteed that whether
    /// the path is absolute will not change due to normalization.
    ///
    /// The normalization of each segment will proceed according to [`Segment::normalize`].
    ///
    /// If the path is absolute (i.e., it starts with a `'/'`), then `as_reference` will be set to
    /// `false` regardless of its set value.
    ///
    /// If `as_reference` is `false`, then all dot segments will be removed as they would be if you
    /// had called [`Path::remove_dot_segments`]. Otherwise, when a dot segment is removed is
    /// dependent on whether it's `"."` or `".."` and its location in the path.
    ///
    /// In general, `"."` dot segments are always removed except for when it is at the beginning of
    /// the path and is followed by a segment containing a `':'`, e.g. `"./a:b"` stays the same.
    ///
    /// For `".."` dot segments, they are kept whenever they are at the beginning of the path and
    /// removed whenever they are not, e.g. `"a/../.."` normalizes to `".."`.
    pub fn normalize(&mut self, as_reference: bool) {
        if self.is_normalized(as_reference) {
            return;
        }

        self.unnormalized_count = 0;

        if self.absolute || !as_reference {
            self.remove_dot_segments_helper(true);
            return;
        }

        let mut double_dot_segment_count = 0;
        let mut last_dot_segment = None;
        let mut new_length = 0;

        for i in 0..self.segments.len() {
            let segment = &self.segments[i];

            if segment.is_single_dot_segment()
                && (new_length > 0
                    || i == self.segments.len() - 1
                    || !self.segments[i + 1].as_str().contains(':'))
            {
                continue;
            }

            if segment.is_double_dot_segment() {
                match last_dot_segment {
                    None if new_length == 0 => (),
                    Some(index) if index == new_length - 1 => (),
                    _ => {
                        if new_length == 2
                            && self.segments[0].is_single_dot_segment()
                            && (i == self.segments.len() - 1
                                || !self.segments[i + 1].as_str().contains(':'))
                        {
                            new_length -= 1
                        }

                        new_length -= 1;

                        continue;
                    }
                }

                double_dot_segment_count += 1;
                last_dot_segment = Some(new_length);
            }

            self.segments.swap(i, new_length);
            self.segments[new_length].normalize();
            new_length += 1;
        }

        if new_length == 0 {
            self.segments[0] = Segment::empty();
            new_length = 1;
        }

        self.double_dot_segment_count = double_dot_segment_count;
        self.leading_double_dot_segment_count = double_dot_segment_count;
        self.single_dot_segment_count = if self.segments[0].is_single_dot_segment() {
            1
        } else {
            0
        };

        self.segments.truncate(new_length);
    }

    /// Pops the last segment off of the path.
    ///
    /// If the path only contains one segment, then that segment will become empty.
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let mut path = Path::try_from("/my/path").unwrap();
    /// path.pop();
    /// assert_eq!(path, "/my");
    /// path.pop();
    /// assert_eq!(path, "/");
    /// ```
    pub fn pop(&mut self) {
        let segment = self.segments.pop().unwrap();

        if segment.is_single_dot_segment() {
            self.single_dot_segment_count =
                self.single_dot_segment_count.checked_sub(1).unwrap_or(0);
        }

        if segment.is_double_dot_segment() {
            self.double_dot_segment_count =
                self.double_dot_segment_count.checked_sub(1).unwrap_or(0);

            if self.double_dot_segment_count < self.leading_double_dot_segment_count {
                self.leading_double_dot_segment_count -= 1;
            }
        }

        if !segment.is_normalized() {
            self.unnormalized_count = self.unnormalized_count.checked_sub(1).unwrap_or(0);
        }

        if self.segments.is_empty() {
            self.segments.push(Segment::empty());
        }
    }

    /// Pushes a segment onto the path.
    ///
    /// If the conversion to a [`Segment`] fails, an [`InvalidPath`] will be returned.
    ///
    /// The behavior of this function is different if the current path is just one empty segment. In
    /// this case, the pushed segment will replace that empty segment unless the pushed segment is
    /// itself empty.
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let mut path = Path::try_from("/my/path").unwrap();
    /// path.push("test");
    /// assert_eq!(path, "/my/path/test");
    ///
    /// let mut path = Path::try_from("/").unwrap();
    /// path.push("test");
    /// assert_eq!(path, "/test");
    ///
    /// let mut path = Path::try_from("/").unwrap();
    /// path.push("");
    /// assert_eq!(path, "//");
    /// ```
    pub fn push<SegmentType, SegmentError>(
        &mut self,
        segment: SegmentType,
    ) -> Result<(), InvalidPath>
    where
        Segment<'path>: TryFrom<SegmentType, Error = SegmentError>,
        InvalidPath: From<SegmentError>,
    {
        if self.segments.len() as u16 == u16::max_value() {
            return Err(InvalidPath::ExceededMaximumLength);
        }

        let segment = Segment::try_from(segment)?;

        if segment.is_single_dot_segment() {
            self.single_dot_segment_count += 1;
        }

        if segment.is_double_dot_segment() {
            if self.segments.len() as u16 == self.double_dot_segment_count {
                self.leading_double_dot_segment_count += 1;
            }

            self.double_dot_segment_count += 1;
        }

        if !segment.is_normalized() {
            self.unnormalized_count += 1;
        }

        if segment != "" && self.segments.len() == 1 && self.segments[0].as_str().is_empty() {
            self.segments[0] = segment;
        } else {
            self.segments.push(segment);
        }

        Ok(())
    }

    /// Removes all dot segments from the path according to the algorithm described in
    /// [[RFC3986, Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4)].
    ///
    /// This function will perform no memory allocations during removal of dot segments.
    ///
    /// If the path currently has no dot segments, then this function is a no-op.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let mut path = Path::try_from("/a/b/c/./../../g").unwrap();
    /// path.remove_dot_segments();
    /// assert_eq!(path, "/a/g");
    /// ```
    pub fn remove_dot_segments(&mut self) {
        if self.single_dot_segment_count == 0 && self.double_dot_segment_count == 0 {
            return;
        }

        self.remove_dot_segments_helper(false);
    }

    /// Helper function that removes all dot segments with optional segment normalization.
    fn remove_dot_segments_helper(&mut self, normalize_segments: bool) {
        let mut input_absolute = self.absolute;
        let mut new_length = 0;

        for i in 0..self.segments.len() {
            let segment = &self.segments[i];

            if input_absolute {
                if segment.is_single_dot_segment() {
                    continue;
                } else if segment.is_double_dot_segment() {
                    if new_length > 0 {
                        new_length -= 1;
                    } else {
                        self.absolute = false;
                    }

                    continue;
                }

                if new_length == 0 {
                    self.absolute = true;
                }
            } else if segment.is_single_dot_segment() || segment.is_double_dot_segment() {
                continue;
            }

            self.segments.swap(i, new_length);

            if normalize_segments {
                self.segments[new_length].normalize();
            }

            new_length += 1;

            if i < self.segments.len() - 1 {
                input_absolute = true;
            } else {
                input_absolute = false;
            }
        }

        if input_absolute {
            if new_length == 0 {
                self.absolute = true;
            } else {
                self.segments[new_length] = Segment::empty();
                new_length += 1;
            }
        }

        if new_length == 0 {
            self.segments[0] = Segment::empty();
            new_length = 1;
        }

        self.double_dot_segment_count = 0;
        self.leading_double_dot_segment_count = 0;
        self.single_dot_segment_count = 0;
        self.segments.truncate(new_length);
    }

    /// Returns the segments of the path.
    ///
    /// If you require mutability, use [`Path::segments_mut`].
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let mut path = Path::try_from("/my/path").unwrap();
    /// assert_eq!(path.segments()[1], "path");
    /// ```
    pub fn segments(&self) -> &[Segment<'path>] {
        &self.segments
    }

    /// Returns the segments of the path mutably.
    ///
    /// Due to the required restriction that there must be at least one segment in a path, this
    /// mutability only applies to the segments themselves, not the container.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::{Path, Segment};
    ///
    /// let mut path = Path::try_from("/my/path").unwrap();
    ///
    /// // TODO: Remove this block once NLL is stable.
    /// {
    ///     let mut segments = path.segments_mut();
    ///     segments[1] = Segment::try_from("test").unwrap();
    /// }
    ///
    /// assert_eq!(path, "/my/test");
    /// ```
    pub fn segments_mut(&mut self) -> &mut [Segment<'path>] {
        &mut self.segments
    }

    /// Sets whether the path is absolute (i.e. it starts with a `'/'`).
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Path;
    ///
    /// let mut path = Path::try_from("/my/path").unwrap();
    /// path.set_absolute(false);
    /// assert_eq!(path, "my/path");
    /// ```
    pub fn set_absolute(&mut self, absolute: bool) {
        self.absolute = absolute;
    }

    /// Returns a new path which is identical but has a lifetime tied to this path.
    ///
    /// This function will perform a memory allocation.
    pub fn to_borrowed(&self) -> Path {
        let segments = self
            .segments
            .iter()
            .map(|segment| segment.as_borrowed())
            .collect();

        Path {
            absolute: self.absolute,
            double_dot_segment_count: self.double_dot_segment_count,
            leading_double_dot_segment_count: self.leading_double_dot_segment_count,
            segments,
            single_dot_segment_count: self.single_dot_segment_count,
            unnormalized_count: self.unnormalized_count,
        }
    }
}

impl Display for Path<'_> {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        if self.absolute {
            formatter.write_char('/')?;
        }

        for (index, segment) in self.segments.iter().enumerate() {
            formatter.write_str(segment.as_str())?;

            if index < self.segments.len() - 1 {
                formatter.write_char('/')?;
            }
        }

        Ok(())
    }
}

impl<'path> From<Path<'path>> for String {
    fn from(value: Path<'path>) -> Self {
        value.to_string()
    }
}

impl PartialEq<[u8]> for Path<'_> {
    fn eq(&self, mut other: &[u8]) -> bool {
        if self.absolute {
            match other.get(0) {
                Some(&byte) => {
                    if byte != b'/' {
                        return false;
                    }
                }
                None => return false,
            }

            other = &other[1..];
        }

        for (index, segment) in self.segments.iter().enumerate() {
            let len = segment.as_str().len();

            if other.len() < len || &other[..len] != segment {
                return false;
            }

            other = &other[len..];

            if index < self.segments.len() - 1 {
                match other.get(0) {
                    Some(&byte) => {
                        if byte != b'/' {
                            return false;
                        }
                    }
                    None => return false,
                }

                other = &other[1..];
            }
        }

        return true;
    }
}

impl<'path> PartialEq<Path<'path>> for [u8] {
    fn eq(&self, other: &Path<'path>) -> bool {
        self == other
    }
}

impl<'a> PartialEq<&'a [u8]> for Path<'_> {
    fn eq(&self, other: &&'a [u8]) -> bool {
        self == *other
    }
}

impl<'a, 'path> PartialEq<Path<'path>> for &'a [u8] {
    fn eq(&self, other: &Path<'path>) -> bool {
        self == other
    }
}

impl PartialEq<str> for Path<'_> {
    fn eq(&self, other: &str) -> bool {
        self == other.as_bytes()
    }
}

impl<'path> PartialEq<Path<'path>> for str {
    fn eq(&self, other: &Path<'path>) -> bool {
        self.as_bytes() == other
    }
}

impl<'a> PartialEq<&'a str> for Path<'_> {
    fn eq(&self, other: &&'a str) -> bool {
        self == other.as_bytes()
    }
}

impl<'a, 'path> PartialEq<Path<'path>> for &'a str {
    fn eq(&self, other: &Path<'path>) -> bool {
        self.as_bytes() == other
    }
}

impl<'path> TryFrom<&'path [u8]> for Path<'path> {
    type Error = InvalidPath;

    fn try_from(value: &'path [u8]) -> Result<Self, Self::Error> {
        let (path, rest) = parse_path(value)?;

        if rest.is_empty() {
            Ok(path)
        } else {
            Err(InvalidPath::InvalidCharacter)
        }
    }
}

impl<'path> TryFrom<&'path str> for Path<'path> {
    type Error = InvalidPath;

    fn try_from(value: &'path str) -> Result<Self, Self::Error> {
        Path::try_from(value.as_bytes())
    }
}

/// A segment of a path.
///
/// Segments are separated from other segments with the `'/'` delimiter.
#[derive(Clone, Debug)]
pub struct Segment<'segment> {
    /// Whether the segment is normalized.
    normalized: bool,

    /// The internal segment source that is either owned or borrowed.
    segment: Cow<'segment, str>,
}

impl Segment<'_> {
    /// Returns a new segment which is identical but has as lifetime tied to this segment.
    pub fn as_borrowed(&self) -> Segment {
        use self::Cow::*;

        let segment = match &self.segment {
            Borrowed(borrowed) => *borrowed,
            Owned(owned) => owned.as_str(),
        };

        Segment {
            normalized: self.normalized,
            segment: Cow::Borrowed(segment),
        }
    }

    /// Returns a `str` representation of the segment.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Segment;
    ///
    /// let segment = Segment::try_from("segment").unwrap();
    /// assert_eq!(segment.as_str(), "segment");
    /// ```
    pub fn as_str(&self) -> &str {
        &self.segment
    }

    /// Constructs a segment that is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use uriparse::Segment;
    ///
    /// assert_eq!(Segment::empty(),  "");
    /// ```
    pub fn empty() -> Segment<'static> {
        Segment {
            normalized: true,
            segment: Cow::from(""),
        }
    }

    /// Converts the [`Segment`] into an owned copy.
    ///
    /// If you construct the segment from a source with a non-static lifetime, you may run into
    /// lifetime problems due to the way the struct is designed. Calling this function will ensure
    /// that the returned value has a static lifetime.
    ///
    /// This is different from just cloning. Cloning the segment will just copy the references, and
    /// thus the lifetime will remain the same.
    pub fn into_owned(self) -> Segment<'static> {
        Segment {
            normalized: self.normalized,
            segment: Cow::from(self.segment.into_owned()),
        }
    }

    /// Returns whether the segment is a dot segment, i.e., is `"."` or `".."`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Segment;
    ///
    /// let segment = Segment::try_from("segment").unwrap();
    /// assert!(!segment.is_dot_segment());
    ///
    /// let segment = Segment::try_from(".").unwrap();
    /// assert!(segment.is_dot_segment());
    ///
    /// let segment = Segment::try_from("..").unwrap();
    /// assert!(segment.is_dot_segment());
    /// ```
    pub fn is_dot_segment(&self) -> bool {
        self == "." || self == ".."
    }

    /// Returns whether the segment is a dot segment, i.e., is `".."`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Segment;
    ///
    /// let segment = Segment::try_from("segment").unwrap();
    /// assert!(!segment.is_double_dot_segment());
    ///
    /// let segment = Segment::try_from(".").unwrap();
    /// assert!(!segment.is_double_dot_segment());
    ///
    /// let segment = Segment::try_from("..").unwrap();
    /// assert!(segment.is_double_dot_segment());
    /// ```
    pub fn is_double_dot_segment(&self) -> bool {
        self == ".."
    }

    /// Returns whether the segment is normalized.
    ///
    /// A normalized segment will have no bytes that are in the unreserved character set
    /// percent-encoded and all alphabetical characters in percent-encodings will be uppercase.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Segment;
    ///
    /// let segment = Segment::try_from("segment").unwrap();
    /// assert!(segment.is_normalized());
    ///
    /// let mut segment = Segment::try_from("%ff%ff").unwrap();
    /// assert!(!segment.is_normalized());
    /// segment.normalize();
    /// assert!(segment.is_normalized());
    /// ```
    pub fn is_normalized(&self) -> bool {
        self.normalized
    }

    /// Returns whether the segment is a dot segment, i.e., is `"."`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Segment;
    ///
    /// let segment = Segment::try_from("segment").unwrap();
    /// assert!(!segment.is_single_dot_segment());
    ///
    /// let segment = Segment::try_from(".").unwrap();
    /// assert!(segment.is_single_dot_segment());
    ///
    /// let segment = Segment::try_from("..").unwrap();
    /// assert!(!segment.is_single_dot_segment());
    /// ```
    pub fn is_single_dot_segment(&self) -> bool {
        self == "."
    }

    /// Normalizes the segment such that it will have no bytes that are in the unreserved character
    /// set percent-encoded and all alphabetical characters in percent-encodings will be uppercase.
    ///
    /// If the segment is already normalized, the function will return immediately. Otherwise, if
    /// the segment is not owned, this function will perform an allocation to clone it. The
    /// normalization itself though, is done in-place with no extra memory allocations required.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![feature(try_from)]
    /// #
    /// use std::convert::TryFrom;
    ///
    /// use uriparse::Segment;
    ///
    /// let mut segment = Segment::try_from("segment").unwrap();
    /// segment.normalize();
    /// assert_eq!(segment, "segment");
    ///
    /// let mut segment = Segment::try_from("%ff%41").unwrap();
    /// assert_eq!(segment, "%ff%41");
    /// segment.normalize();
    /// assert_eq!(segment, "%FFA");
    /// ```
    pub fn normalize(&mut self) {
        if !self.normalized {
            normalize_string(&mut self.segment.to_mut(), true);
            self.normalized = true;
        }
    }
}

impl AsRef<[u8]> for Segment<'_> {
    fn as_ref(&self) -> &[u8] {
        self.segment.as_bytes()
    }
}

impl AsRef<str> for Segment<'_> {
    fn as_ref(&self) -> &str {
        &self.segment
    }
}

impl Deref for Segment<'_> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.segment
    }
}

impl Display for Segment<'_> {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        formatter.write_str(&self.segment)
    }
}

impl Eq for Segment<'_> {}

impl<'segment> From<Segment<'segment>> for String {
    fn from(value: Segment<'segment>) -> Self {
        value.to_string()
    }
}

impl Hash for Segment<'_> {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        percent_encoded_hash(self.segment.as_bytes(), state, true);
    }
}

impl PartialEq for Segment<'_> {
    fn eq(&self, other: &Segment) -> bool {
        percent_encoded_equality(self.segment.as_bytes(), other.segment.as_bytes(), true)
    }
}

impl PartialEq<[u8]> for Segment<'_> {
    fn eq(&self, other: &[u8]) -> bool {
        percent_encoded_equality(self.segment.as_bytes(), other, true)
    }
}

impl<'segment> PartialEq<Segment<'segment>> for [u8] {
    fn eq(&self, other: &Segment<'segment>) -> bool {
        percent_encoded_equality(self, other.segment.as_bytes(), true)
    }
}

impl<'a> PartialEq<&'a [u8]> for Segment<'_> {
    fn eq(&self, other: &&'a [u8]) -> bool {
        percent_encoded_equality(self.segment.as_bytes(), other, true)
    }
}

impl<'a, 'segment> PartialEq<Segment<'segment>> for &'a [u8] {
    fn eq(&self, other: &Segment<'segment>) -> bool {
        percent_encoded_equality(self, other.segment.as_bytes(), true)
    }
}

impl PartialEq<str> for Segment<'_> {
    fn eq(&self, other: &str) -> bool {
        percent_encoded_equality(self.segment.as_bytes(), other.as_bytes(), true)
    }
}

impl<'segment> PartialEq<Segment<'segment>> for str {
    fn eq(&self, other: &Segment<'segment>) -> bool {
        percent_encoded_equality(self.as_bytes(), other.segment.as_bytes(), true)
    }
}

impl<'a> PartialEq<&'a str> for Segment<'_> {
    fn eq(&self, other: &&'a str) -> bool {
        percent_encoded_equality(self.segment.as_bytes(), other.as_bytes(), true)
    }
}

impl<'a, 'segment> PartialEq<Segment<'segment>> for &'a str {
    fn eq(&self, other: &Segment<'segment>) -> bool {
        percent_encoded_equality(self.as_bytes(), other.segment.as_bytes(), true)
    }
}

impl<'segment> TryFrom<&'segment [u8]> for Segment<'segment> {
    type Error = InvalidPath;

    fn try_from(value: &'segment [u8]) -> Result<Self, Self::Error> {
        let mut bytes = value.iter();
        let mut normalized = true;

        while let Some(&byte) = bytes.next() {
            match PATH_CHAR_MAP[byte as usize] {
                0 => return Err(InvalidPath::InvalidCharacter),
                b'%' => {
                    match get_percent_encoded_value(bytes.next().cloned(), bytes.next().cloned()) {
                        Ok((hex_value, uppercase)) => {
                            if !uppercase || UNRESERVED_CHAR_MAP[hex_value as usize] != 0 {
                                normalized = false;
                            }
                        }
                        Err(_) => return Err(InvalidPath::InvalidPercentEncoding),
                    }
                }
                _ => (),
            }
        }

        let segment = Segment {
            normalized,
            segment: Cow::Borrowed(unsafe { str::from_utf8_unchecked(value) }),
        };
        Ok(segment)
    }
}

impl<'segment> TryFrom<&'segment str> for Segment<'segment> {
    type Error = InvalidPath;

    fn try_from(value: &'segment str) -> Result<Self, Self::Error> {
        Segment::try_from(value.as_bytes())
    }
}

/// An error representing an invalid path.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum InvalidPath {
    /// The path exceeded the maximum length allowed. Due to implementation reasons, the maximum
    /// length a path can be is 2^16 or 65536 characters.
    ExceededMaximumLength,

    /// The path contained an invalid character.
    InvalidCharacter,

    /// The path contained an invalid percent encoding (e.g. `"%ZZ"`).
    InvalidPercentEncoding,
}

impl Display for InvalidPath {
    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
        formatter.write_str(self.description())
    }
}

impl Error for InvalidPath {
    fn description(&self) -> &str {
        use self::InvalidPath::*;

        match self {
            ExceededMaximumLength => "exceeded maximum path length",
            InvalidCharacter => "invalid path character",
            InvalidPercentEncoding => "invalid path percent encoding",
        }
    }
}

impl From<!> for InvalidPath {
    fn from(value: !) -> Self {
        value
    }
}

/// Parses the path from the given byte string.
pub(crate) fn parse_path<'path>(
    value: &'path [u8],
) -> Result<(Path<'path>, &'path [u8]), InvalidPath> {
    fn new_segment<'segment>(
        segment: &'segment [u8],
        index: u16,
        normalized: bool,
        unnormalized_count: &mut u16,
        single_dot_segment_count: &mut u16,
        double_dot_segment_count: &mut u16,
        leading_double_dot_segment_count: &mut u16,
        last_double_dot_segment: &mut Option<u16>,
    ) -> Segment<'segment> {
        if !normalized {
            *unnormalized_count += 1;
        }

        if segment == b"." {
            *single_dot_segment_count += 1;
        }

        if segment == b".." {
            *double_dot_segment_count += 1;

            if index == 0 || *last_double_dot_segment == Some(index - 1) {
                *leading_double_dot_segment_count += 1;
                *last_double_dot_segment = Some(index);
            }
        }

        // Unsafe: The loop below makes sure this is safe.

        Segment {
            normalized,
            segment: Cow::from(unsafe { str::from_utf8_unchecked(segment) }),
        }
    }

    let (value, absolute) = if value.starts_with(b"/") {
        (&value[1..], true)
    } else {
        (value, false)
    };

    let mut bytes = value.iter();
    let mut double_dot_segment_count = 0;
    let mut index = 1;
    let mut last_double_dot_segment = None;
    let mut leading_double_dot_segment_count = 0;
    let mut normalized = true;
    let mut segment_end_index = 0;
    let mut segment_start_index = 0;
    let mut single_dot_segment_count = 0;
    let mut unnormalized_count = 0;

    // Set some moderate initial capacity. This seems to help with performance a bit.
    let mut segments = Vec::with_capacity(10);

    while let Some(&byte) = bytes.next() {
        match PATH_CHAR_MAP[byte as usize] {
            0 if byte == b'?' || byte == b'#' => {
                let segment = new_segment(
                    &value[segment_start_index..segment_end_index],
                    index - 1,
                    normalized,
                    &mut unnormalized_count,
                    &mut single_dot_segment_count,
                    &mut double_dot_segment_count,
                    &mut leading_double_dot_segment_count,
                    &mut last_double_dot_segment,
                );
                segments.push(segment);
                let path = Path {
                    absolute,
                    double_dot_segment_count,
                    leading_double_dot_segment_count,
                    segments,
                    single_dot_segment_count,
                    unnormalized_count,
                };

                return Ok((path, &value[segment_end_index..]));
            }
            0 if byte == b'/' => {
                let segment = new_segment(
                    &value[segment_start_index..segment_end_index],
                    index - 1,
                    normalized,
                    &mut unnormalized_count,
                    &mut single_dot_segment_count,
                    &mut double_dot_segment_count,
                    &mut leading_double_dot_segment_count,
                    &mut last_double_dot_segment,
                );
                segments.push(segment);
                segment_end_index += 1;
                segment_start_index = segment_end_index;
                index = index
                    .checked_add(1)
                    .ok_or(InvalidPath::ExceededMaximumLength)?;
                normalized = true;
            }
            0 => return Err(InvalidPath::InvalidCharacter),
            b'%' => match get_percent_encoded_value(bytes.next().cloned(), bytes.next().cloned()) {
                Ok((hex_value, uppercase)) => {
                    if !uppercase || UNRESERVED_CHAR_MAP[hex_value as usize] != 0 {
                        normalized = false;
                    }

                    segment_end_index += 3;
                }
                Err(_) => return Err(InvalidPath::InvalidPercentEncoding),
            },
            _ => segment_end_index += 1,
        }
    }

    let segment = new_segment(
        &value[segment_start_index..],
        index - 1,
        normalized,
        &mut unnormalized_count,
        &mut single_dot_segment_count,
        &mut double_dot_segment_count,
        &mut leading_double_dot_segment_count,
        &mut last_double_dot_segment,
    );
    segments.push(segment);

    let path = Path {
        absolute,
        double_dot_segment_count,
        leading_double_dot_segment_count,
        segments,
        single_dot_segment_count,
        unnormalized_count,
    };
    Ok((path, b""))
}

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

    #[test]
    fn test_path_normalize() {
        fn test_case(value: &str, expected: &str, as_reference: bool) {
            let mut path = Path::try_from(value).unwrap();
            path.normalize(as_reference);

            let expected_single_dot_segment_count = if expected.starts_with("./") { 1 } else { 0 };
            let expected_double_dot_segment_count = expected
                .split('/')
                .filter(|&segment| segment == "..")
                .count() as u16;

            assert!(!path.segments().is_empty());
            assert!(path.is_normalized(as_reference));
            assert_eq!(
                path.single_dot_segment_count,
                expected_single_dot_segment_count
            );
            assert_eq!(
                path.double_dot_segment_count,
                expected_double_dot_segment_count
            );
            assert_eq!(
                path.leading_double_dot_segment_count,
                expected_double_dot_segment_count
            );
            assert_eq!(path.to_string(), expected);
        }

        test_case("", "", true);
        test_case(".", "", true);
        test_case("..", "..", true);
        test_case("../", "../", true);
        test_case("/.", "/", true);
        test_case("./././././././.", "", true);
        test_case("././././././././", "", true);
        test_case("/..", "/", true);
        test_case("../..", "../..", true);
        test_case("../a/../..", "../..", true);
        test_case("a", "a", true);
        test_case("a/..", "", true);
        test_case("a/../", "", true);
        test_case("a/../..", "..", true);
        test_case("./a:b", "./a:b", true);
        test_case("./a:b/..", "", true);
        test_case("./a:b/../c:d", "./c:d", true);
        test_case("./../a:b", "../a:b", true);
        test_case("../a/../", "../", true);
        test_case("../../.././.././../../../.", "../../../../../../..", true);
        test_case("a/.././a:b", "./a:b", true);

        test_case("", "", false);
        test_case(".", "", false);
        test_case("..", "", false);
        test_case("../", "", false);
        test_case("/.", "/", false);
        test_case("/..", "/", false);
        test_case("../../.././.././../../../.", "", false);
        test_case("a/../..", "/", false);
        test_case("a/../../", "/", false);
        test_case("/a/../../../../", "/", false);
        test_case("/a/./././././././c", "/a/c", false);
        test_case("/a/.", "/a/", false);
        test_case("/a/./", "/a/", false);
        test_case("/a/..", "/", false);
        test_case("/a/b/./..", "/a/", false);
        test_case("/a/b/./../", "/a/", false);
        test_case("/a/b/c/./../../g", "/a/g", false);
        test_case("mid/content=5/../6", "mid/6", false);

        test_case("this/is/a/t%65st/path/%ff", "this/is/a/test/path/%FF", true);
        test_case(
            "this/is/a/t%65st/path/%ff",
            "this/is/a/test/path/%FF",
            false,
        );
    }

    #[test]
    fn test_path_parse() {
        use self::InvalidPath::*;

        let slash = "/".to_string();

        assert_eq!(Path::try_from("").unwrap(), "");
        assert_eq!(Path::try_from("/").unwrap(), "/");
        assert_eq!(
            Path::try_from("/tHiS/iS/a/PaTh").unwrap(),
            "/tHiS/iS/a/PaTh"
        );
        assert_eq!(Path::try_from("%ff%ff%ff%41").unwrap(), "%ff%ff%ff%41");
        assert!(Path::try_from(&*slash.repeat(65535)).is_ok());

        assert_eq!(
            Path::try_from(&*slash.repeat(65536)),
            Err(ExceededMaximumLength)
        );
        assert_eq!(Path::try_from(" "), Err(InvalidCharacter));
        assert_eq!(Path::try_from("#"), Err(InvalidCharacter));
        assert_eq!(Path::try_from("%"), Err(InvalidPercentEncoding));
        assert_eq!(Path::try_from("%f"), Err(InvalidPercentEncoding));
        assert_eq!(Path::try_from("%zz"), Err(InvalidPercentEncoding));
    }

    #[test]
    fn test_path_remove_dot_segments() {
        fn test_case(value: &str, expected: &str) {
            let mut path = Path::try_from(value).unwrap();
            path.remove_dot_segments();
            assert!(!path.segments().is_empty());
            assert_eq!(path.single_dot_segment_count, 0);
            assert_eq!(path.double_dot_segment_count, 0);
            assert_eq!(path.leading_double_dot_segment_count, 0);
            assert_eq!(path.to_string(), expected);
        }

        test_case("", "");
        test_case(".", "");
        test_case("..", "");
        test_case("../", "");
        test_case("/.", "/");
        test_case("/..", "/");
        test_case("../../.././.././../../../.", "");
        test_case("a/../..", "/");
        test_case("a/../../", "/");
        test_case("/a/../../../..", "/");
        test_case("/a/../../../../", "/");
        test_case("/a/./././././././c", "/a/c");
        test_case("/a/.", "/a/");
        test_case("/a/./", "/a/");
        test_case("/a/..", "/");
        test_case("/a/b/./..", "/a/");
        test_case("/a/b/./../", "/a/");
        test_case("/a/b/c/./../../g", "/a/g");
        test_case("mid/content=5/../6", "mid/6");
    }

    #[test]
    fn test_segment_normalize() {
        fn test_case(value: &str, expected: &str) {
            let mut segment = Segment::try_from(value).unwrap();
            segment.normalize();
            assert_eq!(segment, expected);
        }

        test_case("", "");
        test_case("%ff", "%FF");
        test_case("%41", "A");
    }

    #[test]
    fn test_segment_parse() {
        use self::InvalidPath::*;

        assert_eq!(Segment::try_from("").unwrap(), "");
        assert_eq!(Segment::try_from("segment").unwrap(), "segment");
        assert_eq!(Segment::try_from("sEgMeNt").unwrap(), "sEgMeNt");
        assert_eq!(Segment::try_from("%ff%ff%ff%41").unwrap(), "%ff%ff%ff%41");

        assert_eq!(Segment::try_from(" "), Err(InvalidCharacter));
        assert_eq!(Segment::try_from("/"), Err(InvalidCharacter));
        assert_eq!(Segment::try_from("%"), Err(InvalidPercentEncoding));
        assert_eq!(Segment::try_from("%f"), Err(InvalidPercentEncoding));
        assert_eq!(Segment::try_from("%zz"), Err(InvalidPercentEncoding));
    }
}