1use core::fmt;
4
5#[cfg(feature = "alloc")]
6use alloc::collections::TryReserveError;
7#[cfg(all(feature = "alloc", not(feature = "std")))]
8use alloc::string::String;
9
10#[cfg(feature = "alloc")]
11use crate::format::{ToDedicatedString, ToStringFallible};
12use crate::spec::Spec;
13use crate::types::{
14 RiAbsoluteStr, RiFragmentStr, RiQueryStr, RiReferenceStr, RiRelativeStr, RiStr,
15};
16#[cfg(feature = "alloc")]
17use crate::types::{
18 RiAbsoluteString, RiFragmentString, RiQueryString, RiReferenceString, RiRelativeString,
19 RiString,
20};
21
22const HEXDIGITS: [u8; 16] = *b"0123456789ABCDEF";
24
25#[derive(Debug, Clone, Copy)]
62pub struct MappedToUri<'a, Src: ?Sized>(&'a Src);
63
64macro_rules! impl_for_iri {
66 ($borrowed:ident, $owned:ident) => {
67 impl<S: Spec> fmt::Display for MappedToUri<'_, $borrowed<S>> {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 write_percent_encoded(f, self.0.as_str())
70 }
71 }
72
73 #[cfg(feature = "alloc")]
74 impl<S: Spec> ToDedicatedString for MappedToUri<'_, $borrowed<S>> {
75 type Target = $owned<$crate::spec::UriSpec>;
76
77 fn try_to_dedicated_string(&self) -> Result<Self::Target, TryReserveError> {
78 let s = self.try_to_string()?;
79 Ok(unsafe {
82 <Self::Target>::new_unchecked_justified(
83 s,
84 "an IRI must always be encodable into a valid URI",
85 )
86 })
87 }
88 }
89
90 impl<'a, S: Spec> From<&'a $borrowed<S>> for MappedToUri<'a, $borrowed<S>> {
91 #[inline]
92 fn from(iri: &'a $borrowed<S>) -> Self {
93 Self(iri)
94 }
95 }
96
97 #[cfg(feature = "alloc")]
98 impl<'a, S: Spec> From<&'a $owned<S>> for MappedToUri<'a, $borrowed<S>> {
99 #[inline]
100 fn from(iri: &'a $owned<S>) -> Self {
101 Self(iri.as_slice())
102 }
103 }
104 };
105}
106
107impl_for_iri!(RiReferenceStr, RiReferenceString);
108impl_for_iri!(RiStr, RiString);
109impl_for_iri!(RiAbsoluteStr, RiAbsoluteString);
110impl_for_iri!(RiRelativeStr, RiRelativeString);
111impl_for_iri!(RiQueryStr, RiQueryString);
112impl_for_iri!(RiFragmentStr, RiFragmentString);
113
114fn write_percent_encoded(f: &mut fmt::Formatter<'_>, mut s: &str) -> fmt::Result {
116 while !s.is_empty() {
117 let non_ascii_pos = s.bytes().position(|b| !b.is_ascii()).unwrap_or(s.len());
119 let (ascii, rest) = s.split_at(non_ascii_pos);
120 if !ascii.is_empty() {
121 f.write_str(ascii)?;
122 s = rest;
123 }
124
125 if s.is_empty() {
126 return Ok(());
127 }
128
129 let nonascii_end = s.bytes().position(|b| b.is_ascii()).unwrap_or(s.len());
131 let (nonasciis, rest) = s.split_at(nonascii_end);
132 debug_assert!(
133 !nonasciis.is_empty(),
134 "string without non-ASCII characters should have caused early return"
135 );
136 s = rest;
137
138 const NUM_BYTES_AT_ONCE: usize = 21;
146 percent_encode_bytes(f, nonasciis, &mut [0_u8; NUM_BYTES_AT_ONCE * 3])?;
147 }
148
149 Ok(())
150}
151
152fn percent_encode_bytes(f: &mut fmt::Formatter<'_>, s: &str, buf: &mut [u8]) -> fmt::Result {
161 fn fill_by_percent_encoded<'a>(buf: &'a mut [u8], bytes: &mut core::str::Bytes<'_>) -> &'a str {
173 let src_len = bytes.len();
174 for (dest, byte) in buf.chunks_exact_mut(3).zip(bytes.by_ref()) {
176 debug_assert_eq!(
177 dest.len(),
178 3,
179 "`chunks_exact()` must return a slice with the exact length"
180 );
181 debug_assert_eq!(
182 dest[0], b'%',
183 "[precondition] the buffer must be properly initialized"
184 );
185
186 let upper = byte >> 4;
187 let lower = byte & 0b1111;
188 dest[1] = HEXDIGITS[usize::from(upper)];
189 dest[2] = HEXDIGITS[usize::from(lower)];
190 }
191 let num_dest_written = (src_len - bytes.len()) * 3;
192 let buf_filled = &buf[..num_dest_written];
193 unsafe {
196 debug_assert!(core::str::from_utf8(buf_filled).is_ok());
197 core::str::from_utf8_unchecked(buf_filled)
198 }
199 }
200
201 assert!(
202 buf.len() >= 3,
203 "[precondition] length of `buf` must be 3 bytes or more"
204 );
205
206 let buf_len = buf.len() / 3 * 3;
209 let buf = &mut buf[..buf_len];
210
211 buf.fill(b'%');
215
216 let mut bytes = s.bytes();
217 while bytes.len() != 0 {
219 let encoded = fill_by_percent_encoded(buf, &mut bytes);
220 f.write_str(encoded)?;
221 }
222
223 Ok(())
224}
225
226#[cfg(feature = "alloc")]
228pub(crate) fn try_percent_encode_iri_inline(
229 iri: &mut String,
230) -> Result<(), alloc::collections::TryReserveError> {
231 let num_nonascii = count_nonascii(iri);
233 if num_nonascii == 0 {
234 return Ok(());
236 }
237 let additional = num_nonascii * 2;
238 iri.try_reserve(additional)?;
239 let src_len = iri.len();
240
241 let mut buf = core::mem::take(iri).into_bytes();
243 buf.extend(core::iter::repeat(b'\0').take(additional));
246
247 let mut dest_end = buf.len();
249 let mut src_end = src_len;
250 let mut rest_nonascii = num_nonascii;
251 while rest_nonascii > 0 {
252 debug_assert!(src_end > 0, "the source position should not overrun");
253 debug_assert!(dest_end > 0, "the destination position should not overrun");
254 src_end -= 1;
255 dest_end -= 1;
256 let byte = buf[src_end];
257 if byte.is_ascii() {
258 buf[dest_end] = byte;
259 } else {
261 dest_end -= 2;
263 buf[dest_end] = b'%';
264 let upper = byte >> 4;
265 let lower = byte & 0b1111;
266 buf[dest_end + 1] = HEXDIGITS[usize::from(upper)];
267 buf[dest_end + 2] = HEXDIGITS[usize::from(lower)];
268 rest_nonascii -= 1;
269 }
270 }
271
272 let s = String::from_utf8(buf).expect("the encoding result is an ASCII string");
274 *iri = s;
275 Ok(())
276}
277
278#[cfg(feature = "alloc")]
280#[inline]
281#[must_use]
282fn count_nonascii(s: &str) -> usize {
283 s.bytes().filter(|b| !b.is_ascii()).count()
284}