urly 1.4.1

Yet another URL library
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
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
use std::any::Any;
use std::borrow::{Borrow, Cow};
use std::ops::{Add, AddAssign, Div};
use std::str::FromStr;

use ntex_bytes::{BufMut, ByteString, Bytes, BytesMut};
use simdutf8::compat::{Utf8Error, from_utf8};

use crate::authority::{self, Authority, Port, UserInfo};
use crate::error::{ErrorKind, InvalidUrl};
use crate::path::{Path, PathAndQuery};
use crate::query::{self, Fragment, Query, split_pair};
use crate::quoting::{Component, quote, requote, unquote};
use crate::{chars::lowercase, host::normalize_host, parse, scheme::Scheme};

/// URL reference, normalized by the general-purpose parsers.
///
/// The URL is stored in a single shared [`ByteString`]; accessors return
/// borrowed, percent-encoded components. Parsing is lenient and normalizes the
/// input the same way Python's `yarl` does:
///
/// * leading and trailing whitespace and C0 controls, tabs and newlines are removed
/// * scheme and host are lowercased, non-ASCII hosts are punycode-encoded
/// * percent-encoding is normalized: invalid characters are encoded, escapes of
///   unreserved characters are decoded, hex digits are uppercased
/// * dot segments are removed from absolute paths
/// * an empty path of `http`, `https`, `ws` and `wss` URLs becomes `/`
/// * the default port of the scheme is removed, as in `https://h:443/`
///
/// The normalized URL always passes strict [`Url::validate`].
/// [`Url::parse_target`] and [`Url::from_target_parts`] instead preserve unvalidated
/// HTTP request-target components. Use [`Url::validate_target`] before
/// [`Url::normalize`] to reject malformed targets rather than repair them.
///
/// ```
/// use urly::Url;
///
/// let url: Url = "HTTPS://User@Example.COM:8443/a/./b/../c d?q=1#frag".parse().unwrap();
/// assert_eq!(url, "https://User@example.com:8443/a/c%20d?q=1#frag");
/// assert_eq!(url.scheme_str(), Some("https"));
/// assert_eq!(url.host(), Some("example.com"));
/// assert_eq!(url.port_u16(), Some(8443));
/// assert_eq!(url.path(), "/a/c%20d");
/// assert_eq!(url.path().decode(), "/a/c d");
/// assert_eq!(url.query().unwrap().get("q").unwrap(), "1");
/// assert_eq!(url.fragment().unwrap(), "frag");
/// ```
///
/// URLs are limited to 65535 bytes; operations that can't return an error panic if
/// the result exceeds the limit.
#[derive(Clone)]
pub struct Url {
    data: ByteString,
    // index of ':', 0 if there is no scheme
    scheme_end: u16,
    // index after "//", 0 if there is no authority
    auth_start: u16,
    path_start: u16,
    path_end: u16,
    query_end: u16,
    // host range within the authority, both 0 if there is no authority
    host_start: u16,
    host_end: u16,
}

/// Borrowed URL components, used to assemble a new URL.
#[derive(Copy, Clone, Default)]
pub(crate) struct Components<'a> {
    pub(crate) scheme: Option<&'a str>,
    pub(crate) authority: Option<&'a str>,
    pub(crate) path: &'a str,
    pub(crate) query: Option<&'a str>,
    pub(crate) fragment: Option<&'a str>,
}

/// Assembles components into a URL.
///
/// The path is adjusted so the result can be parsed back unambiguously. `orig`
/// is reused if it is equal to the result.
pub(crate) fn assemble(c: &Components<'_>, orig: Option<&ByteString>) -> Result<Url, InvalidUrl> {
    assemble_inner(c, orig, false)
}

pub(crate) fn assemble_target(
    c: &Components<'_>,
    orig: Option<&ByteString>,
) -> Result<Url, InvalidUrl> {
    assemble_inner(c, orig, true)
}

/// Builds an origin-form request-target, a path not starting with `//` and an
/// optional query, without copying `data`.
///
/// `query` is the position of the first `?` in `data`, if known.
///
/// Produces the same URL as [`assemble_target`] with the split components.
pub(crate) fn origin_form(data: ByteString, query: Option<Option<usize>>) -> Url {
    debug_assert!(data.starts_with('/') && !data.starts_with("//"));
    debug_assert!(data.len() <= parse::MAX_LEN);
    let query = match query {
        Some(None) => None,
        // only an actual `?` is a char boundary
        Some(Some(i)) if data.as_bytes().get(i) == Some(&b'?') => Some(i),
        _ => data.find('?'),
    };
    debug_assert_eq!(query, data.find('?'), "{data:?}");
    let len = data.len() as u16;
    let path_end = query.map_or(len, |i| i as u16);
    Url {
        data,
        scheme_end: 0,
        auth_start: 0,
        path_start: 0,
        path_end,
        query_end: len,
        host_start: 0,
        host_end: 0,
    }
}

fn assemble_inner(
    c: &Components<'_>,
    orig: Option<&ByteString>,
    target: bool,
) -> Result<Url, InvalidUrl> {
    let stripped;
    let c = match c.authority {
        Some(a) if !target => {
            stripped = Components {
                authority: Some(strip_default_port(c.scheme, a)),
                ..*c
            };
            &stripped
        }
        _ => c,
    };
    let prefix = if c.authority.is_some() {
        if c.path.is_empty() {
            let special = c
                .scheme
                .is_some_and(|s| Scheme::from_str_unchecked(s).is_special());
            if special { "/" } else { "" }
        } else if c.path.starts_with('/') || target {
            ""
        } else {
            "/"
        }
    } else if c.path.starts_with("//") {
        "/."
    } else if c.scheme.is_none() && c.path.split('/').next().is_some_and(|s| s.contains(':')) {
        "./"
    } else {
        ""
    };

    let pieces = [
        c.scheme.unwrap_or(""),
        if c.scheme.is_some() { ":" } else { "" },
        if c.authority.is_some() { "//" } else { "" },
        c.authority.unwrap_or(""),
        prefix,
        c.path,
        if c.query.is_some() { "?" } else { "" },
        c.query.unwrap_or(""),
        if c.fragment.is_some() { "#" } else { "" },
        c.fragment.unwrap_or(""),
    ];
    let len: usize = pieces.iter().map(|p| p.len()).sum();
    if len > parse::MAX_LEN {
        return Err(InvalidUrl::new(ErrorKind::TooLong));
    }

    let reuse = orig.filter(|orig| {
        orig.len() == len && {
            // the lengths add up to `len`, indexing can't panic. most pieces are
            // empty, and comparing empty slices is surprisingly slow
            let orig = orig.as_str().as_bytes();
            let mut pos = 0;
            pieces.iter().all(|p| {
                let start = pos;
                pos += p.len();
                p.is_empty() || orig[start..pos] == *p.as_bytes()
            })
        }
    });
    let data = match reuse {
        Some(orig) => orig.clone(),
        None => concat(&pieces, len),
    };

    // all lengths fit, the total is at most `MAX_LEN`
    let lens = pieces.map(|p| p.len() as u16);
    let scheme_end = lens[0];
    let auth_start = if c.authority.is_some() {
        lens[0] + lens[1] + lens[2]
    } else {
        0
    };
    // the `/.` prefix of an authority-less `//` path is not part of the path
    let hidden = if prefix == "/." { lens[4] } else { 0 };
    let path_start = lens[..4].iter().sum::<u16>() + hidden;
    let path_end = lens[..6].iter().sum::<u16>();
    let query_end = path_end + lens[6] + lens[7];
    let (host_start, host_end) = match c.authority {
        Some(a) => {
            let host = authority::split(a).1;
            let start = auth_start + authority::offset(a, host) as u16;
            (start, start + host.len() as u16)
        }
        None => (0, 0),
    };
    Ok(Url {
        data,
        scheme_end,
        auth_start,
        path_start,
        path_end,
        query_end,
        host_start,
        host_end,
    })
}

/// Removes the port from `authority` if it is the default port of `scheme`.
fn strip_default_port<'a>(scheme: Option<&str>, authority: &'a str) -> &'a str {
    // a port ends the authority with a digit
    if !authority.as_bytes().last().is_some_and(u8::is_ascii_digit) {
        return authority;
    }
    let Some(default) = scheme.and_then(|s| Scheme::from_str_unchecked(s).default_port()) else {
        return authority;
    };
    let (_, host, port) = authority::split(authority);
    if port.and_then(|p| authority::parse_port(p).ok()) == Some(default) {
        &authority[..authority::offset(authority, host) + host.len()]
    } else {
        authority
    }
}

/// Concatenates `pieces` of total length `len` with a single copy.
fn concat(pieces: &[&str], len: usize) -> ByteString {
    // short urls are stored inline in `Bytes`, without allocation
    const INLINE: usize = 23;

    let bytes = if len <= INLINE {
        let mut buf = [0u8; INLINE];
        let mut pos = 0;
        for p in pieces {
            buf[pos..pos + p.len()].copy_from_slice(p.as_bytes());
            pos += p.len();
        }
        Bytes::copy_from_slice(&buf[..len])
    } else {
        let mut buf = BytesMut::with_capacity(len);
        let dst = &mut buf.chunk_mut()[..len];
        let mut pos = 0;
        for p in pieces {
            dst[pos..pos + p.len()].copy_from_slice(p.as_bytes());
            pos += p.len();
        }
        assert_eq!(pos, len);
        // SAFETY: the first `len` bytes of the spare capacity were written above
        unsafe { buf.advance_mut(len) };
        buf.freeze()
    };
    // SAFETY: a concatenation of strings is valid UTF-8
    unsafe { ByteString::from_bytes_unchecked(bytes) }
}

fn too_long<T>(res: Result<T, InvalidUrl>) -> T {
    match res {
        Ok(v) => v,
        Err(e) => panic!("{e}"),
    }
}

impl Url {
    /// Returns the relative URL `/`.
    pub const fn new() -> Url {
        Url {
            data: ByteString::from_static("/"),
            scheme_end: 0,
            auth_start: 0,
            path_start: 0,
            path_end: 1,
            query_end: 1,
            host_start: 0,
            host_end: 0,
        }
    }

    /// Parses and normalizes an authority-form `[userinfo@]host[:port]`, like
    /// `http::Uri` does for a string without a scheme or a leading `/`.
    ///
    /// The result is a network-path reference without a path. Use
    /// [`Url::parse_ref`] to parse any URL reference, it treats such a string
    /// as a relative path.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let url = Url::parse("Custom.Domain:8080").unwrap();
    /// assert_eq!(url, "//custom.domain:8080");
    /// assert_eq!(url.host(), Some("custom.domain"));
    /// assert_eq!(url.port_u16(), Some(8080));
    /// assert_eq!(url.path(), "");
    ///
    /// assert!(Url::parse("custom.domain/path").is_err());
    /// assert_eq!(Url::parse_ref("custom.domain").unwrap().host(), None);
    /// ```
    pub fn parse<T: AsRef<str>>(src: T) -> Result<Url, InvalidUrl> {
        parse::parse_authority(src.as_ref())
    }

    /// Parses and normalizes a URL reference.
    ///
    /// Same as `Url::try_from()` and `str::parse()`.
    pub fn parse_ref<T: AsRef<str>>(src: T) -> Result<Url, InvalidUrl> {
        parse::parse(src.as_ref(), None)
    }

    /// Parses an HTTP request-target without validating or normalizing its components.
    ///
    /// Supports origin-form (including paths starting with `//`), absolute-form,
    /// authority-form and `*`. The caller must check that the form is appropriate
    /// for the request method and protocol.
    ///
    /// Preserves case, percent escapes, dot segments and browser-compatible
    /// unescaped path/query characters such as brackets and braces. Only UTF-8,
    /// nonempty input and the representation's length limit are checked.
    /// Use [`Url::validate_target`] before normalization to reject malformed
    /// targets instead of repairing them.
    ///
    /// The input buffer is reused except when URL-reference serialization
    /// requires a prefix (`//` for an authority, `/.` for an origin path starting
    /// with `//`) or an empty absolute HTTP path needs `/`.
    /// Use [`Url::normalize`] to opt into the usual normalization.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::parse_target("/a/../%7euser?q=%41").unwrap();
    /// assert_eq!(url.path_and_query(), "/a/../%7euser?q=%41");
    /// url.validate_target().unwrap();
    /// url.normalize().unwrap();
    /// assert_eq!(url.path_and_query(), "/~user?q=A");
    /// ```
    pub fn parse_target(src: impl Into<Bytes>) -> Result<Url, InvalidUrl> {
        parse::parse_target(src.into())
    }

    /// Parses an HTTP request-target that is already UTF-8.
    ///
    /// Same as [`Url::parse_target`] without the UTF-8 check, for callers
    /// whose parser has already established that the target is ASCII or UTF-8.
    ///
    /// `query` is the position of the first `?` in `src`, `None` if `src` has
    /// no `?`, as found by the caller's parser, so the target is not searched
    /// again. A position that is not a `?` is ignored.
    ///
    /// ```
    /// use ntex_bytes::ByteString;
    /// use urly::Url;
    ///
    /// let url = Url::parse_target_str(ByteString::from_static("/a?b=1"), Some(2)).unwrap();
    /// assert_eq!(url.path(), "/a");
    /// assert_eq!(url.query().unwrap(), "b=1");
    /// ```
    pub fn parse_target_str(
        src: impl Into<ByteString>,
        query: Option<usize>,
    ) -> Result<Url, InvalidUrl> {
        parse::parse_target_str(src.into(), Some(query))
    }

    /// Builds an unvalidated request-target from HTTP/2 pseudo-header components.
    ///
    /// Preserves component boundaries even when a value contains delimiters or
    /// a path does not start with `/`. Such values must not be validated by
    /// reparsing [`Url::as_str`], which can interpret their boundaries differently.
    /// Use [`Url::validate_target`] and check the method/protocol form instead.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let url = Url::from_target_parts(Some("https"), Some("host/invalid"), "/path").unwrap();
    /// assert_eq!(url.authority().unwrap(), "host/invalid");
    /// assert_eq!(url.path(), "/path");
    /// assert!(url.validate_target().is_err());
    /// ```
    pub fn from_target_parts(
        scheme: Option<&str>,
        authority: Option<&str>,
        path_and_query: &str,
    ) -> Result<Url, InvalidUrl> {
        if scheme == Some("") {
            return Err(InvalidUrl::new(ErrorKind::InvalidScheme));
        }
        let (path, query) = crate::chars::split_at_char(path_and_query, b'?');
        assemble_target(
            &Components {
                scheme,
                authority,
                path,
                query,
                fragment: None,
            },
            None,
        )
    }

    /// Validates request-target characters, scheme and authority without rewriting them.
    ///
    /// Rejects malformed escapes, fragments, non-ASCII, whitespace, controls,
    /// `"`, `<`, `>`, `\`, encoded NULs before the query, userinfo and invalid
    /// or empty hosts. Browser-compatible unescaped path/query characters such
    /// as brackets and braces are accepted. The caller must check the method
    /// and protocol's target-form rules. Error positions refer to [`Url::as_str`].
    pub fn validate_target(&self) -> Result<(), InvalidUrl> {
        parse::validate_target(self)
    }

    /// Normalizes all components in place using the general-purpose parsing rules.
    ///
    /// The buffer is reused if unchanged. On failure, such as exceeding the
    /// length limit after percent-encoding, the original URL is left unchanged.
    /// This is lenient normalization, not HTTP validation; use [`Url::validate_target`]
    /// first when malformed request-targets must be rejected.
    pub fn normalize(&mut self) -> Result<(), InvalidUrl> {
        let url = parse::normalize(&self.components(), Some(&self.data))?;
        *self = url;
        Ok(())
    }

    /// Strictly validates a URI reference according to RFC 3986.
    ///
    /// Unlike parsing, validation does not normalize: whitespace, non-ASCII
    /// characters and invalid escapes are errors. The error position is a byte
    /// offset into `src`. Input that is not valid UTF-8 is rejected with
    /// [`ErrorKind::InvalidChar`](crate::ErrorKind::InvalidChar) at its first
    /// non-ASCII byte.
    ///
    /// ```
    /// use urly::{ErrorKind, Url};
    ///
    /// assert!(Url::validate("https://example.com/a%20b?q#f").is_ok());
    /// assert!(Url::validate(b"/path?q").is_ok());
    ///
    /// let err = Url::validate("http://ex ample.com").unwrap_err();
    /// assert_eq!(err.kind(), ErrorKind::InvalidChar(' '));
    /// assert_eq!(err.position(), Some(9));
    ///
    /// let err = Url::validate(b"/a\xff").unwrap_err();
    /// assert_eq!(err.kind(), ErrorKind::InvalidChar(char::REPLACEMENT_CHARACTER));
    /// assert_eq!(err.position(), Some(2));
    /// ```
    pub fn validate<T: AsRef<[u8]>>(src: T) -> Result<(), InvalidUrl> {
        let src = src.as_ref();
        if let Ok(s) = from_utf8(src) {
            return parse::validate(s);
        }
        let i = src.iter().position(|b| !b.is_ascii()).unwrap_or_default();
        let c = src[i..]
            .utf8_chunks()
            .next()
            .and_then(|chunk| chunk.valid().chars().next())
            .unwrap_or(char::REPLACEMENT_CHARACTER);
        Err(InvalidUrl::at(ErrorKind::InvalidChar(c), i))
    }

    /// Converts a static string to a URL. The string is not copied if it is
    /// already normalized.
    ///
    /// # Panics
    ///
    /// Panics if the URL is not valid.
    pub fn from_static(src: &'static str) -> Url {
        match parse::parse(src, Some(&ByteString::from_static(src))) {
            Ok(url) => url,
            Err(e) => panic!("invalid static url {src:?}: {e}"),
        }
    }

    /// Converts a `Bytes`, `String`, `Vec<u8>` or any other
    /// byte buffer to a URL, reusing the buffer if possible.
    pub fn from_maybe_shared<T>(src: T) -> Result<Url, InvalidUrl>
    where
        T: AsRef<[u8]> + 'static,
    {
        let mut src = Some(src);
        let any = &mut src as &mut dyn Any;
        if let Some(src) = any.downcast_mut::<Option<Bytes>>() {
            return Url::try_from(src.take().unwrap());
        }
        if let Some(src) = any.downcast_mut::<Option<String>>() {
            return Url::try_from(src.take().unwrap());
        }
        if let Some(src) = any.downcast_mut::<Option<Vec<u8>>>() {
            return Url::try_from(Bytes::from(src.take().unwrap()));
        }
        Url::try_from(src.unwrap().as_ref())
    }

    /// Returns a new [`Builder`](crate::Builder).
    pub fn builder() -> crate::Builder {
        crate::Builder::new()
    }

    pub(crate) fn empty() -> Url {
        Url {
            data: ByteString::new(),
            scheme_end: 0,
            auth_start: 0,
            path_start: 0,
            path_end: 0,
            query_end: 0,
            host_start: 0,
            host_end: 0,
        }
    }

    fn components(&self) -> Components<'_> {
        Components {
            scheme: self.scheme_str(),
            authority: self.authority().map(Authority::as_str),
            path: self.path().as_str(),
            query: self.query().map(Query::as_str),
            fragment: self.fragment().map(Fragment::as_str),
        }
    }

    fn range(&self, start: u16, end: u16) -> &str {
        &self.data[start as usize..end as usize]
    }

    // ===== accessors =====

    /// Returns the URL as a string.
    pub fn as_str(&self) -> &str {
        &self.data
    }

    /// Returns the URL as bytes.
    pub fn as_bytes(&self) -> &[u8] {
        self.data.as_bytes()
    }

    /// Returns the underlying buffer.
    pub fn as_byte_string(&self) -> &ByteString {
        &self.data
    }

    /// Returns the scheme, if present.
    pub fn scheme(&self) -> Option<&Scheme> {
        self.scheme_str().map(Scheme::from_str_unchecked)
    }

    /// Returns the scheme as a string, if present.
    pub fn scheme_str(&self) -> Option<&str> {
        (self.scheme_end > 0).then(|| self.range(0, self.scheme_end))
    }

    /// Returns the authority, if present.
    pub fn authority(&self) -> Option<&Authority> {
        (self.auth_start > 0)
            .then(|| Authority::from_str_unchecked(self.range(self.auth_start, self.path_start)))
    }

    /// Returns the userinfo, if present.
    pub fn userinfo(&self) -> Option<&UserInfo> {
        (self.host_start > self.auth_start)
            .then(|| UserInfo::from_str_unchecked(self.range(self.auth_start, self.host_start - 1)))
    }

    /// Returns the decoded user name, if present.
    pub fn username(&self) -> Option<Cow<'_, str>> {
        self.userinfo().map(UserInfo::decoded_username)
    }

    /// Returns the decoded password, if present.
    pub fn password(&self) -> Option<Cow<'_, str>> {
        self.userinfo()?.decoded_password()
    }

    /// Returns the host, if present and not empty. IPv6 addresses include the
    /// brackets. General-purpose parsers punycode-encode non-ASCII domains;
    /// raw request-targets preserve their original spelling.
    pub fn host(&self) -> Option<&str> {
        (self.host_end > self.host_start).then(|| self.range(self.host_start, self.host_end))
    }

    /// Returns the parsed host, if present and not empty.
    ///
    /// ```
    /// use std::net::Ipv4Addr;
    /// use urly::{Host, Url};
    ///
    /// let url = Url::from_static("http://127.0.0.1/");
    /// assert_eq!(url.host_parsed(), Some(Host::Ipv4(Ipv4Addr::LOCALHOST)));
    ///
    /// let url = Url::from_static("http://münchen.de/");
    /// assert_eq!(url.host(), Some("xn--mnchen-3ya.de"));
    /// assert_eq!(url.host_parsed().unwrap().to_unicode(), "münchen.de");
    /// ```
    pub fn host_parsed(&self) -> Option<crate::Host<'_>> {
        self.host().map(crate::Host::classify)
    }

    /// Returns the explicit port, if present.
    ///
    /// The default port of the scheme is removed during normalization, so it
    /// is not returned for a normalized URL; use [`Url::port_or_known_default`].
    pub fn port(&self) -> Option<Port<&str>> {
        if self.auth_start > 0 && self.host_end < self.path_start {
            Port::parse(self.range(self.host_end + 1, self.path_start))
        } else {
            None
        }
    }

    /// Returns the explicit port as a number, if present.
    pub fn port_u16(&self) -> Option<u16> {
        self.port().map(|p| p.as_u16())
    }

    /// Returns the explicit port, or the default port of the scheme.
    pub fn port_or_known_default(&self) -> Option<u16> {
        self.port_u16().or_else(|| self.scheme()?.default_port())
    }

    /// Returns the percent-encoded path.
    ///
    /// A path starting with `//` in a URL without authority is serialized with a
    /// `/.` prefix, which is not part of the path.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let url = Url::from_static("/.//a?q");
    /// assert_eq!(url.path(), "//a");
    /// assert_eq!(url.path_and_query(), "//a?q");
    /// ```
    pub fn path(&self) -> &Path {
        Path::from_str_unchecked(self.range(self.path_start, self.path_end))
    }

    /// Returns the percent-encoded query, if present.
    pub fn query(&self) -> Option<&Query> {
        (self.query_end > self.path_end)
            .then(|| Query::from_str_unchecked(self.range(self.path_end + 1, self.query_end)))
    }

    /// Returns the path and query.
    pub fn path_and_query(&self) -> &PathAndQuery {
        PathAndQuery::from_str_unchecked(self.range(self.path_start, self.query_end))
    }

    /// Returns the percent-encoded fragment, if present.
    pub fn fragment(&self) -> Option<&Fragment> {
        ((self.query_end as usize) < self.data.len())
            .then(|| Fragment::from_str_unchecked(&self.data[self.query_end as usize + 1..]))
    }

    /// Returns `true` if the URL has a scheme.
    pub fn is_absolute(&self) -> bool {
        self.scheme_end > 0
    }

    /// Returns `true` if the port is absent or is the default port of the scheme.
    pub fn is_default_port(&self) -> bool {
        match self.port_u16() {
            None => true,
            Some(port) => self.scheme().and_then(Scheme::default_port) == Some(port),
        }
    }

    // ===== derived urls =====

    /// Returns the origin: scheme, host and port.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let url = Url::from_static("https://user:pw@example.com:8443/a?b#c");
    /// assert_eq!(url.origin().unwrap(), "https://example.com:8443/");
    /// assert!(Url::from_static("/a").origin().is_none());
    /// ```
    pub fn origin(&self) -> Option<Url> {
        let scheme = self.scheme_str()?;
        let authority = self.authority()?;
        if authority.host().is_empty() {
            return None;
        }
        Some(self.derive(|c| {
            *c = Components {
                scheme: Some(scheme),
                authority: Some(authority.host_port()),
                ..Components::default()
            };
        }))
    }

    /// Returns the relative part of the URL: path, query and fragment.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let url = Url::from_static("https://example.com/a?b#c");
    /// assert_eq!(url.relative(), "/a?b#c");
    /// ```
    pub fn relative(&self) -> Url {
        self.derive(|c| {
            c.scheme = None;
            c.authority = None;
        })
    }

    /// Returns the URL with the last path segment removed, without query and
    /// fragment.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// assert_eq!(Url::from_static("http://h/a/b?q").parent(), "http://h/a");
    /// assert_eq!(Url::from_static("http://h/a/b/").parent(), "http://h/a");
    /// assert_eq!(Url::from_static("http://h/a").parent(), "http://h/");
    /// assert_eq!(Url::from_static("http://h/").parent(), "http://h/");
    /// ```
    pub fn parent(&self) -> Url {
        let path = self.path().as_str();
        let trimmed = path.trim_end_matches('/');
        let parent = match trimmed.rfind('/') {
            Some(0) => "/",
            Some(i) => &trimmed[..i],
            None if path.starts_with('/') => "/",
            None => "",
        };
        self.with_path(parent)
    }

    /// Appends literal path segments, without query and fragment.
    ///
    /// Segments are percent-encoded; `/` is kept and a leading `/` is ignored.
    /// `.` and `..` segments are resolved within the appended segments, so they
    /// never remove a segment of this URL's path. The same operation is
    /// available as the `/` operator.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let url = Url::from_static("http://h/api?q");
    /// assert_eq!(url.push_segments(["v1", "a b"]), "http://h/api/v1/a%20b");
    /// assert_eq!(&url / "users/" / "1", "http://h/api/users/1");
    /// assert_eq!(&url / "../admin", "http://h/api/admin");
    /// assert_eq!(&url / "v1/../v2", "http://h/api/v2");
    /// ```
    pub fn push_segments<I, S>(&self, segments: I) -> Url
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        // appended segments, relative to a virtual root
        let mut rel = String::from("/");
        let mut pushed = false;
        for segment in segments {
            let segment = segment.as_ref();
            let segment = segment.strip_prefix('/').unwrap_or(segment);
            if !rel.ends_with('/') {
                rel.push('/');
            }
            rel.push_str(&quote(segment, Component::Path));
            pushed = true;
        }
        if !pushed {
            return self.with_path(self.path().as_str());
        }
        if parse::has_dot_segments(&rel) {
            rel = parse::remove_dot_segments(&rel);
        }
        let mut path = self.path().as_str().to_string();
        if !path.is_empty() && !path.ends_with('/') {
            path.push('/');
        }
        path.push_str(&rel[1..]);
        self.with_path(&path)
    }

    /// Resolves a reference against this URL, RFC 3986 section 5.2.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let base = Url::from_static("http://a/b/c/d;p?q");
    /// assert_eq!(base.join("../g").unwrap(), "http://a/b/g");
    /// assert_eq!(base.join("//g/x").unwrap(), "http://g/x");
    /// assert_eq!(base.join("?y").unwrap(), "http://a/b/c/d;p?y");
    /// ```
    pub fn join(&self, reference: &str) -> Result<Url, InvalidUrl> {
        if reference.trim_matches(|c: char| c <= ' ').is_empty() {
            return self.rebuild(|c| c.fragment = None);
        }
        Ok(self.join_url(&Url::parse_ref(reference)?))
    }

    /// Resolves a parsed reference against this URL, RFC 3986 section 5.2.2.
    ///
    /// The `+` and `+=` operators are equivalent.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let base = Url::from_static("http://a/b/c/d;p?q");
    /// let r = Url::from_static("../g");
    /// assert_eq!(base.join_url(&r), "http://a/b/g");
    /// assert_eq!(&base + &r, "http://a/b/g");
    ///
    /// let mut url = base.clone();
    /// url += r;
    /// assert_eq!(url, "http://a/b/g");
    /// ```
    pub fn join_url(&self, r: &Url) -> Url {
        let base = self.components();
        let r = r.components();
        let resolved = |path| Cow::Owned(parse::remove_dot_segments(path));
        let (scheme, authority, path, query) = if r.scheme.is_some() {
            (r.scheme, r.authority, resolved(r.path), r.query)
        } else if r.authority.is_some() {
            (base.scheme, r.authority, resolved(r.path), r.query)
        } else if r.path.is_empty() {
            let query = r.query.or(base.query);
            (base.scheme, base.authority, Cow::Borrowed(base.path), query)
        } else if r.path.starts_with('/') {
            (base.scheme, base.authority, resolved(r.path), r.query)
        } else {
            let dir = if base.authority.is_some() && base.path.is_empty() {
                "/"
            } else {
                dir(base.path)
            };
            let path = resolved(&format!("{dir}{}", r.path));
            (base.scheme, base.authority, path, r.query)
        };
        self.derive(|c| {
            *c = Components {
                scheme,
                authority,
                path: &path,
                query,
                fragment: r.fragment,
            };
        })
    }

    // ===== setters =====

    /// Assembles a URL from modified components, reusing the buffer if
    /// nothing changed.
    fn rebuild<'a>(&'a self, f: impl FnOnce(&mut Components<'a>)) -> Result<Url, InvalidUrl> {
        let mut c = self.components();
        f(&mut c);
        assemble(&c, Some(&self.data))
    }

    fn derive<'a>(&'a self, f: impl FnOnce(&mut Components<'a>)) -> Url {
        too_long(self.rebuild(f))
    }

    /// Returns the URL with a new path, without query and fragment.
    fn with_path(&self, path: &str) -> Url {
        self.derive(|c| {
            c.path = path;
            c.query = None;
            c.fragment = None;
        })
    }

    /// Sets the scheme.
    pub fn set_scheme(&mut self, scheme: &str) -> Result<(), InvalidUrl> {
        let scheme = lowercase(Scheme::new(scheme)?.as_str().into());
        self.rebuild(|c| c.scheme = Some(&scheme))
            .map(|url| *self = url)
    }

    /// Sets or removes the raw authority: `[userinfo "@"] host [":" port]`.
    pub fn set_authority(&mut self, authority: Option<&str>) -> Result<(), InvalidUrl> {
        let authority = authority.map(parse::normalize_authority).transpose()?;
        self.rebuild(|c| c.authority = authority.as_deref())
            .map(|url| *self = url)
    }

    fn with_authority(
        &self,
        userinfo: Option<&str>,
        host: &str,
        port: Option<u16>,
    ) -> Result<Url, InvalidUrl> {
        let authority = parse::join_authority(userinfo, host, port);
        self.rebuild(|c| c.authority = Some(&authority))
    }

    fn host_parts(&self) -> Result<(Option<&str>, &str, Option<u16>), InvalidUrl> {
        let authority = self
            .authority()
            .ok_or(InvalidUrl::new(ErrorKind::AuthorityMissing))?;
        let (userinfo, host, _) = authority::split(authority.as_str());
        if host.is_empty() {
            return Err(InvalidUrl::new(ErrorKind::InvalidHost));
        }
        Ok((userinfo, host, authority.port_u16()))
    }

    /// Sets or removes the literal user name and password.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://example.com/");
    /// url.set_userinfo(Some("us@r"), Some("p:w")).unwrap();
    /// assert_eq!(url, "http://us%40r:p%3Aw@example.com/");
    /// assert_eq!(url.password().unwrap(), "p:w");
    /// ```
    pub fn set_userinfo(
        &mut self,
        username: Option<&str>,
        password: Option<&str>,
    ) -> Result<(), InvalidUrl> {
        let (_, host, port) = self.host_parts()?;
        let userinfo = match (username, password) {
            (None, None) => None,
            (user, None) => Some(quote(user.unwrap_or(""), Component::UserInfo)),
            (user, Some(password)) => Some(Cow::Owned(format!(
                "{}:{}",
                quote(user.unwrap_or(""), Component::UserInfo),
                quote(password, Component::UserInfo)
            ))),
        };
        self.with_authority(userinfo.as_deref(), host, port)
            .map(|url| *self = url)
    }

    /// Sets the host. Escapes are decoded, non-ASCII domains are
    /// punycode-encoded, IPv6 addresses may be given without brackets.
    ///
    /// An authority is added if the URL doesn't have one.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://user@example.com:8080/a");
    /// url.set_host("::1").unwrap();
    /// assert_eq!(url, "http://user@[::1]:8080/a");
    /// url.set_host("Bücher.example").unwrap();
    /// assert_eq!(url, "http://user@xn--bcher-kva.example:8080/a");
    /// ```
    pub fn set_host(&mut self, host: &str) -> Result<(), InvalidUrl> {
        let bracketed;
        let host = if host.contains(':') && !host.starts_with('[') {
            bracketed = format!("[{host}]");
            &bracketed
        } else {
            host
        };
        let host = normalize_host(host)?;
        if host.is_empty() {
            return Err(InvalidUrl::new(ErrorKind::InvalidHost));
        }
        let (userinfo, port) = match self.authority() {
            Some(a) => (a.userinfo().map(UserInfo::as_str), a.port_u16()),
            None => (None, None),
        };
        self.with_authority(userinfo, &host, port)
            .map(|url| *self = url)
    }

    /// Sets or removes the port.
    pub fn set_port(&mut self, port: Option<u16>) -> Result<(), InvalidUrl> {
        let (userinfo, host, _) = self.host_parts()?;
        self.with_authority(userinfo, host, port)
            .map(|url| *self = url)
    }

    /// Sets the percent-encoded path, keeping query and fragment.
    ///
    /// Invalid characters are encoded and dot segments are removed.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/a?q");
    /// url.set_path("/b/../c d");
    /// assert_eq!(url, "http://h/c%20d?q");
    /// ```
    pub fn set_path(&mut self, path: &str) {
        too_long(self.try_set_path(path));
    }

    pub(crate) fn try_set_path(&mut self, path: &str) -> Result<(), InvalidUrl> {
        let prefixed;
        let path = if self.auth_start != 0 && !path.is_empty() && !path.starts_with('/') {
            prefixed = format!("/{path}");
            &prefixed
        } else {
            path
        };
        let path = parse::normalize_path(path);
        self.rebuild(|c| c.path = &path).map(|url| *self = url)
    }

    /// Replaces the last path segment with a literal file name.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/a/b.txt?q");
    /// url.set_file_name("c d.html").unwrap();
    /// assert_eq!(url, "http://h/a/c%20d.html?q");
    /// ```
    pub fn set_file_name(&mut self, name: &str) -> Result<(), InvalidUrl> {
        if name.contains('/') || name == "." || name == ".." {
            return Err(InvalidUrl::new(ErrorKind::InvalidPath));
        }
        self.with_file_name(&quote(name, Component::Path))
            .map(|url| *self = url)
    }

    /// Replaces the last path segment with an encoded file name.
    fn with_file_name(&self, name: &str) -> Result<Url, InvalidUrl> {
        let path = format!("{}{name}", dir(self.path().as_str()));
        self.rebuild(|c| c.path = &path)
    }

    /// Replaces the extension of the file name; an empty extension removes it.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/a/b.txt");
    /// url.set_extension("tar.gz").unwrap();
    /// assert_eq!(url, "http://h/a/b.tar.gz");
    /// url.set_extension("").unwrap();
    /// assert_eq!(url, "http://h/a/b.tar");
    /// ```
    pub fn set_extension(&mut self, extension: &str) -> Result<(), InvalidUrl> {
        let stem = self
            .path()
            .file_stem()
            .ok_or(InvalidUrl::new(ErrorKind::InvalidPath))?;
        if extension.contains('/') {
            return Err(InvalidUrl::new(ErrorKind::InvalidPath));
        }
        let name = if extension.is_empty() {
            Cow::Borrowed(stem)
        } else {
            let extension = quote(extension, Component::Path);
            Cow::Owned(format!("{stem}.{extension}"))
        };
        self.with_file_name(&name).map(|url| *self = url)
    }

    /// Sets or removes the percent-encoded query.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/#f");
    /// url.set_query(Some("a=b c&d"));
    /// assert_eq!(url, "http://h/?a=b+c&d#f");
    /// ```
    pub fn set_query(&mut self, query: Option<&str>) {
        too_long(self.try_set_query(query));
    }

    pub(crate) fn try_set_query(&mut self, query: Option<&str>) -> Result<(), InvalidUrl> {
        let query = query.map(|q| requote(q, Component::Query));
        self.rebuild(|c| c.query = query.as_deref())
            .map(|url| *self = url)
    }

    /// Keeps existing pairs whose decoded key passes `keep` and appends literal
    /// `pairs`. An empty result removes the query.
    fn edit_query_pairs<I, K, V>(
        &mut self,
        keep: impl Fn(&str) -> bool,
        pairs: I,
    ) -> Result<(), InvalidUrl>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let existing = self.query().map_or("", Query::as_str);
        let pieces: Vec<Cow<'_, str>> = query::pieces(existing)
            .filter(|piece| keep(&unquote(split_pair(piece).0, Component::QueryPart)))
            .map(Cow::Borrowed)
            .chain(pairs.into_iter().map(|(k, v)| {
                let (k, v) = (k.as_ref(), v.as_ref());
                let (k, v) = (
                    quote(k, Component::QueryPart),
                    quote(v, Component::QueryPart),
                );
                Cow::Owned(format!("{k}={v}"))
            }))
            .collect();
        let query = pieces.join("&");
        self.rebuild(|c| c.query = (!query.is_empty()).then_some(query.as_str()))
            .map(|url| *self = url)
    }

    /// Replaces the query with literal key-value pairs. Empty pairs remove the query.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/?old");
    /// url.set_query_pairs([("a", "1 2"), ("b&", "=")]);
    /// assert_eq!(url, "http://h/?a=1+2&b%26=%3D");
    /// ```
    pub fn set_query_pairs<I, K, V>(&mut self, pairs: I)
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        too_long(self.edit_query_pairs(|_| false, pairs));
    }

    /// Appends literal key-value pairs to the query.
    pub fn extend_query_pairs<I, K, V>(&mut self, pairs: I)
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        too_long(self.try_extend_query_pairs(pairs));
    }

    pub(crate) fn try_extend_query_pairs<I, K, V>(&mut self, pairs: I) -> Result<(), InvalidUrl>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.edit_query_pairs(|_| true, pairs)
    }

    /// Replaces all values of the given keys, appending the new pairs.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/?a=1&b=2&a=3");
    /// url.update_query_pairs([("a", "4")]);
    /// assert_eq!(url, "http://h/?b=2&a=4");
    /// ```
    pub fn update_query_pairs<I, K, V>(&mut self, pairs: I)
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let pairs: Vec<(K, V)> = pairs.into_iter().collect();
        let keep = |key: &str| !pairs.iter().any(|(k, _)| k.as_ref() == key);
        too_long(self.edit_query_pairs(keep, pairs.iter().map(|(k, v)| (k.as_ref(), v.as_ref()))));
    }

    /// Removes all pairs with the given keys from the query.
    ///
    /// ```
    /// use urly::Url;
    ///
    /// let mut url = Url::from_static("http://h/?a=1&b=2&a=3");
    /// url.remove_query_params(["a"]);
    /// assert_eq!(url, "http://h/?b=2");
    /// url.remove_query_params(["b"]);
    /// assert_eq!(url, "http://h/");
    /// ```
    pub fn remove_query_params<I, K>(&mut self, keys: I)
    where
        I: IntoIterator<Item = K>,
        K: AsRef<str>,
    {
        let keys: Vec<K> = keys.into_iter().collect();
        let keep = |key: &str| !keys.iter().any(|k| k.as_ref() == key);
        too_long(self.edit_query_pairs(keep, std::iter::empty::<(&str, &str)>()));
    }

    /// Sets or removes the percent-encoded fragment.
    pub fn set_fragment(&mut self, fragment: Option<&str>) {
        too_long(self.try_set_fragment(fragment));
    }

    pub(crate) fn try_set_fragment(&mut self, fragment: Option<&str>) -> Result<(), InvalidUrl> {
        let fragment = fragment.map(|f| requote(f, Component::Fragment));
        self.rebuild(|c| c.fragment = fragment.as_deref())
            .map(|url| *self = url)
    }

    /// Splits the URL into its parts.
    pub fn into_parts(self) -> crate::Parts {
        let slice = |start: u16, end: usize| self.data.slice(start as usize..end);
        crate::Parts {
            scheme: self.scheme().map(|_| slice(0, self.scheme_end as usize)),
            authority: self
                .authority()
                .map(|_| slice(self.auth_start, self.path_start as usize)),
            path_and_query: slice(self.path_start, self.query_end as usize),
            fragment: self
                .fragment()
                .map(|_| slice(self.query_end + 1, self.data.len())),
        }
    }

    /// Converts the URL into its buffer.
    pub fn into_byte_string(self) -> ByteString {
        self.data
    }
}

/// Returns the path up to and including the last `/`.
fn dir(path: &str) -> &str {
    path.rfind('/').map_or("", |i| &path[..=i])
}

// ===== trait impls =====

str_fmt!(Url);
str_eq!(Url);

/// Returns the relative URL `/`, like `http::Uri::default()`.
impl Default for Url {
    fn default() -> Url {
        Url::new()
    }
}

impl FromStr for Url {
    type Err = InvalidUrl;

    fn from_str(s: &str) -> Result<Url, InvalidUrl> {
        parse::parse(s, None)
    }
}

macro_rules! try_from {
    ($($ty:ty => |$s:ident| $conv:expr;)*) => {$(
        impl TryFrom<$ty> for Url {
            type Error = InvalidUrl;

            fn try_from($s: $ty) -> Result<Url, InvalidUrl> {
                $conv
            }
        }
    )*};
}

try_from! {
    &str => |s| parse::parse(s, None);
    &String => |s| parse::parse(s, None);
    // `ByteString::from(String)` copies, assembling copies only once
    String => |s| parse::parse(&s, None);
    ByteString => |s| parse::parse(&s, Some(&s));
    &ByteString => |s| parse::parse(s, Some(s));
    &[u8] => |s| parse::parse(from_utf8(s).map_err(utf8_error)?, None);
    Bytes => |s| {
        from_utf8(&s).map_err(utf8_error)?;
        // SAFETY: validated above
        Url::try_from(unsafe { ByteString::from_bytes_unchecked(s) })
    };
}

#[allow(clippy::needless_pass_by_value)]
pub(crate) fn utf8_error(e: Utf8Error) -> InvalidUrl {
    InvalidUrl::at(ErrorKind::InvalidChar('\u{FFFD}'), e.valid_up_to())
}

impl From<Url> for ByteString {
    fn from(url: Url) -> ByteString {
        url.data
    }
}

impl From<Url> for String {
    fn from(url: Url) -> String {
        url.as_str().to_string()
    }
}

impl<S: AsRef<str>> Div<S> for &Url {
    type Output = Url;

    fn div(self, segment: S) -> Url {
        self.push_segments([segment])
    }
}

impl<S: AsRef<str>> Div<S> for Url {
    type Output = Url;

    fn div(self, segment: S) -> Url {
        self.push_segments([segment])
    }
}

impl<U: Borrow<Url>> Add<U> for &Url {
    type Output = Url;

    fn add(self, reference: U) -> Url {
        self.join_url(reference.borrow())
    }
}

impl<U: Borrow<Url>> Add<U> for Url {
    type Output = Url;

    fn add(self, reference: U) -> Url {
        self.join_url(reference.borrow())
    }
}

impl<U: Borrow<Url>> AddAssign<U> for Url {
    fn add_assign(&mut self, reference: U) {
        *self = self.join_url(reference.borrow());
    }
}

#[cfg(feature = "http")]
mod http_impls {
    use http::uri::{InvalidUri, Uri};

    use super::Url;
    use crate::error::InvalidUrl;

    impl TryFrom<&Uri> for Url {
        type Error = InvalidUrl;

        fn try_from(uri: &Uri) -> Result<Url, InvalidUrl> {
            if uri.scheme().is_none()
                && let Some(authority) = uri.authority()
            {
                return Url::parse(authority.as_str());
            }
            let uri = uri.to_string();
            // an origin-form path starting with `//` is not an authority
            if uri.starts_with("//") {
                Url::try_from(format!("/.{uri}"))
            } else {
                Url::try_from(uri)
            }
        }
    }

    impl TryFrom<Uri> for Url {
        type Error = InvalidUrl;

        fn try_from(uri: Uri) -> Result<Url, InvalidUrl> {
            Url::try_from(&uri)
        }
    }

    /// The fragment is removed, `Uri` doesn't support it. A network-path
    /// reference converts to authority-form, it fails if it has a path or
    /// query.
    impl TryFrom<&Url> for Uri {
        type Error = InvalidUri;

        fn try_from(url: &Url) -> Result<Uri, InvalidUri> {
            // `Uri` parses a relative reference as origin-form, without the `/.`
            // prefix, and a reference without scheme and `//` as authority-form
            let start = match (url.scheme_end, url.auth_start) {
                (0, 0) => url.path_start,
                (0, auth_start) => auth_start,
                _ => 0,
            };
            Uri::try_from(url.range(start, url.query_end))
        }
    }

    /// The fragment is removed, `Uri` doesn't support it.
    impl TryFrom<Url> for Uri {
        type Error = InvalidUri;

        fn try_from(url: Url) -> Result<Uri, InvalidUri> {
            Uri::try_from(&url)
        }
    }
}

#[cfg(feature = "serde")]
mod serde_impls {
    use std::fmt;

    use serde::de::{self, Deserialize, Deserializer, Visitor};
    use serde::{Serialize, Serializer};

    use super::Url;

    impl Serialize for Url {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.serialize_str(self.as_str())
        }
    }

    struct UrlVisitor;

    impl Visitor<'_> for UrlVisitor {
        type Value = Url;

        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("a url")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Url, E> {
            Url::try_from(v).map_err(E::custom)
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Url, E> {
            Url::try_from(v).map_err(E::custom)
        }
    }

    impl<'de> Deserialize<'de> for Url {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Url, D::Error> {
            deserializer.deserialize_str(UrlVisitor)
        }
    }
}

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

    #[test]
    fn default() {
        const URL: Url = Url::new();
        assert_eq!(URL, Url::default());
        let (url, p) = (Url::default(), Url::from_static("/"));
        assert_eq!(url.scheme_end, p.scheme_end);
        assert_eq!(url.auth_start, p.auth_start);
        assert_eq!(url.path_start, p.path_start);
        assert_eq!(url.path_end, p.path_end);
        assert_eq!(url.query_end, p.query_end);
        assert_eq!((url.host_start, url.host_end), (p.host_start, p.host_end));
        assert_eq!(url, "/");
        assert_eq!(url.path(), "/");
        assert!(url.query().is_none());
        assert!(!url.is_absolute());
    }

    #[test]
    fn cached_host() {
        let cases = [
            (
                "http://u:p@[::1]:8080/a",
                Some("u:p"),
                Some("[::1]"),
                Some(8080),
            ),
            ("http://@h/", Some(""), Some("h"), None),
            ("http://h:0/", None, Some("h"), Some(0)),
            ("file:///etc", None, None, None),
            ("//h", None, Some("h"), None),
            ("/a", None, None, None),
        ];
        for (src, userinfo, host, port) in cases {
            let url = Url::from_static(src);
            let auth = url.authority();
            assert_eq!(url.userinfo().map(UserInfo::as_str), userinfo, "{src}");
            assert_eq!(url.host(), host, "{src}");
            assert_eq!(url.port_u16(), port, "{src}");
            assert_eq!(
                auth.and_then(|a| a.userinfo()).map(UserInfo::as_str),
                userinfo
            );
            assert_eq!(auth.map(Authority::host).filter(|h| !h.is_empty()), host);
            assert_eq!(auth.and_then(Authority::port_u16), port);
            let mut copy = url.clone();
            copy.set_path("/x");
            assert_eq!((copy.host(), copy.port_u16()), (host, port), "{src}");
        }
    }

    #[test]
    fn double_slash_path() {
        let url = Url::from_static("/.//a/../b?q#f");
        assert_eq!(url, "/.//b?q#f");
        assert_eq!(url.path(), "//b");
        assert_eq!(url.path_and_query(), "//b?q");
        assert!(url.authority().is_none());
        assert_eq!(Url::from_parts(url.clone().into_parts()).unwrap(), url);
        assert_eq!(url.join("c").unwrap().path(), "//c");

        let mut url = Url::default();
        url.set_path("//p");
        assert_eq!(url, "/.//p");
        assert_eq!(url.path(), "//p");

        let mut url = Url::from_static("http://h//p?q");
        assert_eq!(url.path(), "//p");
        url.set_authority(None).unwrap();
        assert_eq!(url, "http:/.//p?q");
        assert_eq!(url.path(), "//p");
        url.set_authority(Some("h")).unwrap();
        assert_eq!(url, "http://h//p?q");

        let parts = crate::Parts {
            path_and_query: "//p?q".into(),
            ..crate::Parts::default()
        };
        assert_eq!(Url::from_parts(parts).unwrap().path(), "//p");
    }
}