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
//! URI/IRI builder.
//!
//! See the documentation of [`Builder`] type.

use core::fmt::{self, Display as _, Write as _};
use core::marker::PhantomData;

#[cfg(feature = "alloc")]
use alloc::collections::TryReserveError;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::string::ToString;

use crate::format::Censored;
#[cfg(feature = "alloc")]
use crate::format::{ToDedicatedString, ToStringFallible};
use crate::normalize::{self, NormalizationMode, PathCharacteristic, PctCaseNormalized};
use crate::parser::str::{find_split, prior_byte2};
use crate::parser::validate as parser;
use crate::spec::Spec;
use crate::types::{RiAbsoluteStr, RiReferenceStr, RiRelativeStr, RiStr};
#[cfg(feature = "alloc")]
use crate::types::{RiAbsoluteString, RiReferenceString, RiRelativeString, RiString};
use crate::validate::Error;

/// Port builder.
///
/// This type is intended to be created by `From` trait implementations, and
/// to be passed to [`Builder::port`] method.
#[derive(Debug, Clone)]
pub struct PortBuilder<'a>(PortBuilderRepr<'a>);

impl Default for PortBuilder<'_> {
    #[inline]
    fn default() -> Self {
        Self(PortBuilderRepr::Empty)
    }
}

impl<'a> From<u8> for PortBuilder<'a> {
    #[inline]
    fn from(v: u8) -> Self {
        Self(PortBuilderRepr::Integer(v.into()))
    }
}

impl<'a> From<u16> for PortBuilder<'a> {
    #[inline]
    fn from(v: u16) -> Self {
        Self(PortBuilderRepr::Integer(v))
    }
}

impl<'a> From<&'a str> for PortBuilder<'a> {
    #[inline]
    fn from(v: &'a str) -> Self {
        Self(PortBuilderRepr::String(v))
    }
}

#[cfg(feature = "alloc")]
impl<'a> From<&'a alloc::string::String> for PortBuilder<'a> {
    #[inline]
    fn from(v: &'a alloc::string::String) -> Self {
        Self(PortBuilderRepr::String(v.as_str()))
    }
}

/// Internal representation of a port builder.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
enum PortBuilderRepr<'a> {
    /// Empty port.
    Empty,
    /// Port as an integer.
    ///
    /// Note that RFC 3986 accepts any number of digits as a port, but
    /// practically (at least in TCP/IP) `u16` is enough.
    Integer(u16),
    /// Port as a string.
    String(&'a str),
}

/// Userinfo builder.
///
/// This type is intended to be created by `From` trait implementations, and
/// to be passed to [`Builder::userinfo`] method.
#[derive(Clone)]
pub struct UserinfoBuilder<'a>(UserinfoRepr<'a>);

impl Default for UserinfoBuilder<'_> {
    #[inline]
    fn default() -> Self {
        Self(UserinfoRepr::None)
    }
}

impl fmt::Debug for UserinfoBuilder<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("UserinfoBuilder");
        if let Some((user, password)) = self.to_user_password() {
            debug.field("user", &user);
            // > Applications should not render as clear text any data after
            // > the first colon (":") character found within a userinfo
            // > subcomponent unless the data after the colon is the empty
            // > string (indicating no password).
            if matches!(password, None | Some("")) {
                debug.field("password", &password);
            } else {
                debug.field("password", &Some(Censored));
            }
        }
        debug.finish()
    }
}

impl<'a> UserinfoBuilder<'a> {
    /// Decomposes the userinfo into `user` and `password`.
    #[must_use]
    fn to_user_password(&self) -> Option<(&'a str, Option<&'a str>)> {
        match &self.0 {
            UserinfoRepr::None => None,
            UserinfoRepr::Direct(s) => match find_split(s, b':') {
                None => Some((s, None)),
                Some((user, password)) => Some((user, Some(password))),
            },
            UserinfoRepr::UserPass(user, password) => Some((*user, *password)),
        }
    }
}

impl<'a> From<&'a str> for UserinfoBuilder<'a> {
    #[inline]
    fn from(direct: &'a str) -> Self {
        Self(UserinfoRepr::Direct(direct))
    }
}

impl<'a> From<(&'a str, &'a str)> for UserinfoBuilder<'a> {
    #[inline]
    fn from((user, password): (&'a str, &'a str)) -> Self {
        Self(UserinfoRepr::UserPass(user, Some(password)))
    }
}

impl<'a> From<(&'a str, Option<&'a str>)> for UserinfoBuilder<'a> {
    #[inline]
    fn from((user, password): (&'a str, Option<&'a str>)) -> Self {
        Self(UserinfoRepr::UserPass(user, password))
    }
}

#[cfg(feature = "alloc")]
impl<'a> From<&'a alloc::string::String> for UserinfoBuilder<'a> {
    #[inline]
    fn from(v: &'a alloc::string::String) -> Self {
        Self::from(v.as_str())
    }
}

/// Internal representation of a userinfo builder.
#[derive(Clone, Copy)]
enum UserinfoRepr<'a> {
    /// Not specified (absent).
    None,
    /// Direct `userinfo` content.
    Direct(&'a str),
    /// User name and password.
    UserPass(&'a str, Option<&'a str>),
}

/// URI/IRI authority builder.
#[derive(Default, Debug, Clone)]
struct AuthorityBuilder<'a> {
    /// Host.
    host: HostRepr<'a>,
    /// Port.
    port: PortBuilder<'a>,
    /// Userinfo.
    userinfo: UserinfoBuilder<'a>,
}

impl AuthorityBuilder<'_> {
    /// Writes the authority to the given formatter.
    fn fmt_write_to<S: Spec>(&self, f: &mut fmt::Formatter<'_>, normalize: bool) -> fmt::Result {
        match &self.userinfo.0 {
            UserinfoRepr::None => {}
            UserinfoRepr::Direct(userinfo) => {
                if normalize {
                    PctCaseNormalized::<S>::new(userinfo).fmt(f)?;
                } else {
                    userinfo.fmt(f)?;
                }
                f.write_char('@')?;
            }
            UserinfoRepr::UserPass(user, password) => {
                if normalize {
                    PctCaseNormalized::<S>::new(user).fmt(f)?;
                } else {
                    f.write_str(user)?;
                }
                if let Some(password) = password {
                    f.write_char(':')?;
                    if normalize {
                        PctCaseNormalized::<S>::new(password).fmt(f)?;
                    } else {
                        password.fmt(f)?;
                    }
                }
                f.write_char('@')?;
            }
        }

        match self.host {
            HostRepr::String(host) => {
                if normalize {
                    normalize::normalize_host_port::<S>(f, host)?;
                } else {
                    f.write_str(host)?;
                }
            }
            #[cfg(feature = "std")]
            HostRepr::IpAddr(ipaddr) => match ipaddr {
                std::net::IpAddr::V4(v) => v.fmt(f)?,
                std::net::IpAddr::V6(v) => write!(f, "[{v}]")?,
            },
        }

        match self.port.0 {
            PortBuilderRepr::Empty => {}
            PortBuilderRepr::Integer(v) => write!(f, ":{v}")?,
            PortBuilderRepr::String(v) => {
                // Omit empty port if the normalization is enabled.
                if !(v.is_empty() && normalize) {
                    write!(f, ":{v}")?;
                }
            }
        }

        Ok(())
    }
}

/// Host representation.
#[derive(Debug, Clone, Copy)]
enum HostRepr<'a> {
    /// Direct string representation.
    String(&'a str),
    #[cfg(feature = "std")]
    /// Dedicated IP address type.
    IpAddr(std::net::IpAddr),
}

impl Default for HostRepr<'_> {
    #[inline]
    fn default() -> Self {
        Self::String("")
    }
}

/// URI/IRI reference builder.
///
/// # Usage
///
/// 1. Create builder by [`Builder::new()`][`Self::new`].
/// 2. Set (or unset) components and set normalization mode as you wish.
/// 3. Validate by [`Builder::build()`][`Self::build`] and get [`Built`] value.
/// 4. Use [`core::fmt::Display`] trait to serialize the resulting [`Built`],
///    or use [`From`]/[`Into`] traits to convert into an allocated string types.
///
/// ```
/// # use iri_string::validate::Error;
/// use iri_string::build::Builder;
/// # #[cfg(not(feature = "alloc"))]
/// # use iri_string::types::IriStr;
/// # #[cfg(feature = "alloc")]
/// use iri_string::types::{IriStr, IriString};
///
/// // 1. Create builder.
/// let mut builder = Builder::new();
///
/// // 2. Set (or unset) component and normalization mode.
/// builder.scheme("http");
/// builder.host("example.com");
/// builder.path("/foo/../");
/// builder.normalize();
///
/// // 3. Validate and create the result.
/// let built = builder.build::<IriStr>()?;
///
/// # #[cfg(feature = "alloc")] {
/// // 4a. Serialize by `Display` trait (or `ToString`).
/// let s = built.to_string();
/// assert_eq!(s, "http://example.com/");
/// # }
///
/// # #[cfg(feature = "alloc")] {
/// // 4b. Convert into an allocated string types.
/// // Thanks to pre-validation by `.build::<IriStr>()`, this conversion is infallible!
/// let s: IriString = built.into();
/// assert_eq!(s, "http://example.com/");
/// # }
///
/// # Ok::<_, Error>(())
/// ```
#[derive(Default, Debug, Clone)]
pub struct Builder<'a> {
    /// Scheme.
    scheme: Option<&'a str>,
    /// Authority.
    authority: Option<AuthorityBuilder<'a>>,
    /// Path.
    path: &'a str,
    /// Query (without the leading `?`).
    query: Option<&'a str>,
    /// Fragment (without the leading `#`).
    fragment: Option<&'a str>,
    /// Normalization mode.
    normalize: bool,
}

impl<'a> Builder<'a> {
    /// Creates a builder with empty data.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let builder = Builder::new();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Writes the authority to the given formatter.
    ///
    /// Don't expose this as public, since this method does not validate.
    ///
    /// # Preconditions
    ///
    /// The IRI string to be built should be a valid IRI reference.
    /// Callers are responsible to validate the component values before calling
    /// this method.
    fn fmt_write_to<S: Spec>(
        &self,
        f: &mut fmt::Formatter<'_>,
        path_is_absolute: bool,
    ) -> fmt::Result {
        if let Some(scheme) = self.scheme {
            // Write the scheme.
            if self.normalize {
                normalize::normalize_scheme(f, scheme)?;
            } else {
                f.write_str(scheme)?;
            }
            f.write_char(':')?;
        }

        if let Some(authority) = &self.authority {
            f.write_str("//")?;
            authority.fmt_write_to::<S>(f, self.normalize)?;
        }

        if !self.normalize {
            // No normalization.
            f.write_str(self.path)?;
        } else if self.scheme.is_some() || self.authority.is_some() || path_is_absolute {
            // Apply full syntax-based normalization.
            let op = normalize::NormalizationOp {
                mode: NormalizationMode::Default,
            };
            normalize::PathToNormalize::from_single_path(self.path).fmt_write_normalize::<S, _>(
                f,
                op,
                self.authority.is_some(),
            )?;
        } else {
            // The IRI reference starts with `path` component, and the path is relative.
            // Skip path segment normalization.
            PctCaseNormalized::<S>::new(self.path).fmt(f)?;
        }

        if let Some(query) = self.query {
            f.write_char('?')?;
            if self.normalize {
                normalize::normalize_query::<S>(f, query)?;
            } else {
                f.write_str(query)?;
            }
        }

        if let Some(fragment) = self.fragment {
            f.write_char('#')?;
            if self.normalize {
                normalize::normalize_fragment::<S>(f, fragment)?;
            } else {
                f.write_str(fragment)?;
            }
        }

        Ok(())
    }

    /// Builds the proxy object that can be converted to the desired IRI string type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriStr;
    /// # #[cfg(feature = "alloc")]
    /// use iri_string::types::IriString;
    ///
    /// let mut builder = Builder::new();
    ///
    /// builder.scheme("http");
    /// builder.host("example.com");
    /// builder.path("/foo/bar");
    ///
    /// let built = builder.build::<IriStr>()?;
    ///
    /// # #[cfg(feature = "alloc")] {
    /// // The returned value implements `core::fmt::Display` and
    /// // `core::string::ToString`.
    /// assert_eq!(built.to_string(), "http://example.com/foo/bar");
    ///
    /// // The returned value implements `Into<{iri_owned_string_type}>`.
    /// let iri = IriString::from(built);
    /// // `let iri: IriString = built.into();` is also OK.
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn build<T>(self) -> Result<Built<'a, T>, Error>
    where
        T: ?Sized + Buildable<'a>,
    {
        <T as private::Sealed<'a>>::validate_builder(self)
    }
}

// Setters does not return `&mut Self` or `Self` since it introduces needless
// ambiguity for users.
// For example, if setters return something and allows method chaining, can you
// correctly explain what happens with the code below without reading document?
//
// ```text
// let mut builder = Builder::new().foo("foo").bar("bar");
// let baz = builder.baz("baz").clone().build();
// // Should the result be foo+bar+qux, or foo+bar+baz+qux?
// let qux = builder.qux("qux").build();
// ```
impl<'a> Builder<'a> {
    /// Sets the scheme.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.scheme("foo");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "foo:");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn scheme(&mut self, v: &'a str) {
        self.scheme = Some(v);
    }

    /// Unsets the scheme.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.scheme("foo");
    /// builder.unset_scheme();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_scheme(&mut self) {
        self.scheme = None;
    }

    /// Sets the path.
    ///
    /// Note that no methods are provided to "unset" path since every IRI
    /// references has a path component (although it can be empty).
    /// If you want to "unset" the path, just set the empty string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.path("foo/bar");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "foo/bar");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn path(&mut self, v: &'a str) {
        self.path = v;
    }

    /// Initializes the authority builder.
    #[inline]
    fn authority_builder(&mut self) -> &mut AuthorityBuilder<'a> {
        self.authority.get_or_insert_with(AuthorityBuilder::default)
    }

    /// Unsets the authority.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.host("example.com");
    /// builder.unset_authority();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_authority(&mut self) {
        self.authority = None;
    }

    /// Sets the userinfo.
    ///
    /// `userinfo` component always have `user` part (but it can be empty).
    ///
    /// Note that `("", None)` is considered as an empty userinfo, rather than
    /// unset userinfo.
    /// Also note that the user part cannot have colon characters.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.userinfo("user:pass");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//user:pass@");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    ///
    /// You can specify `(user, password)` pair.
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    ///
    /// builder.userinfo(("user", Some("pass")));
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(
    ///     builder.clone().build::<IriReferenceStr>()?.to_string(),
    ///     "//user:pass@"
    /// );
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    ///
    /// `("", None)` is considered as an empty userinfo.
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.userinfo(("", None));
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//@");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn userinfo<T: Into<UserinfoBuilder<'a>>>(&mut self, v: T) {
        self.authority_builder().userinfo = v.into();
    }

    /// Unsets the port.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.userinfo("user:pass");
    /// // Note that this does not unset the entire authority.
    /// // Now empty authority is set.
    /// builder.unset_userinfo();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_userinfo(&mut self) {
        self.authority_builder().userinfo = UserinfoBuilder::default();
    }

    /// Sets the reg-name or IP address (i.e. host) without port.
    ///
    /// Note that no methods are provided to "unset" host.
    /// Depending on your situation, set empty string as a reg-name, or unset
    /// the authority entirely by [`unset_authority`][`Self::unset_authority`]
    /// method.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.host("example.com");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//example.com");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn host(&mut self, v: &'a str) {
        self.authority_builder().host = HostRepr::String(v);
    }

    /// Sets the IP address as a host.
    ///
    /// Note that no methods are provided to "unset" host.
    /// Depending on your situation, set empty string as a reg-name, or unset
    /// the authority entirely by [`unset_authority`][`Self::unset_authority`]
    /// method.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// # #[cfg(feature = "std")] {
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.ip_address(std::net::Ipv4Addr::new(192, 0, 2, 0));
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//192.0.2.0");
    /// # }
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[cfg(feature = "std")]
    #[inline]
    pub fn ip_address<T: Into<std::net::IpAddr>>(&mut self, addr: T) {
        self.authority_builder().host = HostRepr::IpAddr(addr.into());
    }

    /// Sets the port.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.port(80_u16);
    /// // Accepts other types that implements `Into<PortBuilder<'a>>`.
    /// //builder.port(80_u8);
    /// //builder.port("80");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//:80");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn port<T: Into<PortBuilder<'a>>>(&mut self, v: T) {
        self.authority_builder().port = v.into();
    }

    /// Unsets the port.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.port(80_u16);
    /// // Note that this does not unset the entire authority.
    /// // Now empty authority is set.
    /// builder.unset_port();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "//");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_port(&mut self) {
        self.authority_builder().port = PortBuilder::default();
    }

    /// Sets the query.
    ///
    /// The string after `?` should be specified.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.query("q=example");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "?q=example");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn query(&mut self, v: &'a str) {
        self.query = Some(v);
    }

    /// Unsets the query.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.query("q=example");
    /// builder.unset_query();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_query(&mut self) {
        self.query = None;
    }

    /// Sets the fragment.
    ///
    /// The string after `#` should be specified.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.fragment("anchor");
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "#anchor");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn fragment(&mut self, v: &'a str) {
        self.fragment = Some(v);
    }

    /// Unsets the fragment.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.fragment("anchor");
    /// builder.unset_fragment();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_fragment(&mut self) {
        self.fragment = None;
    }

    /// Stop normalizing the result.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.scheme("http");
    /// // `%75%73%65%72` is "user".
    /// builder.userinfo("%75%73%65%72");
    /// builder.host("EXAMPLE.COM");
    /// builder.port("");
    /// builder.path("/foo/../%2e%2e/bar/%2e/baz/.");
    ///
    /// builder.unset_normalize();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(
    ///     iri.to_string(),
    ///     "http://%75%73%65%72@EXAMPLE.COM:/foo/../%2e%2e/bar/%2e/baz/."
    /// );
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn unset_normalize(&mut self) {
        self.normalize = false;
    }

    /// Normalizes the result using RFC 3986 syntax-based normalization and
    /// WHATWG URL Standard algorithm.
    ///
    /// # Normalization
    ///
    /// If `scheme` or `authority` component is present or the path is absolute,
    /// the build result will fully normalized using full syntax-based normalization:
    ///
    /// * case normalization ([RFC 3986 6.2.2.1]),
    /// * percent-encoding normalization ([RFC 3986 6.2.2.2]), and
    /// * path segment normalization ([RFC 3986 6.2.2.2]).
    ///
    /// However, if both `scheme` and `authority` is absent and the path is relative
    /// (including empty), i.e. the IRI reference to be built starts with the
    /// relative `path` component, path segment normalization will be omitted.
    /// This is because the path segment normalization depends on presence or
    /// absense of the `authority` components, and will remove extra `..`
    /// segments which should not be ignored.
    ///
    /// Note that `path` must already be empty or start with a slash **before
    /// the normalizaiton** if `authority` is present.
    ///
    /// # WHATWG URL Standard
    ///
    /// If you need to avoid WHATWG URL Standard serialization, use
    /// [`Built::ensure_rfc3986_normalizable`] method to test if the result is
    /// normalizable without WHATWG spec.
    ///
    /// # Examples
    ///
    /// ```
    /// # use iri_string::validate::Error;
    /// use iri_string::build::Builder;
    /// use iri_string::types::IriReferenceStr;
    ///
    /// let mut builder = Builder::new();
    /// builder.scheme("http");
    /// // `%75%73%65%72` is "user".
    /// builder.userinfo("%75%73%65%72");
    /// builder.host("EXAMPLE.COM");
    /// builder.port("");
    /// builder.path("/foo/../%2e%2e/bar/%2e/baz/.");
    ///
    /// builder.normalize();
    ///
    /// let iri = builder.build::<IriReferenceStr>()?;
    /// # #[cfg(feature = "alloc")] {
    /// assert_eq!(iri.to_string(), "http://user@example.com/bar/baz/");
    /// # }
    /// # Ok::<_, Error>(())
    /// ```
    #[inline]
    pub fn normalize(&mut self) {
        self.normalize = true;
    }
}

/// [`Display`]-able IRI build result.
///
/// The value of this type can generate an IRI using [`From`]/[`Into`] traits or
/// [`Display`] trait.
///
/// # Security consideration
///
/// This can be stringified or directly printed by `std::fmt::Display`, but note
/// that this `Display` **does not hide the password part**. Be careful **not to
/// print the value using `Display for Built<_>` in public context**.
///
/// [`From`]: `core::convert::From`
/// [`Into`]: `core::convert::Into`
/// [`Display`]: `core::fmt::Display`
#[derive(Debug)]
pub struct Built<'a, T: ?Sized> {
    /// Builder with the validated content.
    builder: Builder<'a>,
    /// Whether the path is absolute.
    path_is_absolute: bool,
    /// String type.
    _ty_str: PhantomData<fn() -> T>,
}

impl<T: ?Sized> Clone for Built<'_, T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            builder: self.builder.clone(),
            path_is_absolute: self.path_is_absolute,
            _ty_str: PhantomData,
        }
    }
}

/// Implements conversions to a string.
macro_rules! impl_stringifiers {
    ($borrowed:ident, $owned:ident) => {
        impl<S: Spec> Built<'_, $borrowed<S>> {
            /// Returns Ok`(())` if the IRI is normalizable by the RFC 3986 algorithm.
            #[inline]
            pub fn ensure_rfc3986_normalizable(&self) -> Result<(), normalize::Error> {
                if self.builder.authority.is_none() {
                    let path = normalize::PathToNormalize::from_single_path(self.builder.path);
                    path.ensure_rfc3986_normalizable_with_authority_absent()?;
                }
                Ok(())
            }
        }

        impl<S: Spec> fmt::Display for Built<'_, $borrowed<S>> {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.builder.fmt_write_to::<S>(f, self.path_is_absolute)
            }
        }

        #[cfg(feature = "alloc")]
        impl<S: Spec> ToDedicatedString for Built<'_, $borrowed<S>> {
            type Target = $owned<S>;

            #[inline]
            fn try_to_dedicated_string(&self) -> Result<Self::Target, TryReserveError> {
                let s = self.try_to_string()?;
                Ok(TryFrom::try_from(s)
                    .expect("[validity] the IRI to be built is already validated"))
            }
        }

        #[cfg(feature = "alloc")]
        impl<S: Spec> From<Built<'_, $borrowed<S>>> for $owned<S> {
            #[inline]
            fn from(builder: Built<'_, $borrowed<S>>) -> Self {
                (&builder).into()
            }
        }

        #[cfg(feature = "alloc")]
        impl<S: Spec> From<&Built<'_, $borrowed<S>>> for $owned<S> {
            #[inline]
            fn from(builder: &Built<'_, $borrowed<S>>) -> Self {
                let s = builder.to_string();
                Self::try_from(s).expect("[validity] the IRI to be built is already validated")
            }
        }
    };
}

impl_stringifiers!(RiReferenceStr, RiReferenceString);
impl_stringifiers!(RiStr, RiString);
impl_stringifiers!(RiAbsoluteStr, RiAbsoluteString);
impl_stringifiers!(RiRelativeStr, RiRelativeString);

/// A trait for borrowed IRI string types buildable by the [`Builder`].
pub trait Buildable<'a>: private::Sealed<'a> {}

impl<'a, S: Spec> private::Sealed<'a> for RiReferenceStr<S> {
    fn validate_builder(builder: Builder<'a>) -> Result<Built<'a, Self>, Error> {
        let path_is_absolute = validate_builder_for_iri_reference::<S>(&builder)?;

        Ok(Built {
            builder,
            path_is_absolute,
            _ty_str: PhantomData,
        })
    }
}
impl<'a, S: Spec> Buildable<'a> for RiReferenceStr<S> {}

impl<'a, S: Spec> private::Sealed<'a> for RiStr<S> {
    fn validate_builder(builder: Builder<'a>) -> Result<Built<'a, Self>, Error> {
        if builder.scheme.is_none() {
            return Err(Error::new());
        }
        let path_is_absolute = validate_builder_for_iri_reference::<S>(&builder)?;

        Ok(Built {
            builder,
            path_is_absolute,
            _ty_str: PhantomData,
        })
    }
}
impl<'a, S: Spec> Buildable<'a> for RiStr<S> {}

impl<'a, S: Spec> private::Sealed<'a> for RiAbsoluteStr<S> {
    fn validate_builder(builder: Builder<'a>) -> Result<Built<'a, Self>, Error> {
        if builder.scheme.is_none() {
            return Err(Error::new());
        }
        if builder.fragment.is_some() {
            return Err(Error::new());
        }
        let path_is_absolute = validate_builder_for_iri_reference::<S>(&builder)?;

        Ok(Built {
            builder,
            path_is_absolute,
            _ty_str: PhantomData,
        })
    }
}
impl<'a, S: Spec> Buildable<'a> for RiAbsoluteStr<S> {}

impl<'a, S: Spec> private::Sealed<'a> for RiRelativeStr<S> {
    fn validate_builder(builder: Builder<'a>) -> Result<Built<'a, Self>, Error> {
        if builder.scheme.is_some() {
            return Err(Error::new());
        }
        let path_is_absolute = validate_builder_for_iri_reference::<S>(&builder)?;

        Ok(Built {
            builder,
            path_is_absolute,
            _ty_str: PhantomData,
        })
    }
}
impl<'a, S: Spec> Buildable<'a> for RiRelativeStr<S> {}

/// Checks whether the builder output is valid IRI reference.
///
/// Returns whether the path is absolute.
fn validate_builder_for_iri_reference<S: Spec>(builder: &Builder<'_>) -> Result<bool, Error> {
    if let Some(scheme) = builder.scheme {
        parser::validate_scheme(scheme)?;
    }

    if let Some(authority) = &builder.authority {
        match &authority.userinfo.0 {
            UserinfoRepr::None => {}
            UserinfoRepr::Direct(userinfo) => {
                parser::validate_userinfo::<S>(userinfo)?;
            }
            UserinfoRepr::UserPass(user, password) => {
                // `user` is not allowed to have a colon, since the characters
                // after the colon is parsed as the password.
                if user.contains(':') {
                    return Err(Error::new());
                }

                // Note that the syntax of components inside `authority`
                // (`user` and `password`) is not specified by RFC 3986.
                parser::validate_userinfo::<S>(user)?;
                if let Some(password) = password {
                    parser::validate_userinfo::<S>(password)?;
                }
            }
        }

        match authority.host {
            HostRepr::String(s) => parser::validate_host::<S>(s)?,
            #[cfg(feature = "std")]
            HostRepr::IpAddr(_) => {}
        }

        if let PortBuilderRepr::String(s) = authority.port.0 {
            if !s.bytes().all(|b| b.is_ascii_digit()) {
                return Err(Error::new());
            }
        }
    }

    let path_is_absolute: bool;
    let mut is_path_acceptable;
    if builder.normalize {
        if builder.scheme.is_some() || builder.authority.is_some() || builder.path.starts_with('/')
        {
            if builder.authority.is_some() {
                // Note that the path should already be in an absolute form before normalization.
                is_path_acceptable = builder.path.is_empty() || builder.path.starts_with('/');
            } else {
                is_path_acceptable = true;
            }
            let op = normalize::NormalizationOp {
                mode: NormalizationMode::Default,
            };
            let path_characteristic = PathCharacteristic::from_path_to_display::<S>(
                &normalize::PathToNormalize::from_single_path(builder.path),
                op,
                builder.authority.is_some(),
            );
            path_is_absolute = path_characteristic.is_absolute();
            is_path_acceptable = is_path_acceptable
                && match path_characteristic {
                    PathCharacteristic::CommonAbsolute | PathCharacteristic::CommonRelative => true,
                    PathCharacteristic::StartsWithDoubleSlash
                    | PathCharacteristic::RelativeFirstSegmentHasColon => {
                        builder.scheme.is_some() || builder.authority.is_some()
                    }
                };
        } else {
            path_is_absolute = false;
            // If the path is relative (where neither scheme nor authority is
            // available), the first segment should not contain a colon.
            is_path_acceptable = prior_byte2(builder.path.as_bytes(), b'/', b':') != Some(b':');
        }
    } else {
        path_is_absolute = builder.path.starts_with('/');
        is_path_acceptable = if builder.authority.is_some() {
            // The path should be absolute or empty.
            path_is_absolute || builder.path.is_empty()
        } else if builder.scheme.is_some() || path_is_absolute {
            // The path should not start with '//'.
            !builder.path.starts_with("//")
        } else {
            // If the path is relative (where neither scheme nor authority is
            // available), the first segment should not contain a colon.
            prior_byte2(builder.path.as_bytes(), b'/', b':') != Some(b':')
        };
    }
    if !is_path_acceptable {
        return Err(Error::new());
    }

    if let Some(query) = builder.query {
        parser::validate_query::<S>(query)?;
    }

    if let Some(fragment) = builder.fragment {
        parser::validate_fragment::<S>(fragment)?;
    }

    Ok(path_is_absolute)
}

/// Private module to put the trait to seal.
mod private {
    use super::{Builder, Built, Error};

    /// A trait for types buildable by the [`Builder`].
    pub trait Sealed<'a> {
        /// Validates the content of the builder and returns the validated type if possible.
        fn validate_builder(builder: Builder<'a>) -> Result<Built<'a, Self>, Error>;
    }
}