templated_uri 0.1.2

Standards-compliant URI handling with templating, safety validation, and data classification
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::fmt::{Debug, Display};
use std::str::FromStr;

use http::uri::PathAndQuery;

use crate::ValidationError;
use crate::uri::{Authority, Parts, Scheme};

mod base_path;
mod origin;

pub use base_path::BasePath;
pub use origin::Origin;

/// An HTTP or HTTPS [`BaseUri`] representing a target location with an optional path prefix.
///
/// [`BaseUri`] is a lightweight type that stores the scheme, authority, and an optional
/// path prefix of a URI, making it ideal for representing target destinations in HTTP scenarios.
/// It omits query string and fragment components, focusing on the base location information.
///
/// Use [`BaseUri`] when you need to:
///
/// - Store a base server location that will be combined with different paths.
/// - Handle scenarios where storing the full URI is unnecessary. For example, a list
///   of servers or [`BaseUri`] values.
/// - Expose a way to configure the base server location in your library. In this case,
///   the library manages its own paths and the consumer cares only about the target [`BaseUri`].
///
/// # Best Practices
///
/// For optimal performance when working with [`BaseUri`], follow these practices:
///
/// - Pre-create and cache static paths using `PathAndQuery::from_static` for frequently used paths.
/// - Combine static paths with [`BaseUri`] to create complete URIs without allocations.
/// - Use the `build_uri` method with these cached paths instead of passing strings each time.
/// - Consider making common paths constants in your application code.
///
/// ```rust
/// # use templated_uri::{BaseUri, uri::{Scheme, PathAndQuery}};
///
/// // Pre-create PathAndQuery objects (can be static or stored in a cache)
/// let api_path = PathAndQuery::from_static("/api/v1/resources");
/// let users_path = PathAndQuery::from_static("/api/v1/users");
///
/// // Create base_uri once
/// let base_uri = BaseUri::from_uri_static("https://api.example.com");
///
/// // Combine with a path to create a complete URI
/// let uri = base_uri.build_http_uri(api_path)?;
/// assert_eq!(uri.to_string(), "https://api.example.com/api/v1/resources");
///
/// // Reuse the base_uri with different paths without additional allocations
/// let uri = base_uri.build_http_uri(users_path)?;
/// assert_eq!(uri.to_string(), "https://api.example.com/api/v1/users");
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
///
/// # Examples
///
/// Creating `base_uri` with various constructors:
///
/// ```
/// # use templated_uri::{BasePath, BaseUri, uri::Scheme, };
/// // From scheme and authority
/// let base_uri1 = BaseUri::new(Scheme::HTTPS, "example.com")?;
/// assert_eq!(base_uri1.to_string(), "https://example.com/");
///
/// // From scheme, host, and port
/// let base_uri2 =
///     BaseUri::from_parts(Scheme::HTTP, "api.example.com", 8080, BasePath::default())?;
/// assert_eq!(base_uri2.to_string(), "http://api.example.com:8080/");
///
/// // From a URI string with path prefix
/// let base_uri3 = BaseUri::from_uri_str("https://auth.example.com/path/prefix/")?;
/// assert_eq!(
///     base_uri3.to_string(),
///     "https://auth.example.com/path/prefix/"
/// );
///
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
///
/// Converting an `base_uri` to a complete URI:
///
/// ```
/// # use templated_uri::{BaseUri, uri::{Scheme, PathAndQuery}};
/// let base_uri = BaseUri::new(Scheme::HTTPS, "api.example.com")?;
///
/// // Combine with a path to create a complete URI
/// let uri = base_uri.build_http_uri("/users/123?active=true")?;
/// assert_eq!(
///     uri.to_string(),
///     "https://api.example.com/users/123?active=true"
/// );
///
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BaseUri {
    /// The origin part of the URI, consisting of scheme and authority.
    origin: Origin,
    /// path prefix for the URI, always starts and ends with a slash
    ///
    /// In a perfect world, this would be `Option<BasePath>` and None would represent no path,
    /// but [`http::Uri`] which we need to interface with
    /// parses absent path (`http://example.com`) into a `/` path - which would lead into confusing
    /// behavior and inconsistency, so we are explicit about it.
    path: BasePath,
}

impl BaseUri {
    /// Creates a new [`BaseUri`] with the specified scheme and authority.
    ///
    /// This is a fallible constructor that attempts to convert the inputs to the
    /// required types. You can provide pre-constructed `Scheme` and `Authority` objects
    /// to avoid unnecessary conversions.
    ///
    /// # Arguments
    ///
    /// * `scheme`: The URI scheme (must be either HTTP or HTTPS).
    /// * `authority`: The authority component (hostname and optional port).
    ///
    /// # Errors
    ///
    /// Returns a validation error if:
    ///
    /// - The scheme is not HTTP or HTTPS.
    /// - The scheme or authority conversion fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::{Scheme, Authority}};
    /// // Default HTTPS port (443)
    /// let base_uri = BaseUri::new(Scheme::HTTPS, "example.com")?;
    /// assert_eq!(base_uri.to_string(), "https://example.com/");
    ///
    /// // Default HTTPS port (443)
    /// let base_uri = BaseUri::new(Scheme::HTTPS, "www.example.com")?;
    /// assert_eq!(base_uri.to_string(), "https://www.example.com/");
    ///
    /// // Default HTTP port (80)
    /// let base_uri = BaseUri::new(Scheme::HTTP, "example.com")?;
    /// assert_eq!(base_uri.to_string(), "http://example.com/");
    ///
    /// // Custom port
    /// let base_uri = BaseUri::new(Scheme::HTTPS, "example.com:1234")?;
    /// assert_eq!(base_uri.to_string(), "https://example.com:1234/");
    ///
    /// // Invalid or unsupported scheme
    /// let error = BaseUri::new("invalid", "example.com:1234").unwrap_err();
    /// assert!(
    ///     error
    ///         .to_string()
    ///         .starts_with("unsupported scheme: invalid, only HTTP and HTTPS schemes are supported")
    /// );
    ///
    /// // Invalid authority
    /// let error = BaseUri::new(Scheme::HTTPS, "exa/mple.com").unwrap_err();
    /// assert!(error.to_string().starts_with("invalid uri character"));
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(
        scheme: impl TryInto<Scheme, Error: Into<http::Error>>,
        authority: impl TryInto<Authority, Error: Into<http::Error>>,
    ) -> Result<Self, ValidationError> {
        let origin = Origin::new(scheme, authority)?;

        Ok(Self {
            origin,
            path: BasePath::default(),
        })
    }

    /// Sets the path component of this [`BaseUri`].
    ///
    /// The path must start and end with a slash (`/`).
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme, BasePath};
    /// let base_uri =
    ///     BaseUri::new(Scheme::HTTPS, "example.com")?.with_path(BasePath::try_from("/api/v1/")?)?;
    ///
    /// assert_eq!(base_uri.to_string(), "https://example.com/api/v1/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a [`ValidationError`] if the path cannot be converted to a valid [`BasePath`].
    pub fn with_path<P>(mut self, path: P) -> Result<Self, ValidationError>
    where
        P: TryInto<BasePath>,
        ValidationError: From<<P as TryInto<BasePath>>::Error>,
    {
        self.path = path.try_into()?;
        Ok(self)
    }

    /// Creates a [`BaseUri`] from a host, port, scheme and path.
    ///
    /// This is a convenience method that constructs the `base_uri` from individual components.
    ///
    /// # Arguments
    ///
    /// - `scheme`: The URI scheme (must be either HTTP or HTTPS).
    /// - `host`: The hostname.
    /// - `port`: The port number.
    /// - `path`: The path component. Must start and end with a slash (`/`)
    ///
    /// # Errors
    ///
    /// Returns a validation error if:
    ///
    /// - The scheme is not HTTP or HTTPS.
    /// - The provided host is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme, BasePath};
    /// let base_uri = BaseUri::from_parts(Scheme::HTTPS, "example.com", 1234, BasePath::default())?;
    /// assert_eq!(base_uri.to_string(), "https://example.com:1234/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_parts(scheme: Scheme, host: impl AsRef<str>, port: u16, path: BasePath) -> Result<Self, ValidationError> {
        Self::new(scheme, format!("{}:{}", host.as_ref(), port))?.with_path(path)
    }

    /// Creates an [`BaseUri`] from a static URI string.
    ///
    /// This method parses a static string as a URI and creates a [`BaseUri`] from it.
    /// The URI must contain both a scheme (HTTP or HTTPS) and an authority component.
    ///
    /// Any query string or fragment in the URI is silently discarded - only the scheme,
    /// authority and path prefix are preserved.
    ///
    /// # Arguments
    ///
    /// - `uri`: A static string representing a valid URI with HTTP or HTTPS scheme and authority.
    ///
    /// # Panics
    ///
    /// Panics if:
    ///
    /// - The provided string is not a valid URI.
    /// - The scheme is not HTTP or HTTPS.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com:443");
    /// assert_eq!(base_uri.to_string(), "https://example.com/");
    /// ```
    #[must_use]
    pub fn from_uri_static(uri: &'static str) -> Self {
        Self::from_http_uri(&http::Uri::from_static(uri)).expect("static str is not a valid base_uri URI")
    }

    /// Creates a [`BaseUri`] from a URI string.
    ///
    /// This method parses a string as a URI and extracts the scheme, authority and optional
    /// path prefix to create a [`BaseUri`]. The URI must contain both a scheme and authority,
    /// and the scheme must be either HTTP or HTTPS.
    ///
    /// Any query string or fragment in the URI is silently discarded - only the scheme,
    /// authority and path prefix are preserved.
    ///
    /// # Arguments
    ///
    /// - `uri`: A string representing a valid URI with HTTP or HTTPS scheme and authority.
    ///
    /// # Errors
    ///
    /// Returns a validation error if:
    ///
    /// - The URI string cannot be parsed as a valid URI.
    /// - The URI does not contain both a scheme and an authority component.
    /// - The scheme is not HTTP or HTTPS.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::BaseUri;
    /// let base_uri = BaseUri::from_uri_str("https://example.com:443")?;
    /// assert_eq!(base_uri.to_string(), "https://example.com/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Using a URI string with a path prefix:
    ///
    /// ```
    /// # use templated_uri::BaseUri;
    /// let base_uri = BaseUri::from_uri_str("https://example.com/path/prefix/")?;
    /// assert_eq!(base_uri.to_string(), "https://example.com/path/prefix/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Query strings are discarded:
    ///
    /// ```
    /// # use templated_uri::BaseUri;
    /// let base_uri = BaseUri::from_uri_str("https://example.com/path/?query=1")?;
    /// assert_eq!(base_uri.to_string(), "https://example.com/path/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_uri_str(uri: &str) -> Result<Self, ValidationError> {
        uri.parse::<http::Uri>()
            .map_err(Into::into)
            .and_then(|uri| Self::from_http_uri(&uri))
    }

    /// Creates a [`BaseUri`] from an existing `http::Uri`.
    ///
    /// Extracts the scheme, authority and optional path prefix from a `Uri` object to create
    /// a [`BaseUri`]. The URI must contain both a scheme and authority component.
    ///
    /// Any query string or fragment in the URI is silently discarded - only the scheme,
    /// authority and path are used.
    ///
    /// # Arguments
    ///
    /// - `uri`: A reference to an `http::Uri` object.
    ///
    /// # Errors
    ///
    /// Returns a validation error if the URI is missing either the scheme or authority component.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::BaseUri;
    /// let uri = "https://example.com".parse::<http::Uri>()?;
    /// let base_uri = BaseUri::from_http_uri(&uri)?;
    /// // Note the added trailing slash, this is a behavior of http::Uri parsing which initializes a `/`
    /// // path if none is present in input string, we can't do anything about it.
    /// assert_eq!(base_uri.to_string(), "https://example.com/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Using a URI string with a path:
    ///
    /// ```
    /// # use templated_uri::BaseUri;
    /// let uri = "https://example.com/path/".parse::<http::Uri>()?;
    /// let base_uri = BaseUri::from_http_uri(&uri)?;
    /// assert_eq!(base_uri.to_string(), "https://example.com/path/");
    /// assert_eq!(base_uri.path().as_str(), "/path/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Query and fragment are discarded:
    ///
    /// ```
    /// # use templated_uri::BaseUri;
    /// let uri = "https://example.com/path/?query=1".parse::<http::Uri>()?;
    /// let base_uri = BaseUri::from_http_uri(&uri)?;
    /// assert_eq!(base_uri.to_string(), "https://example.com/path/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_http_uri(uri: &http::Uri) -> Result<Self, ValidationError> {
        let (Some(scheme), Some(authority)) = (uri.scheme(), uri.authority()) else {
            return Err(ValidationError::invalid_uri("URI must have both scheme and authority components"));
        };

        // Use only the path component - query and fragment are not part of a base URI.
        let path = match uri.path() {
            "" | "/" => BasePath::default(),
            p => BasePath::try_from(p)?,
        };

        Self::new(scheme.clone(), authority.clone())?.with_path(path)
    }

    /// Returns a reference to the scheme component of this [`BaseUri`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com");
    /// assert_eq!(base_uri.scheme().as_str(), "https");
    /// ```
    pub const fn scheme(&self) -> &Scheme {
        self.origin.scheme()
    }

    /// Returns a reference to the authority component of this [`BaseUri`].
    ///
    /// The authority typically consists of a hostname and optional port.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com");
    /// assert_eq!(base_uri.authority().as_str(), "example.com");
    /// ```
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com:1234");
    /// assert_eq!(base_uri.authority().as_str(), "example.com:1234");
    /// ```
    pub const fn authority(&self) -> &Authority {
        self.origin.authority()
    }

    /// Returns the host part of this [`BaseUri`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com:443");
    /// assert_eq!(base_uri.host(), "example.com");
    /// ```
    pub fn host(&self) -> &str {
        self.origin.authority().host()
    }

    /// Returns the origin of this [`BaseUri`] in the form `scheme://authority`.
    pub fn origin(&self) -> &Origin {
        &self.origin
    }

    /// Consumes `BaseUri` and returns a new instance with different origin
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, Origin, uri::{Scheme, Authority}};
    /// let base_uri = BaseUri::from_uri_static("https://example.com:443");
    /// let new_base_uri = base_uri.with_origin(
    ///     Origin::new(
    ///         Scheme::HTTPS,
    ///         Authority::from_static("new-example.com:8080"),
    ///     )
    ///     .unwrap(),
    /// );
    /// assert_eq!(new_base_uri.to_string(), "https://new-example.com:8080/");
    /// ```
    #[must_use]
    pub fn with_origin(self, origin: Origin) -> Self {
        Self { origin, path: self.path }
    }

    /// Returns the port of this [`BaseUri`].
    ///
    /// This method determines the port based on the following rules:
    /// 1. If the authority explicitly specifies a port, that port is returned.
    /// 2. If no port is specified, a default port is returned based on the scheme:
    ///    - `80` for `http` scheme.
    ///    - `443` for `https` scheme.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// // Explicit port
    /// let base_uri = BaseUri::from_uri_static("https://example.com:8443");
    /// assert_eq!(base_uri.port(), 8443);
    ///
    /// // Default HTTPS port
    /// let base_uri = BaseUri::from_uri_static("https://example.com");
    /// assert_eq!(base_uri.port(), 443);
    ///
    /// // Default HTTP port
    /// let base_uri = BaseUri::from_uri_static("http://example.com");
    /// assert_eq!(base_uri.port(), 80);
    /// ```
    pub fn port(&self) -> u16 {
        self.origin.port()
    }

    /// Consume this `BaseUri` instance and return a new one with the specified port.
    ///
    /// # Examples
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let mut base_uri = BaseUri::from_uri_static("https://example.com");
    /// assert_eq!(base_uri.port(), 443);
    ///
    /// let base_uri = base_uri.with_port(8443);
    /// assert_eq!(base_uri.port(), 8443);
    /// assert_eq!(base_uri.to_string(), "https://example.com:8443/");
    /// ```
    #[must_use]
    pub fn with_port(self, port: u16) -> Self {
        Self {
            origin: self.origin.with_port(port),
            path: self.path,
        }
    }

    /// Returns a reference to the path component of this `base_uri`.
    ///
    /// The path is guaranteed to start and end with a slash (`/`).
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com/some/path/");
    ///
    /// assert_eq!(base_uri.path().as_str(), "/some/path/");
    /// ```
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let base_uri = BaseUri::from_uri_static("https://example.com");
    ///
    /// assert_eq!(base_uri.path().as_str(), "/");
    /// ```
    pub const fn path(&self) -> &BasePath {
        &self.path
    }

    /// Checks if this `base_uri` uses the HTTPS scheme.
    ///
    /// Returns `true` if the scheme is HTTPS, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme};
    /// let secure = BaseUri::from_uri_static("https://example.com");
    /// assert!(secure.is_https());
    ///
    /// let insecure = BaseUri::from_uri_static("http://example.com");
    /// assert!(!insecure.is_https());
    /// ```
    pub fn is_https(&self) -> bool {
        self.origin.is_https()
    }

    /// Constructs a complete URI by combining this `base_uri` with the given path.
    ///
    /// This method combines the [`BaseUri`] with the provided path to create a complete URI.
    /// The resulting URI will have the scheme, authority and path from this `base_uri`, and the path
    /// from the argument.
    ///
    /// # Arguments
    ///
    /// - `path`: A path or path with query parameters that will be converted to a `PathAndQuery`.
    ///
    /// # Errors
    ///
    /// Returns a validation error if the provided path cannot be converted into a `PathAndQuery`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::{Scheme, PathAndQuery}};
    /// let base_uri = BaseUri::from_uri_static("https://example.com");
    /// let uri = base_uri.build_http_uri("/api/resource?param=value")?;
    ///
    /// assert_eq!(
    ///     uri.to_string(),
    ///     "https://example.com/api/resource?param=value"
    /// );
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Using a path prefix as a part of the [`BaseUri`]:
    /// ```
    /// # use templated_uri::{BaseUri, uri::{Scheme, PathAndQuery}};
    /// let base_uri = BaseUri::from_uri_static("https://example.com/api/");
    /// let uri = base_uri.build_http_uri("resource?param=value")?;
    ///
    /// assert_eq!(
    ///     uri.to_string(),
    ///     "https://example.com/api/resource?param=value"
    /// );
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Using a pre-existing `PathAndQuery`:
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::{Scheme, PathAndQuery}};
    /// let base_uri = BaseUri::from_uri_static("https://example.com");
    ///
    /// // Pre-create and cache path and query to avoid parsing and extra allocations.
    /// let path = PathAndQuery::from_static("/api/resource?param=value");
    ///
    /// let uri = base_uri.build_http_uri(path)?;
    /// assert_eq!(
    ///     uri.to_string(),
    ///     "https://example.com/api/resource?param=value"
    /// );
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn build_http_uri(&self, path: impl TryInto<PathAndQuery, Error: Into<http::Error>>) -> Result<http::Uri, ValidationError> {
        let full_path = self.path.join(path)?;

        let mut parts = Parts::default();
        parts.scheme = Some(self.scheme().clone());
        parts.authority = Some(self.authority().clone());
        parts.path_and_query = Some(full_path);

        http::Uri::from_parts(parts).map_err(Into::into)
    }
}

impl TryFrom<http::Uri> for BaseUri {
    type Error = ValidationError;

    /// Tries to convert a URI into an `base_uri`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    ///
    /// - The URI does not have both scheme and authority components.
    /// - The scheme is not HTTP or HTTPS.
    fn try_from(uri: http::Uri) -> Result<Self, Self::Error> {
        Self::from_http_uri(&uri)
    }
}

impl From<Origin> for BaseUri {
    /// Converts an `Origin` into a `BaseUri` with a root path ("/").
    ///
    /// This conversion adds a minimal path component to ensure the resulting URI is valid.
    fn from(origin: Origin) -> Self {
        Self {
            origin,
            path: BasePath::default(),
        }
    }
}

impl FromStr for BaseUri {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_uri_str(s)
    }
}

impl From<BaseUri> for http::Uri {
    /// Converts an `base_uri` into a `Uri` with a root path ("/").
    ///
    /// This conversion adds a minimal path component to ensure the resulting URI is valid.
    fn from(value: BaseUri) -> Self {
        let (scheme, authority) = value.origin.into_parts();
        let mut parts = Parts::default();
        parts.scheme = Some(scheme);
        parts.authority = Some(authority);
        parts.path_and_query = Some(value.path.into());

        Self::from_parts(parts).expect("all inputs are already validated, this call never fails")
    }
}

impl Display for BaseUri {
    /// Formats the `base_uri` as a string in the form `scheme://authority/base_path/`.
    ///
    /// The [`BasePath`] always starts and ends with `/`, so the minimal form is
    /// `scheme://authority/` when no path prefix is set.
    ///
    /// Default ports (80 for HTTP, 443 for HTTPS) are omitted from the display string.
    /// Custom ports are included when present.
    ///
    /// # Examples
    ///
    /// ```
    /// # use templated_uri::{BaseUri, uri::Scheme, BasePath};
    /// let base_uri = BaseUri::from_parts(Scheme::HTTPS, "example.com", 443, BasePath::default())?;
    /// assert_eq!(format!("{}", base_uri), "https://example.com/");
    ///
    /// let custom_port = BaseUri::from_parts(Scheme::HTTPS, "example.com", 8443, BasePath::default())?;
    /// assert_eq!(format!("{}", custom_port), "https://example.com:8443/");
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}://", self.scheme())?;

        match (self.scheme().as_str(), self.port()) {
            ("http", 80) | ("https", 443) => write!(f, "{}", self.host())?,
            _ => write!(f, "{}", self.authority())?,
        }
        write!(f, "{}", self.path)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for BaseUri {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for BaseUri {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

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

    mod new {
        use super::*;

        #[test]
        fn valid_base_uri() {
            let base_uri = BaseUri::new(Scheme::HTTPS, "example.com").unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
        }

        #[test]
        fn with_custom_port() {
            let base_uri = BaseUri::new(Scheme::HTTP, "example.com:8080").unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTP);
            assert_eq!(base_uri.authority().as_str(), "example.com:8080");
        }

        #[test]
        fn with_string_scheme() {
            let base_uri = BaseUri::new("https", "example.com").unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
        }

        #[test]
        fn invalid_scheme() {
            let err = BaseUri::new("ftp", "example.com").unwrap_err();
            assert!(err.to_string().contains("unsupported scheme: ftp"));
        }

        #[test]
        fn invalid_authority() {
            let err = BaseUri::new(Scheme::HTTPS, "exam/ple.com:123").unwrap_err();
            assert!(err.to_string().contains("invalid uri"));
        }
    }

    mod from_parts {
        use super::*;

        #[test]
        fn valid_parts() {
            let base_uri = BaseUri::from_parts(Scheme::HTTPS, "example.com", 443, BasePath::from_str("/example/").unwrap()).unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com:443");
            assert_eq!(base_uri.to_string(), "https://example.com/example/");
        }

        #[test]
        fn invalid_host() {
            let err = BaseUri::from_parts(Scheme::HTTPS, "exa/mple.com", 443, BasePath::from_str("/example/").unwrap()).unwrap_err();
            assert!(err.to_string().contains("invalid uri"));
        }
    }

    mod from_uri_static {
        use super::*;

        #[test]
        fn valid_uri() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
        }

        #[test]
        fn with_path() {
            let base_uri = BaseUri::from_uri_static("https://example.com/path/to/resource/");
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
            assert_eq!(base_uri.to_string(), "https://example.com/path/to/resource/");
        }

        #[should_panic(expected = "static str is not a valid base_uri URI")]
        #[test]
        fn invalid_uri() {
            let _base_uri = BaseUri::from_uri_static("not-a-valid-uri");
        }
    }

    mod from_uri_str {
        use ohno::ErrorExt;

        use super::*;

        #[test]
        fn valid_uri() {
            let base_uri = BaseUri::from_uri_str("https://example.com/").unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
        }

        #[test]
        fn with_path() {
            let base_uri = BaseUri::from_uri_str("https://example.com/path/").unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
        }

        #[test]
        fn strips_query_from_path() {
            let base_uri = BaseUri::from_uri_str("https://example.com/path/?query=1&other=2").unwrap();
            assert_eq!(base_uri.to_string(), "https://example.com/path/");
        }

        #[test]
        fn invalid_uri() {
            let err = BaseUri::from_uri_str("not-a-valid-uri").unwrap_err();
            assert_eq!(err.message(), "URI must have both scheme and authority components");
        }
    }

    mod from_uri {
        use super::*;

        #[test]
        fn valid_uri() {
            let uri = http::Uri::from_static("https://example.com");
            let base_uri = BaseUri::from_http_uri(&uri).unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
        }

        #[test]
        fn with_path() {
            let uri = http::Uri::from_static("https://example.com/path/");
            let base_uri = BaseUri::from_http_uri(&uri).unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
            assert_eq!(base_uri.path().as_str(), "/path/");
        }

        #[test]
        fn strips_query_from_path() {
            let uri = http::Uri::from_static("https://example.com/path/?query=1");
            let base_uri = BaseUri::from_http_uri(&uri).unwrap();
            assert_eq!(base_uri.to_string(), "https://example.com/path/");
        }

        #[test]
        fn missing_components() {
            let uri = http::Uri::from_static("/just-a-path");
            let err = BaseUri::from_http_uri(&uri).unwrap_err();
            assert!(err.to_string().contains("URI must have both scheme and authority"));
        }
    }

    mod accessors {
        use super::*;

        #[test]
        fn scheme() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            assert_eq!(base_uri.scheme().as_str(), "https");
        }

        #[test]
        fn authority() {
            let base_uri = BaseUri::from_uri_static("https://example.com:8443");
            assert_eq!(base_uri.authority().as_str(), "example.com:8443");
        }

        #[test]
        fn host() {
            let base_uri = BaseUri::from_uri_static("https://example.com:8443");
            assert_eq!(base_uri.host(), "example.com");
        }

        #[test]
        fn port_explicit() {
            let base_uri = BaseUri::from_uri_static("https://example.com:8443");
            assert_eq!(base_uri.port(), 8443);
        }

        #[test]
        fn port_default_https() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            assert_eq!(base_uri.port(), 443);
        }

        #[test]
        fn port_default_http() {
            let base_uri = BaseUri::from_uri_static("http://example.com");
            assert_eq!(base_uri.port(), 80);
        }
    }

    mod is_https {
        use super::*;

        #[test]
        fn secure() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            assert!(base_uri.is_https());
        }

        #[test]
        fn insecure() {
            let base_uri = BaseUri::from_uri_static("http://example.com");
            assert!(!base_uri.is_https());
        }
    }

    mod build_uri {
        use super::*;

        #[test]
        fn with_path_string() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            let uri = base_uri.build_http_uri("/api/resource").unwrap();
            assert_eq!(uri.to_string(), "https://example.com/api/resource");
        }

        #[test]
        fn with_empty_uri() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            let uri = base_uri.build_http_uri("/").unwrap();
            assert_eq!(uri.to_string(), "https://example.com/");
        }

        #[test]
        fn with_path_and_query_string() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            let uri = base_uri.build_http_uri("/api/resource?param=value").unwrap();
            assert_eq!(uri.to_string(), "https://example.com/api/resource?param=value");
        }

        #[test]
        fn with_path_and_query_object() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            let path_and_query = PathAndQuery::from_static("/api/resource?param=value");
            let uri = base_uri.build_http_uri(path_and_query).unwrap();
            assert_eq!(uri.to_string(), "https://example.com/api/resource?param=value");
        }

        #[test]
        fn invalid_path() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            let invalid_path = "some path/?invalid\\character";
            let err = base_uri.build_http_uri(invalid_path).unwrap_err();
            assert!(err.to_string().contains("invalid uri character"));
        }
    }

    mod conversions {
        use super::*;

        #[test]
        fn uri_to_base_uri() {
            let uri = http::Uri::from_static("https://example.com/path/");
            let base_uri: BaseUri = uri.try_into().unwrap();
            assert_eq!(base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(base_uri.authority().as_str(), "example.com");
        }

        #[test]
        fn base_uri_to_uri() {
            let base_uri = BaseUri::from_uri_static("https://example.com");
            let uri: http::Uri = base_uri.into();
            assert_eq!(uri.to_string(), "https://example.com/");
        }

        #[test]
        fn origin_to_base_uri() {
            let origin = Origin::new(Scheme::HTTPS, "example.com:8443").unwrap();
            let base_uri: BaseUri = origin.into();

            assert_eq!(base_uri.to_string(), "https://example.com:8443/");
        }

        #[test]
        fn from_str_valid() {
            let base_uri: BaseUri = "https://example.com:8443/api/".parse().unwrap();

            assert_eq!(base_uri.to_string(), "https://example.com:8443/api/");
        }

        #[test]
        fn from_str_invalid() {
            let err = "not-a-valid-uri".parse::<BaseUri>().unwrap_err();
            assert!(err.to_string().contains("URI must have both scheme and authority"));
        }
    }

    mod display {
        use super::*;

        #[test]
        fn http_default_port() {
            let base_uri = BaseUri::from_uri_static("http://example.com:80");
            assert_eq!(base_uri.to_string(), "http://example.com/");
        }

        #[test]
        fn https_default_port() {
            let base_uri = BaseUri::from_uri_static("https://example.com:443");
            assert_eq!(base_uri.to_string(), "https://example.com/");
        }

        #[test]
        fn custom_port() {
            let base_uri = BaseUri::from_uri_static("https://example.com:8443");
            assert_eq!(base_uri.to_string(), "https://example.com:8443/");
        }
    }

    mod with_origin {
        use super::*;

        #[test]
        fn replaces_origin() {
            let base_uri = BaseUri::from_uri_static("https://example.com/api/");
            let new_origin = Origin::new(Scheme::HTTPS, "new-example.com:8080").unwrap();

            let new_base_uri = base_uri.with_origin(new_origin.clone());

            assert_eq!(new_base_uri.origin(), &new_origin);
            assert_eq!(new_base_uri.scheme(), &Scheme::HTTPS);
            assert_eq!(new_base_uri.authority().as_str(), "new-example.com:8080");
            assert_eq!(new_base_uri.port(), 8080);
            assert_eq!(new_base_uri.path().as_str(), "/api/");
            assert_eq!(new_base_uri.to_string(), "https://new-example.com:8080/api/");
        }
    }

    mod with_port {
        use super::*;

        #[test]
        fn changes_port() {
            let base_uri = BaseUri::from_uri_static("https://example.com/api/");

            let new_base_uri = base_uri.with_port(8443);

            assert_eq!(new_base_uri.origin().port(), 8443);
            assert_eq!(new_base_uri.port(), 8443);
            assert_eq!(new_base_uri.to_string(), "https://example.com:8443/api/");
        }
    }

    #[cfg(feature = "serde")]
    mod serde_tests {
        use super::*;

        #[test]
        fn base_uri_roundtrip() {
            let original = BaseUri::from_uri_static("https://example.com:8443/api/");
            let json = serde_json::to_string(&original).unwrap();
            assert_eq!(json, r#""https://example.com:8443/api/""#);
            let deserialized: BaseUri = serde_json::from_str(&json).unwrap();
            assert_eq!(original, deserialized);
        }

        #[test]
        fn base_uri_deserialize_rejects_invalid() {
            serde_json::from_str::<BaseUri>(r#""not-a-uri""#).unwrap_err();
        }
    }
}