iri_string/percent_encode.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
//! Percent encoding.
use core::fmt::{self, Write as _};
use core::marker::PhantomData;
use crate::parser::char;
use crate::spec::{IriSpec, Spec, UriSpec};
/// A proxy to percent-encode a string as a part of URI.
pub type PercentEncodedForUri<T> = PercentEncoded<T, UriSpec>;
/// A proxy to percent-encode a string as a part of IRI.
pub type PercentEncodedForIri<T> = PercentEncoded<T, IriSpec>;
/// Context for percent encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
enum Context {
/// Encode the string as a reg-name (usually called as "hostname").
RegName,
/// Encode the string as a user name or a password (inside the `userinfo` component).
UserOrPassword,
/// Encode the string as a path segment.
///
/// A slash (`/`) will be encoded to `%2F`.
PathSegment,
/// Encode the string as path segments joined with `/`.
///
/// A slash (`/`) will be used as is.
Path,
/// Encode the string as a query string (without the `?` prefix).
Query,
/// Encode the string as a fragment string (without the `#` prefix).
Fragment,
/// Encode all characters except for `unreserved` characters.
Unreserve,
/// Encode characters only if they cannot appear anywhere in an IRI reference.
///
/// `%` character will be always encoded.
Character,
}
/// A proxy to percent-encode a string.
///
/// Type aliases [`PercentEncodedForIri`] and [`PercentEncodedForUri`] are provided.
/// You can use them to make the expression simpler, for example write
/// `PercentEncodedForUri::from_path(foo)` instead of
/// `PercentEncoded::<_, UriSpec>::from_path(foo)`.
#[derive(Debug, Clone, Copy)]
pub struct PercentEncoded<T, S> {
/// Source string context.
context: Context,
/// Raw string before being encoded.
raw: T,
/// Spec.
_spec: PhantomData<fn() -> S>,
}
impl<T: fmt::Display, S: Spec> PercentEncoded<T, S> {
/// Creates an encoded string from a raw reg-name (i.e. hostname or domain).
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "alpha.\u{03B1}.example.com";
/// let encoded = "alpha.%CE%B1.example.com";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_reg_name(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_reg_name(raw: T) -> Self {
Self {
context: Context::RegName,
raw,
_spec: PhantomData,
}
}
/// Creates an encoded string from a raw user name (inside `userinfo` component).
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "user:\u{03B1}";
/// // The first `:` will be interpreted as a delimiter, so colons will be escaped.
/// let encoded = "user%3A%CE%B1";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_user(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_user(raw: T) -> Self {
Self {
context: Context::UserOrPassword,
raw,
_spec: PhantomData,
}
}
/// Creates an encoded string from a raw user name (inside `userinfo` component).
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "password:\u{03B1}";
/// // The first `:` will be interpreted as a delimiter, and the colon
/// // inside the password will be the first one if the user name is empty,
/// // so colons will be escaped.
/// let encoded = "password%3A%CE%B1";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_password(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_password(raw: T) -> Self {
Self {
context: Context::UserOrPassword,
raw,
_spec: PhantomData,
}
}
/// Creates an encoded string from a raw path segment.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "alpha/\u{03B1}?#";
/// // Note that `/` is encoded to `%2F`.
/// let encoded = "alpha%2F%CE%B1%3F%23";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_path_segment(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_path_segment(raw: T) -> Self {
Self {
context: Context::PathSegment,
raw,
_spec: PhantomData,
}
}
/// Creates an encoded string from a raw path.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "alpha/\u{03B1}?#";
/// // Note that `/` is NOT percent encoded.
/// let encoded = "alpha/%CE%B1%3F%23";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_path(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_path(raw: T) -> Self {
Self {
context: Context::Path,
raw,
_spec: PhantomData,
}
}
/// Creates an encoded string from a raw query.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "alpha/\u{03B1}?#";
/// let encoded = "alpha/%CE%B1?%23";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_query(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_query(raw: T) -> Self {
Self {
context: Context::Query,
raw,
_spec: PhantomData,
}
}
/// Creates an encoded string from a raw fragment.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let raw = "alpha/\u{03B1}?#";
/// let encoded = "alpha/%CE%B1?%23";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::from_fragment(raw).to_string(),
/// encoded
/// );
/// # }
/// ```
pub fn from_fragment(raw: T) -> Self {
Self {
context: Context::Fragment,
raw,
_spec: PhantomData,
}
}
/// Creates a string consists of only `unreserved` string and percent-encoded triplets.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let unreserved = "%a0-._~\u{03B1}";
/// let unreserved_encoded = "%25a0-._~%CE%B1";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::unreserve(unreserved).to_string(),
/// unreserved_encoded
/// );
///
/// let reserved = ":/?#[]@ !$&'()*+,;=";
/// let reserved_encoded =
/// "%3A%2F%3F%23%5B%5D%40%20%21%24%26%27%28%29%2A%2B%2C%3B%3D";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::unreserve(reserved).to_string(),
/// reserved_encoded
/// );
/// # }
/// ```
#[inline]
#[must_use]
pub fn unreserve(raw: T) -> Self {
Self {
context: Context::Unreserve,
raw,
_spec: PhantomData,
}
}
/// Percent-encodes characters only if they cannot appear anywhere in an IRI reference.
///
/// `%` character will be always encoded. In other words, this conversion
/// is not aware of percent-encoded triplets.
///
/// Note that this encoding process does not guarantee that the resulting
/// string is a valid IRI reference.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use iri_string::percent_encode::PercentEncoded;
/// use iri_string::spec::UriSpec;
///
/// let unreserved = "%a0-._~\u{03B1}";
/// let unreserved_encoded = "%25a0-._~%CE%B1";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::characters(unreserved).to_string(),
/// unreserved_encoded
/// );
///
/// let reserved = ":/?#[]@ !$&'()*+,;=";
/// // Note that `%20` cannot appear directly in an IRI reference.
/// let expected = ":/?#[]@%20!$&'()*+,;=";
/// assert_eq!(
/// PercentEncoded::<_, UriSpec>::characters(reserved).to_string(),
/// expected
/// );
/// # }
/// ```
#[inline]
#[must_use]
pub fn characters(raw: T) -> Self {
Self {
context: Context::Character,
raw,
_spec: PhantomData,
}
}
}
impl<T: fmt::Display, S: Spec> fmt::Display for PercentEncoded<T, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// Filter that encodes a character before written if necessary.
struct Filter<'a, 'b, S> {
/// Encoding context.
context: Context,
/// Writer.
writer: &'a mut fmt::Formatter<'b>,
/// Spec.
_spec: PhantomData<fn() -> S>,
}
impl<S: Spec> fmt::Write for Filter<'_, '_, S> {
fn write_str(&mut self, s: &str) -> fmt::Result {
s.chars().try_for_each(|c| self.write_char(c))
}
fn write_char(&mut self, c: char) -> fmt::Result {
let is_valid_char = match (self.context, c.is_ascii()) {
(Context::RegName, true) => char::is_ascii_regname(c as u8),
(Context::RegName, false) => char::is_nonascii_regname::<S>(c),
(Context::UserOrPassword, true) => {
c != ':' && char::is_ascii_userinfo_ipvfutureaddr(c as u8)
}
(Context::UserOrPassword, false) => char::is_nonascii_userinfo::<S>(c),
(Context::PathSegment, true) => char::is_ascii_pchar(c as u8),
(Context::PathSegment, false) => S::is_nonascii_char_unreserved(c),
(Context::Path, true) => c == '/' || char::is_ascii_pchar(c as u8),
(Context::Path, false) => S::is_nonascii_char_unreserved(c),
(Context::Query, true) => c == '/' || char::is_ascii_frag_query(c as u8),
(Context::Query, false) => char::is_nonascii_query::<S>(c),
(Context::Fragment, true) => c == '/' || char::is_ascii_frag_query(c as u8),
(Context::Fragment, false) => char::is_nonascii_fragment::<S>(c),
(Context::Unreserve, true) => char::is_ascii_unreserved(c as u8),
(Context::Unreserve, false) => S::is_nonascii_char_unreserved(c),
(Context::Character, true) => char::is_ascii_unreserved_or_reserved(c as u8),
(Context::Character, false) => {
S::is_nonascii_char_unreserved(c) || S::is_nonascii_char_private(c)
}
};
if is_valid_char {
self.writer.write_char(c)
} else {
write_pct_encoded_char(&mut self.writer, c)
}
}
}
let mut filter = Filter {
context: self.context,
writer: f,
_spec: PhantomData::<fn() -> S>,
};
write!(filter, "{}", self.raw)
}
}
/// Percent-encodes the given character and writes it.
#[inline]
fn write_pct_encoded_char<W: fmt::Write>(writer: &mut W, c: char) -> fmt::Result {
let mut buf = [0_u8; 4];
let buf = c.encode_utf8(&mut buf);
buf.bytes().try_for_each(|b| write!(writer, "%{:02X}", b))
}