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            #[inline]
47            pub(crate) const fn from_str_unchecked(s: &str) -> &$name {
48                // SAFETY: the type is a `repr(transparent)` wrapper around `str`
49                unsafe { &*(s as *const str as *const $name) }
50            }
51
52            /// Returns the component as a string slice.
53            #[inline]
54            pub const fn as_str(&self) -> &str {
55                &self.0
56            }
57        }
58
59        impl<'a> TryFrom<&'a str> for &'a $name {
60            type Error = $crate::InvalidUrl;
61
62            fn try_from(s: &'a str) -> Result<Self, Self::Error> {
63                $name::new(s)
64            }
65        }
66
67        str_fmt!($name);
68    };
69}
70
71/// `AsRef<str>`, `Display` and `Debug` via `as_str()`.
72macro_rules! str_fmt {
73    ($name:ident) => {
74        impl AsRef<str> for $name {
75            #[inline]
76            fn as_ref(&self) -> &str {
77                self.as_str()
78            }
79        }
80
81        impl std::fmt::Display for $name {
82            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83                f.write_str(self.as_str())
84            }
85        }
86
87        impl std::fmt::Debug for $name {
88            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89                std::fmt::Debug::fmt(self.as_str(), f)
90            }
91        }
92    };
93}
94
95/// Comparison and hashing via `as_str()`.
96macro_rules! str_eq {
97    ($name:ident) => {
98        impl PartialEq for $name {
99            #[inline]
100            fn eq(&self, other: &$name) -> bool {
101                self.as_str() == other.as_str()
102            }
103        }
104
105        impl Eq for $name {}
106
107        impl PartialEq<str> for $name {
108            #[inline]
109            fn eq(&self, other: &str) -> bool {
110                self.as_str() == other
111            }
112        }
113
114        impl PartialEq<&str> for $name {
115            #[inline]
116            fn eq(&self, other: &&str) -> bool {
117                self.as_str() == *other
118            }
119        }
120
121        impl PartialEq<$name> for str {
122            #[inline]
123            fn eq(&self, other: &$name) -> bool {
124                self == other.as_str()
125            }
126        }
127
128        impl PartialEq<$name> for &str {
129            #[inline]
130            fn eq(&self, other: &$name) -> bool {
131                *self == other.as_str()
132            }
133        }
134
135        impl std::hash::Hash for $name {
136            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
137                self.as_str().hash(state)
138            }
139        }
140
141        impl PartialOrd for $name {
142            fn partial_cmp(&self, other: &$name) -> Option<std::cmp::Ordering> {
143                Some(self.cmp(other))
144            }
145        }
146
147        impl Ord for $name {
148            fn cmp(&self, other: &$name) -> std::cmp::Ordering {
149                self.as_str().cmp(other.as_str())
150            }
151        }
152    };
153}
154
155mod authority;
156mod builder;
157mod chars;
158mod error;
159mod host;
160mod idna;
161mod parse;
162mod path;
163mod query;
164pub mod quoting;
165mod scheme;
166mod url;
167
168pub use crate::authority::{Authority, Port, UserInfo};
169pub use crate::builder::{Builder, Parts};
170pub use crate::error::{ErrorKind, InvalidUrl, InvalidUrlParts};
171pub use crate::host::Host;
172pub use crate::path::{Path, PathAndQuery, Segments};
173pub use crate::query::{Fragment, Query, QueryPairs};
174pub use crate::scheme::Scheme;
175pub use crate::url::Url;
176
177#[cfg(doctest)]
178#[doc = include_str!("../README.md")]
179struct ReadmeDoctests;