Skip to main content

urly/
lib.rs

1//! URL manipulation library with an API inspired by Python's
2//! [yarl](https://yarl.aio-libs.org/).
3//!
4//! [`Url`] is a cheaply cloneable URL reference stored
5//! in a single [`ByteString`](ntex_bytes::ByteString). Accessors return
6//! borrowed components with methods to decode them. General-purpose parsing
7//! normalizes URLs; [`Url::parse_target`] preserves unvalidated HTTP request-target
8//! components for later [`Url::validate_target`] and [`Url::normalize`] calls. Component setters
9//! normalize the components they replace, not the rest of a raw target.
10//!
11//! ```
12//! use urly::Url;
13//!
14//! let url = Url::from_static("https://example.com/api/v1?page=2");
15//! assert_eq!(url.host(), Some("example.com"));
16//! assert_eq!(url.port_or_known_default(), Some(443));
17//!
18//! let users = &url / "users" / "john doe";
19//! assert_eq!(users, "https://example.com/api/v1/users/john%20doe");
20//! assert_eq!(users.path().segments().last().unwrap(), "john%20doe");
21//!
22//! let mut url = users.join("../groups?id=1").unwrap();
23//! url.extend_query_pairs([("sort", "name asc")]);
24//! assert_eq!(url, "https://example.com/api/v1/groups?id=1&sort=name+asc");
25//!
26//! let url = Url::builder()
27//!     .scheme("http")
28//!     .host("münchen.de")
29//!     .path("/a b")
30//!     .query_pair("q", "x&y")
31//!     .build()
32//!     .unwrap();
33//! assert_eq!(url, "http://xn--mnchen-3ya.de/a%20b?q=x%26y");
34//! ```
35//!
36//! # Features
37//!
38//! * `http` - conversions between [`Url`] and `http::Uri`
39//! * `serde` - `Serialize` and `Deserialize` for [`Url`]
40#![deny(missing_docs)]
41
42macro_rules! str_type {
43    ($name:ident) => {
44        impl $name {
45            #[allow(dead_code)]
46            pub(crate) const fn from_str_unchecked(s: &str) -> &$name {
47                // SAFETY: the type is a `repr(transparent)` wrapper around `str`
48                unsafe { &*(s as *const str as *const $name) }
49            }
50
51            /// Returns the component as a string slice.
52            pub const fn as_str(&self) -> &str {
53                &self.0
54            }
55        }
56
57        impl<'a> TryFrom<&'a str> for &'a $name {
58            type Error = $crate::InvalidUrl;
59
60            fn try_from(s: &'a str) -> Result<Self, Self::Error> {
61                $name::new(s)
62            }
63        }
64
65        str_fmt!($name);
66    };
67}
68
69/// `AsRef<str>`, `Display` and `Debug` via `as_str()`.
70macro_rules! str_fmt {
71    ($name:ident) => {
72        impl AsRef<str> for $name {
73            fn as_ref(&self) -> &str {
74                self.as_str()
75            }
76        }
77
78        impl std::fmt::Display for $name {
79            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80                f.write_str(self.as_str())
81            }
82        }
83
84        impl std::fmt::Debug for $name {
85            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86                std::fmt::Debug::fmt(self.as_str(), f)
87            }
88        }
89    };
90}
91
92/// Comparison and hashing via `as_str()`.
93macro_rules! str_eq {
94    ($name:ident) => {
95        impl PartialEq for $name {
96            fn eq(&self, other: &$name) -> bool {
97                self.as_str() == other.as_str()
98            }
99        }
100
101        impl Eq for $name {}
102
103        impl PartialEq<str> for $name {
104            fn eq(&self, other: &str) -> bool {
105                self.as_str() == other
106            }
107        }
108
109        impl PartialEq<&str> for $name {
110            fn eq(&self, other: &&str) -> bool {
111                self.as_str() == *other
112            }
113        }
114
115        impl PartialEq<$name> for str {
116            fn eq(&self, other: &$name) -> bool {
117                self == other.as_str()
118            }
119        }
120
121        impl PartialEq<$name> for &str {
122            fn eq(&self, other: &$name) -> bool {
123                *self == other.as_str()
124            }
125        }
126
127        impl std::hash::Hash for $name {
128            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
129                self.as_str().hash(state)
130            }
131        }
132
133        impl PartialOrd for $name {
134            fn partial_cmp(&self, other: &$name) -> Option<std::cmp::Ordering> {
135                Some(self.cmp(other))
136            }
137        }
138
139        impl Ord for $name {
140            fn cmp(&self, other: &$name) -> std::cmp::Ordering {
141                self.as_str().cmp(other.as_str())
142            }
143        }
144    };
145}
146
147mod authority;
148mod builder;
149mod chars;
150mod error;
151mod host;
152mod idna;
153mod parse;
154mod path;
155mod query;
156pub mod quoting;
157mod scheme;
158mod url;
159
160pub use crate::authority::{Authority, Port, UserInfo};
161pub use crate::builder::{Builder, Parts};
162pub use crate::error::{ErrorKind, InvalidUrl, InvalidUrlParts};
163pub use crate::host::Host;
164pub use crate::path::{Path, PathAndQuery, Segments};
165pub use crate::query::{Fragment, Query, QueryPairs};
166pub use crate::scheme::Scheme;
167pub use crate::url::Url;
168
169#[cfg(doctest)]
170#[doc = include_str!("../README.md")]
171struct ReadmeDoctests;