Skip to main content

better_url/util/
url_string.rs

1//! [`UrlString`].
2
3use std::ptr::NonNull;
4use std::mem::ManuallyDrop;
5
6use crate::prelude::*;
7
8/// A [`String`] with a length and capacity defined as [`u32`]s, saving a total 8 bytes on 64 bit systems.
9///
10/// Used in [`BetterUrl`] since URLs can never be longer than 4GiB.
11/// # Examples
12/// ```
13/// use better_url::util::*;
14///
15/// assert!(std::mem::size_of::<UrlString>() <= 16);
16/// ```
17pub struct UrlString {
18    /// The data.
19    ptr: NonNull<u8>,
20    /// The length.
21    len: u32,
22    /// The capacity.
23    cap: u32,
24}
25
26impl UrlString {
27    /// Make a new [`UrlString`].
28    /// # Safety
29    /// The [`String`] must have a capacity below [`u32::MAX`].
30    pub unsafe fn new_unchecked(value: String) -> Self {
31        let (ptr, len, cap) = value.into_raw_parts();
32
33        unsafe {
34            Self {
35                ptr: NonNull::new_unchecked(ptr),
36                len: len.try_into().unwrap_unchecked(),
37                cap: cap.try_into().unwrap_unchecked(),
38            }
39        }
40    }
41
42    /// Make a temporary [`String`] to modify.
43    ///
44    /// `f` is allowed to reallocate and even grow beyond [`u32::MAX`], as long at the end the capacity isn't above [`u32::MAX`].
45    ///
46    /// Additionally, `f` is, I think, allowed to panic.
47    /// # Safety
48    /// The [`String`] must not end up with a capacity above [`u32::MAX`].
49    pub unsafe fn modify<F: FnOnce(&mut String)>(&mut self, f: F) {
50        let mut temp = ManuallyDrop::new(unsafe {String::from_raw_parts(self.ptr.as_ptr(), self.len as _, self.cap as _)});
51
52        f(&mut temp);
53
54        let (ptr, len, cap) = ManuallyDrop::into_inner(temp).into_raw_parts();
55
56        unsafe {
57            self.ptr = NonNull::new_unchecked(ptr);
58            self.len = len.try_into().unwrap_unchecked();
59            self.cap = cap.try_into().unwrap_unchecked();
60        }
61    }
62
63    /// Borrow as a [`str`].
64    pub fn as_str(&self) -> &str {
65        unsafe {
66            str::from_utf8_unchecked(self.as_bytes())
67        }
68    }
69
70    /// Borrow as a mutable [`str`].
71    pub fn as_mut_str(&mut self) -> &mut str {
72        unsafe {
73            str::from_utf8_unchecked_mut(self.as_bytes_mut())
74        }
75    }
76
77    /// Borrow as a [`slice`] of [`u8`].
78    pub fn as_bytes(&self) -> &[u8] {
79        unsafe {
80            std::slice::from_raw_parts(self.ptr.as_ptr(), self.len as _)
81        }
82    }
83
84    /// Borrow as a mutable [`slice`] of [`u8`].
85    /// # Safety
86    /// The [`slice`] must be valid UTF-8 at the end.
87    pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
88        unsafe {
89            std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len as _)
90        }
91    }
92
93    /// The length.
94    pub fn len(&self) -> u32 {
95        self.len
96    }
97
98    /// If it's empty.
99    pub fn is_empty(&self) -> bool {
100        self.len == 0
101    }
102
103    /// The capacity.
104    pub fn capacity(&self) -> u32 {
105        self.cap
106    }
107}
108
109
110
111impl From<UrlString> for String {
112    fn from(value: UrlString) -> Self {
113        let ret = unsafe {String::from_raw_parts(value.ptr.as_ptr(), value.len as _, value.cap as _)};
114        std::mem::forget(value);
115        ret
116    }
117}
118
119impl TryFrom<String> for UrlString {
120    type Error = String;
121
122    fn try_from(value: String) -> Result<Self, Self::Error> {
123        if value.capacity() > u32::MAX as usize {
124            Err(value)
125        } else {
126            Ok(unsafe {
127                Self::new_unchecked(value)
128            })
129        }
130    }
131}
132
133impl std::ops::Drop for UrlString {
134    fn drop(&mut self) {
135        unsafe {String::from_raw_parts(self.ptr.as_ptr(), self.len as _, self.cap as _)};
136    }
137}
138
139
140
141unsafe impl Send for UrlString {}
142unsafe impl Sync for UrlString {}
143
144
145
146impl std::fmt::Debug for UrlString {
147    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
148        write!(formatter, "{:?}", self.as_str())
149    }
150}
151
152impl std::fmt::Display for UrlString {
153    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
154        formatter.write_str(self.as_str())
155    }
156}
157
158impl Clone for UrlString {
159    fn clone(&self) -> Self {
160        unsafe {
161            let temp = ManuallyDrop::new(String::from_raw_parts(self.ptr.as_ptr(), self.len as _, self.cap as _));
162            let ret = temp.clone();
163            Self::new_unchecked(ManuallyDrop::into_inner(ret))
164        }
165    }
166}
167
168
169
170impl std::ops::Deref for UrlString {
171    type Target = str;
172
173    fn deref(&self) -> &Self::Target {
174        self.as_str()
175    }
176}
177
178impl std::ops::DerefMut for UrlString {
179    fn deref_mut(&mut self) -> &mut Self::Target {
180        self.as_mut_str()
181    }
182}
183
184impl AsRef    <str> for UrlString {fn as_ref    (&    self) -> &    str {self}}
185impl Borrow   <str> for UrlString {fn borrow    (&    self) -> &    str {self}}
186impl AsMut    <str> for UrlString {fn as_mut    (&mut self) -> &mut str {self}}
187impl BorrowMut<str> for UrlString {fn borrow_mut(&mut self) -> &mut str {self}}
188
189
190
191impl PartialEq for UrlString {fn eq(&self, other: &Self) -> bool {self.as_str() == other.as_str()}}
192impl Eq for UrlString {}
193
194impl PartialEq< str         > for UrlString {fn eq(&self, other: & str         ) -> bool {self.as_str() ==     other}}
195impl PartialEq<&str         > for UrlString {fn eq(&self, other: &&str         ) -> bool {self.as_str() ==    *other}}
196impl PartialEq< String      > for UrlString {fn eq(&self, other: & String      ) -> bool {self.as_str() == & **other}}
197impl PartialEq<&String      > for UrlString {fn eq(&self, other: &&String      ) -> bool {self.as_str() == &***other}}
198impl PartialEq< Cow<'_, str>> for UrlString {fn eq(&self, other: & Cow<'_, str>) -> bool {self.as_str() == & **other}}
199impl PartialEq<&Cow<'_, str>> for UrlString {fn eq(&self, other: &&Cow<'_, str>) -> bool {self.as_str() == &***other}}
200
201impl PartialEq<UrlString> for  str          {fn eq(&self, other: &UrlString) -> bool {other == self}}
202impl PartialEq<UrlString> for &str          {fn eq(&self, other: &UrlString) -> bool {other == self}}
203impl PartialEq<UrlString> for  String       {fn eq(&self, other: &UrlString) -> bool {other == self}}
204impl PartialEq<UrlString> for &String       {fn eq(&self, other: &UrlString) -> bool {other == self}}
205impl PartialEq<UrlString> for  Cow<'_, str> {fn eq(&self, other: &UrlString) -> bool {other == self}}
206impl PartialEq<UrlString> for &Cow<'_, str> {fn eq(&self, other: &UrlString) -> bool {other == self}}
207
208
209
210impl PartialOrd for UrlString {fn partial_cmp(&self, other: &Self) -> Option<Ordering> {Some(self.cmp(other))}}
211impl Ord for UrlString {fn cmp(&self, other: &Self) -> Ordering {self.as_str().cmp(other.as_str())}}
212
213impl PartialOrd< str         > for UrlString {fn partial_cmp(&self, other: & str         ) -> Option<Ordering> {self.as_str().partial_cmp(    other)}}
214impl PartialOrd<&str         > for UrlString {fn partial_cmp(&self, other: &&str         ) -> Option<Ordering> {self.as_str().partial_cmp(   *other)}}
215impl PartialOrd< String      > for UrlString {fn partial_cmp(&self, other: & String      ) -> Option<Ordering> {self.as_str().partial_cmp(& **other)}}
216impl PartialOrd<&String      > for UrlString {fn partial_cmp(&self, other: &&String      ) -> Option<Ordering> {self.as_str().partial_cmp(&***other)}}
217impl PartialOrd< Cow<'_, str>> for UrlString {fn partial_cmp(&self, other: & Cow<'_, str>) -> Option<Ordering> {self.as_str().partial_cmp(& **other)}}
218impl PartialOrd<&Cow<'_, str>> for UrlString {fn partial_cmp(&self, other: &&Cow<'_, str>) -> Option<Ordering> {self.as_str().partial_cmp(&***other)}}
219
220impl PartialOrd<UrlString> for  str          {fn partial_cmp(&self, other: &UrlString) -> Option<Ordering> {other.partial_cmp(self)}}
221impl PartialOrd<UrlString> for &str          {fn partial_cmp(&self, other: &UrlString) -> Option<Ordering> {other.partial_cmp(self)}}
222impl PartialOrd<UrlString> for  String       {fn partial_cmp(&self, other: &UrlString) -> Option<Ordering> {other.partial_cmp(self)}}
223impl PartialOrd<UrlString> for &String       {fn partial_cmp(&self, other: &UrlString) -> Option<Ordering> {other.partial_cmp(self)}}
224impl PartialOrd<UrlString> for  Cow<'_, str> {fn partial_cmp(&self, other: &UrlString) -> Option<Ordering> {other.partial_cmp(self)}}
225impl PartialOrd<UrlString> for &Cow<'_, str> {fn partial_cmp(&self, other: &UrlString) -> Option<Ordering> {other.partial_cmp(self)}}
226
227
228
229impl Hash for UrlString {
230    fn hash<H: Hasher>(&self, hasher: &mut H) {
231        self.as_str().hash(hasher)
232    }
233}