Skip to main content

better_url/url/
mod.rs

1//! [`BetterUrl`].
2
3use crate::prelude::*;
4
5mod new;
6mod join;
7
8mod canon;
9mod scheme;
10mod userinfo;
11mod host;
12mod port;
13mod path;
14mod query;
15mod fragment;
16
17/// A URL.
18///
19/// # Size
20///
21/// By using [`UrlString`] and [`DenseUrlDetails`] instead of [`String`] and [`UrlDetails`], [`BetterUrl`] takes, on 64 bit targets, just 64 bytes of stack space.
22///
23/// On 32 bit systems it takes even less but who cares.
24///
25/// ```
26/// use better_url::prelude::*;
27///
28/// assert!(std::mem::size_of::<BetterUrl>() <= 64);
29/// ```
30///
31/// # Canon APIs
32///
33/// The [URL spec](https://url.spec.whatwg.org/) specifies a number of APIs that do specific additional things that the normal type based APIs provided by this crate don't.
34///
35/// Primarily, this involves getters doing stupid things to avoid ever returning [`None`] and setters doing pointless pre-processing to compensate for javascript being awful.
36///
37/// Generally, you should stick to the non-canon APIs since they're just better, but if you need them the canon APIs are provided.
38///
39/// For example:
40///
41/// ```
42/// use better_url::prelude::*;
43///
44/// let mut x = BetterUrl::new("https://example.com/abc").unwrap();
45/// x.canon_set_hostname("example\t2.net/def").unwrap();
46/// assert_eq!(x, "https://example2.net/abc");
47///
48/// let mut x = BetterUrl::new("https://example.com/abc").unwrap();
49/// x.set_host("example\t3.net/def").unwrap_err();
50/// ```
51#[derive(Debug, Clone)]
52pub struct BetterUrl {
53    /** The serialization.       */ serialization: UrlString    ,
54    /** The [`DenseUrlDetails`]. */ details      : DenseUrlDetails,
55}
56
57impl BetterUrl {
58    /// Make a new [`Self`].
59    /// # Errors
60    /// If [`TryInto::try_into`] returns an error, that error is returned.
61    pub fn new<T: TryInto<Self>>(value: T) -> Result<Self, T::Error> {
62        value.try_into()
63    }
64
65    /// Make a new [`Self`] without doing any validity checks.
66    /// # Safety
67    /// `serialization` and `details` must be a valid output of [`Self::new`] and [`Self::into_parts`].
68    pub unsafe fn from_parts(serialization: UrlString, details: DenseUrlDetails) -> Self {
69        Self {serialization, details}
70    }
71
72    /// Turn into the inner [`String`] and [`DenseUrlDetails`].
73    pub fn into_parts(self) -> (UrlString, DenseUrlDetails) {
74        (self.serialization, self.details)
75    }
76
77    /// The [`DenseUrlDetails`].
78    pub fn details(&self) -> DenseUrlDetails {
79        self.details
80    }
81
82    /// The URL as a [`str`].
83    pub fn as_str(&self) -> &str {
84        &self.serialization
85    }
86
87    /// If it cannot be a base.
88    /// # Examples
89    /// ```
90    /// use better_url::prelude::*;
91    ///
92    /// assert!(!BetterUrl::new("https://example.com/").unwrap().cannot_be_a_base());
93    /// assert!(!BetterUrl::new("aaaaa://example.com/").unwrap().cannot_be_a_base());
94    /// assert!(!BetterUrl::new("aaaaa://example.com" ).unwrap().cannot_be_a_base());
95    /// assert!(!BetterUrl::new("aaaaa:/123"          ).unwrap().cannot_be_a_base());
96    /// assert!( BetterUrl::new("aaaaa:123"           ).unwrap().cannot_be_a_base());
97    /// assert!( BetterUrl::new("aaaaa:"              ).unwrap().cannot_be_a_base());
98    /// ```
99    pub fn cannot_be_a_base(&self) -> bool {
100        !self.has_host() && unsafe {!self.as_str().get_unchecked(self.details.path_start as usize ..).starts_with('/')}
101    }
102
103    /// If it can be a base.
104    /// # Examples
105    /// ```
106    /// use better_url::prelude::*;
107    ///
108    /// assert!( BetterUrl::new("https://example.com/").unwrap().can_be_a_base());
109    /// assert!( BetterUrl::new("aaaaa://example.com/").unwrap().can_be_a_base());
110    /// assert!( BetterUrl::new("aaaaa://example.com" ).unwrap().can_be_a_base());
111    /// assert!( BetterUrl::new("aaaaa:/123"          ).unwrap().can_be_a_base());
112    /// assert!(!BetterUrl::new("aaaaa:123"           ).unwrap().can_be_a_base());
113    /// assert!(!BetterUrl::new("aaaaa:"              ).unwrap().can_be_a_base());
114    /// ```
115    pub fn can_be_a_base(&self) -> bool {
116        self.has_host() || unsafe {self.as_str().get_unchecked(self.details.path_start as usize ..).starts_with('/')}
117    }
118
119    /// The length.
120    #[expect(clippy::len_without_is_empty, reason = "Can't be empty.")]
121    pub fn len(&self) -> usize {
122        self.serialization.len() as usize
123    }
124}
125
126
127
128impl TryFrom<Cow<'_, [u8]>> for BetterUrl {
129    type Error = InvalidUrl;
130
131    fn try_from(value: Cow<'_, [u8]>) -> Result<Self, Self::Error> {
132        Self::new_bytes(value)
133    }
134}
135
136impl FromStr for BetterUrl {
137    type Err = InvalidUrl;
138
139    fn from_str(s: &str) -> Result<Self, Self::Err> {
140        s.try_into()
141    }
142}
143
144impl                 TryFrom<Cow<'_, str>> for BetterUrl {type Error = InvalidUrl; fn try_from(value: Cow<'_, str>) -> Result<Self, Self::Error> {Self::new_str(value)}}
145impl                 TryFrom<&str        > for BetterUrl {type Error = InvalidUrl; fn try_from(value: &str        ) -> Result<Self, Self::Error> {Cow::Borrowed     (   value           ).try_into()}}
146impl                 TryFrom< String     > for BetterUrl {type Error = InvalidUrl; fn try_from(value: String      ) -> Result<Self, Self::Error> {Cow::<str>::Owned (   value           ).try_into()}}
147impl                 TryFrom<&String     > for BetterUrl {type Error = InvalidUrl; fn try_from(value: &String     ) -> Result<Self, Self::Error> {Cow::Borrowed     (&**value           ).try_into()}}
148impl                 TryFrom<&[u8   ]    > for BetterUrl {type Error = InvalidUrl; fn try_from(value: &[u8   ]    ) -> Result<Self, Self::Error> {Cow::Borrowed     (   value           ).try_into()}}
149impl<const N: usize> TryFrom<&[u8; N]    > for BetterUrl {type Error = InvalidUrl; fn try_from(value: &[u8; N]    ) -> Result<Self, Self::Error> {Cow::Borrowed     (   value.as_slice()).try_into()}}
150impl                 TryFrom< Vec<u8>    > for BetterUrl {type Error = InvalidUrl; fn try_from(value: Vec<u8>     ) -> Result<Self, Self::Error> {Cow::<[u8]>::Owned(   value           ).try_into()}}
151impl                 TryFrom<&Vec<u8>    > for BetterUrl {type Error = InvalidUrl; fn try_from(value: &Vec<u8>    ) -> Result<Self, Self::Error> {Cow::Borrowed     (&**value           ).try_into()}}
152
153
154
155impl From<BetterUrl> for String            {fn from(value: BetterUrl) -> Self {           value.serialization.into() }}
156impl From<BetterUrl> for Cow<'static, str> {fn from(value: BetterUrl) -> Self {Cow::Owned(value.serialization.into())}}
157
158impl AsRef <str> for BetterUrl {fn as_ref(&self) -> &str {self.as_str()}}
159impl Borrow<str> for BetterUrl {fn borrow(&self) -> &str {self.as_str()}}
160
161impl AsRef <UrlString> for BetterUrl {fn as_ref(&self) -> &UrlString {&self.serialization}}
162impl Borrow<UrlString> for BetterUrl {fn borrow(&self) -> &UrlString {&self.serialization}}
163
164
165
166impl PartialEq for BetterUrl {fn eq(&self, other: &Self) -> bool {self.as_str() == other.as_str()}}
167impl Eq for BetterUrl {}
168
169impl PartialEq< str         > for BetterUrl {fn eq(&self, other: & str         ) -> bool {self.as_str() ==  other}}
170impl PartialEq< String      > for BetterUrl {fn eq(&self, other: & String      ) -> bool {self.as_str() ==  other}}
171impl PartialEq< Cow<'_, str>> for BetterUrl {fn eq(&self, other: & Cow<'_, str>) -> bool {self.as_str() ==  other}}
172impl PartialEq<&str         > for BetterUrl {fn eq(&self, other: &&str         ) -> bool {self.as_str() == *other}}
173impl PartialEq<&String      > for BetterUrl {fn eq(&self, other: &&String      ) -> bool {self.as_str() == *other}}
174impl PartialEq<&Cow<'_, str>> for BetterUrl {fn eq(&self, other: &&Cow<'_, str>) -> bool {self.as_str() == *other}}
175
176impl PartialEq<BetterUrl> for  str          {fn eq(&self, other: &BetterUrl) -> bool {other == self}}
177impl PartialEq<BetterUrl> for  String       {fn eq(&self, other: &BetterUrl) -> bool {other == self}}
178impl PartialEq<BetterUrl> for  Cow<'_, str> {fn eq(&self, other: &BetterUrl) -> bool {other == self}}
179impl PartialEq<BetterUrl> for &str          {fn eq(&self, other: &BetterUrl) -> bool {other == self}}
180impl PartialEq<BetterUrl> for &String       {fn eq(&self, other: &BetterUrl) -> bool {other == self}}
181impl PartialEq<BetterUrl> for &Cow<'_, str> {fn eq(&self, other: &BetterUrl) -> bool {other == self}}
182
183
184
185impl PartialOrd for BetterUrl {fn partial_cmp(&self, other: &Self) -> Option<Ordering> {Some(self.cmp(other))}}
186impl Ord        for BetterUrl {fn cmp        (&self, other: &Self) ->        Ordering  {self.as_str().cmp(other.as_str())}}
187
188impl PartialOrd< str         > for BetterUrl {fn partial_cmp(&self, other: & str         ) -> Option<Ordering> {self.as_str().partial_cmp(    other)}}
189impl PartialOrd< String      > for BetterUrl {fn partial_cmp(&self, other: & String      ) -> Option<Ordering> {self.as_str().partial_cmp(& **other)}}
190impl PartialOrd< Cow<'_, str>> for BetterUrl {fn partial_cmp(&self, other: & Cow<'_, str>) -> Option<Ordering> {self.as_str().partial_cmp(& **other)}}
191impl PartialOrd<&str         > for BetterUrl {fn partial_cmp(&self, other: &&str         ) -> Option<Ordering> {self.as_str().partial_cmp(   *other)}}
192impl PartialOrd<&String      > for BetterUrl {fn partial_cmp(&self, other: &&String      ) -> Option<Ordering> {self.as_str().partial_cmp(&***other)}}
193impl PartialOrd<&Cow<'_, str>> for BetterUrl {fn partial_cmp(&self, other: &&Cow<'_, str>) -> Option<Ordering> {self.as_str().partial_cmp(&***other)}}
194
195impl PartialOrd<BetterUrl> for  str          {fn partial_cmp(&self, other: &BetterUrl    ) -> Option<Ordering> {other.partial_cmp(self)}}
196impl PartialOrd<BetterUrl> for  String       {fn partial_cmp(&self, other: &BetterUrl    ) -> Option<Ordering> {other.partial_cmp(self)}}
197impl PartialOrd<BetterUrl> for  Cow<'_, str> {fn partial_cmp(&self, other: &BetterUrl    ) -> Option<Ordering> {other.partial_cmp(self)}}
198impl PartialOrd<BetterUrl> for &str          {fn partial_cmp(&self, other: &BetterUrl    ) -> Option<Ordering> {other.partial_cmp(self)}}
199impl PartialOrd<BetterUrl> for &String       {fn partial_cmp(&self, other: &BetterUrl    ) -> Option<Ordering> {other.partial_cmp(self)}}
200impl PartialOrd<BetterUrl> for &Cow<'_, str> {fn partial_cmp(&self, other: &BetterUrl    ) -> Option<Ordering> {other.partial_cmp(self)}}
201
202
203
204impl Hash for BetterUrl {
205    fn hash<H: Hasher>(&self, hasher: &mut H) {
206        self.as_str().hash(hasher)
207    }
208}
209
210impl std::fmt::Display for BetterUrl {
211    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212        write!(formatter, "{}", self.as_str())
213    }
214}
215
216#[cfg(feature = "serde")]
217impl Serialize for BetterUrl {
218    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
219        self.as_str().serialize(serializer)
220    }
221}
222
223#[cfg(any(feature = "serde", test))]
224impl<'de> Deserialize<'de> for BetterUrl {
225    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
226        Self::new(<Cow<'de, str>>::deserialize(deserializer)?).map_err(D::Error::custom)
227    }
228}