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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
use std::hash::Hash;
use std::borrow::Cow;
use state::InitCell;
use crate::{RawStr, ext::IntoOwned};
use crate::uri::Segments;
use crate::uri::fmt::{self, Part};
use crate::parse::{IndexedStr, Extent};
// INTERNAL DATA STRUCTURE.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct Data<'a, P: Part> {
pub(crate) value: IndexedStr<'a>,
pub(crate) decoded_segments: InitCell<Vec<P::Raw>>,
}
impl<'a, P: Part> Data<'a, P> {
pub(crate) fn raw(value: Extent<&'a [u8]>) -> Self {
Data { value: value.into(), decoded_segments: InitCell::new() }
}
// INTERNAL METHOD.
#[doc(hidden)]
pub fn new<S: Into<Cow<'a, str>>>(value: S) -> Self {
Data {
value: IndexedStr::from(value.into()),
decoded_segments: InitCell::new(),
}
}
}
/// A URI path: `/foo/bar`, `foo/bar`, etc.
#[derive(Debug, Clone, Copy)]
pub struct Path<'a> {
pub(crate) source: &'a Option<Cow<'a, str>>,
pub(crate) data: &'a Data<'a, fmt::Path>,
}
/// A URI query: `?foo&bar`.
#[derive(Debug, Clone, Copy)]
pub struct Query<'a> {
pub(crate) source: &'a Option<Cow<'a, str>>,
pub(crate) data: &'a Data<'a, fmt::Query>,
}
fn decode_to_indexed_str<P: fmt::Part>(
value: &RawStr,
(indexed, source): (&IndexedStr<'_>, &RawStr)
) -> IndexedStr<'static> {
let decoded = match P::KIND {
fmt::Kind::Path => value.percent_decode_lossy(),
fmt::Kind::Query => value.url_decode_lossy(),
};
match decoded {
Cow::Borrowed(b) if indexed.is_indexed() => {
let checked = IndexedStr::checked_from(b, source.as_str());
debug_assert!(checked.is_some(), "\nunindexed {:?} in {:?} {:?}", b, indexed, source);
checked.unwrap_or_else(|| IndexedStr::from(Cow::Borrowed("")))
}
cow => IndexedStr::from(Cow::Owned(cow.into_owned())),
}
}
impl<'a> Path<'a> {
/// Returns the raw path value.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// let uri = uri!("/foo%20bar%2dbaz");
/// assert_eq!(uri.path(), "/foo%20bar%2dbaz");
/// assert_eq!(uri.path().raw(), "/foo%20bar%2dbaz");
/// ```
pub fn raw(&self) -> &'a RawStr {
self.data.value.from_cow_source(self.source).into()
}
/// Returns the raw, undecoded path value as an `&str`.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// let uri = uri!("/foo%20bar%2dbaz");
/// assert_eq!(uri.path(), "/foo%20bar%2dbaz");
/// assert_eq!(uri.path().as_str(), "/foo%20bar%2dbaz");
/// ```
pub fn as_str(&self) -> &'a str {
self.raw().as_str()
}
/// Whether `self` is normalized, i.e, it has no empty segments except the
/// last one.
///
/// If `absolute`, then a starting `/` is required.
pub(crate) fn is_normalized(&self, absolute: bool) -> bool {
if absolute && !self.raw().starts_with('/') {
return false;
}
self.raw_segments()
.rev()
.skip(1)
.all(|s| !s.is_empty())
}
/// Normalizes `self`. If `absolute`, a starting `/` is required. If
/// `trail`, a trailing slash is allowed. Otherwise it is not.
pub(crate) fn to_normalized(self, absolute: bool, trail: bool) -> Data<'static, fmt::Path> {
let raw = self.raw().trim();
let mut path = String::with_capacity(raw.len());
if absolute || raw.starts_with('/') {
path.push('/');
}
for (i, segment) in self.raw_segments().filter(|s| !s.is_empty()).enumerate() {
if i != 0 { path.push('/'); }
path.push_str(segment.as_str());
}
if trail && raw.len() > 1 && raw.ends_with('/') && !path.ends_with('/') {
path.push('/');
}
Data {
value: IndexedStr::from(Cow::Owned(path)),
decoded_segments: InitCell::new(),
}
}
/// Returns an iterator over the raw, undecoded segments, potentially empty
/// segments.
///
/// ### Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::http::uri::Origin;
///
/// let uri = Origin::parse("/").unwrap();
/// let segments: Vec<_> = uri.path().raw_segments().collect();
/// assert_eq!(segments, &[""]);
///
/// let uri = Origin::parse("//").unwrap();
/// let segments: Vec<_> = uri.path().raw_segments().collect();
/// assert_eq!(segments, &["", ""]);
///
/// let uri = Origin::parse("/foo").unwrap();
/// let segments: Vec<_> = uri.path().raw_segments().collect();
/// assert_eq!(segments, &["foo"]);
///
/// let uri = Origin::parse("/a/").unwrap();
/// let segments: Vec<_> = uri.path().raw_segments().collect();
/// assert_eq!(segments, &["a", ""]);
///
/// // Recall that `uri!()` normalizes static inputs.
/// let uri = uri!("//");
/// let segments: Vec<_> = uri.path().raw_segments().collect();
/// assert_eq!(segments, &[""]);
///
/// let uri = Origin::parse("/a//b///c/d?query¶m").unwrap();
/// let segments: Vec<_> = uri.path().raw_segments().collect();
/// assert_eq!(segments, &["a", "", "b", "", "", "c", "d"]);
/// ```
#[inline]
pub fn raw_segments(&self) -> impl DoubleEndedIterator<Item = &'a RawStr> {
let raw = self.raw().trim();
raw.strip_prefix(fmt::Path::DELIMITER)
.unwrap_or(raw)
.split(fmt::Path::DELIMITER)
}
/// Returns a (smart) iterator over the percent-decoded segments. Empty
/// segments between non-empty segments are skipped. A trailing slash will
/// result in an empty segment emitted as the final item.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::http::uri::Origin;
///
/// let uri = Origin::parse("/").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &[""]);
///
/// let uri = Origin::parse("/a").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &["a"]);
///
/// let uri = Origin::parse("/a/").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &["a", ""]);
///
/// let uri = Origin::parse("/foo/bar").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &["foo", "bar"]);
///
/// let uri = Origin::parse("/foo///bar").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &["foo", "bar"]);
///
/// let uri = Origin::parse("/foo///bar//").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &["foo", "bar", ""]);
///
/// let uri = Origin::parse("/a%20b/b%2Fc/d//e?query=some").unwrap();
/// let path_segs: Vec<&str> = uri.path().segments().collect();
/// assert_eq!(path_segs, &["a b", "b/c", "d", "e"]);
/// ```
pub fn segments(&self) -> Segments<'a, fmt::Path> {
let raw = self.raw();
let cached = self.data.decoded_segments.get_or_init(|| {
let mut segments = vec![];
let mut raw_segments = self.raw_segments().peekable();
while let Some(s) = raw_segments.next() {
// Only allow an empty segment if it's the last one.
if s.is_empty() && raw_segments.peek().is_some() {
continue;
}
segments.push(decode_to_indexed_str::<fmt::Path>(s, (&self.data.value, raw)));
}
segments
});
Segments::new(raw, cached)
}
}
impl<'a> Query<'a> {
/// Returns the raw, undecoded query value.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// let uri = uri!("/foo?baz+bar");
/// assert_eq!(uri.query().unwrap(), "baz+bar");
/// assert_eq!(uri.query().unwrap().raw(), "baz+bar");
/// ```
pub fn raw(&self) -> &'a RawStr {
self.data.value.from_cow_source(self.source).into()
}
/// Returns the raw, undecoded query value as an `&str`.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// let uri = uri!("/foo/bar?baz+bar");
/// assert_eq!(uri.query().unwrap(), "baz+bar");
/// assert_eq!(uri.query().unwrap().as_str(), "baz+bar");
/// ```
pub fn as_str(&self) -> &'a str {
self.raw().as_str()
}
/// Whether `self` is normalized, i.e, it has no empty segments.
pub(crate) fn is_normalized(&self) -> bool {
self.raw_segments().all(|s| !s.is_empty())
}
/// Normalizes `self`.
pub(crate) fn to_normalized(self) -> Data<'static, fmt::Query> {
let mut query = String::with_capacity(self.raw().trim().len());
for (i, seg) in self.raw_segments().filter(|s| !s.is_empty()).enumerate() {
if i != 0 { query.push('&'); }
query.push_str(seg.as_str());
}
Data {
value: IndexedStr::from(Cow::Owned(query)),
decoded_segments: InitCell::new(),
}
}
/// Returns an iterator over the undecoded, potentially empty `(name,
/// value)` pairs of this query. If there is no query, the iterator is
/// empty.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::http::uri::Origin;
///
/// let uri = Origin::parse("/").unwrap();
/// assert!(uri.query().is_none());
///
/// let uri = Origin::parse("/?").unwrap();
/// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
/// assert!(query_segs.is_empty());
///
/// let uri = Origin::parse("/?foo").unwrap();
/// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
/// assert_eq!(query_segs, &["foo"]);
///
/// let uri = Origin::parse("/?a=b&dog").unwrap();
/// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
/// assert_eq!(query_segs, &["a=b", "dog"]);
///
/// let uri = Origin::parse("/?&").unwrap();
/// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
/// assert_eq!(query_segs, &["", ""]);
///
/// // Recall that `uri!()` normalizes, so this is equivalent to `/?`.
/// let uri = uri!("/?&");
/// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
/// assert!(query_segs.is_empty());
///
/// // These are raw and undecoded. Use `segments()` for decoded variant.
/// let uri = Origin::parse("/foo/bar?a+b%2F=some+one%40gmail.com&&%26%3D2").unwrap();
/// let query_segs: Vec<_> = uri.query().unwrap().raw_segments().collect();
/// assert_eq!(query_segs, &["a+b%2F=some+one%40gmail.com", "", "%26%3D2"]);
/// ```
#[inline]
pub fn raw_segments(&self) -> impl Iterator<Item = &'a RawStr> {
let query = match self.raw().trim() {
q if q.is_empty() => None,
q => Some(q)
};
query.map(|p| p.split(fmt::Query::DELIMITER))
.into_iter()
.flatten()
}
/// Returns a (smart) iterator over the non-empty, url-decoded `(name,
/// value)` pairs of this query. If there is no query, the iterator is
/// empty.
///
/// # Example
///
/// ```rust
/// # #[macro_use] extern crate rocket;
/// use rocket::http::uri::Origin;
///
/// let uri = Origin::parse("/").unwrap();
/// assert!(uri.query().is_none());
///
/// let uri = Origin::parse("/foo/bar?a+b%2F=some+one%40gmail.com&&%26%3D2").unwrap();
/// let query_segs: Vec<_> = uri.query().unwrap().segments().collect();
/// assert_eq!(query_segs, &[("a b/", "some one@gmail.com"), ("&=2", "")]);
/// ```
pub fn segments(&self) -> Segments<'a, fmt::Query> {
let cached = self.data.decoded_segments.get_or_init(|| {
let (indexed, query) = (&self.data.value, self.raw());
self.raw_segments()
.filter(|s| !s.is_empty())
.map(|s| s.split_at_byte(b'='))
.map(|(k, v)| {
let key = decode_to_indexed_str::<fmt::Query>(k, (indexed, query));
let val = decode_to_indexed_str::<fmt::Query>(v, (indexed, query));
(key, val)
})
.collect()
});
Segments::new(self.raw(), cached)
}
}
macro_rules! impl_partial_eq {
($A:ty = $B:ty) => (
impl PartialEq<$A> for $B {
#[inline(always)]
fn eq(&self, other: &$A) -> bool {
let left: &RawStr = self.as_ref();
let right: &RawStr = other.as_ref();
left == right
}
}
)
}
macro_rules! impl_traits {
($T:ident) => (
impl Hash for $T<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.raw().hash(state);
}
}
impl Eq for $T<'_> { }
impl IntoOwned for Data<'_, fmt::$T> {
type Owned = Data<'static, fmt::$T>;
fn into_owned(self) -> Self::Owned {
Data {
value: self.value.into_owned(),
decoded_segments: self.decoded_segments.map(|v| v.into_owned()),
}
}
}
impl std::ops::Deref for $T<'_> {
type Target = RawStr;
fn deref(&self) -> &Self::Target {
self.raw()
}
}
impl AsRef<RawStr> for $T<'_> {
fn as_ref(&self) -> &RawStr {
self.raw()
}
}
impl AsRef<std::ffi::OsStr> for $T<'_> {
fn as_ref(&self) -> &std::ffi::OsStr {
self.raw().as_ref()
}
}
impl std::fmt::Display for $T<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.raw())
}
}
impl_partial_eq!($T<'_> = $T<'_>);
impl_partial_eq!(str = $T<'_>);
impl_partial_eq!(&str = $T<'_>);
impl_partial_eq!($T<'_> = str);
impl_partial_eq!($T<'_> = &str);
impl_partial_eq!(RawStr = $T<'_>);
impl_partial_eq!(&RawStr = $T<'_>);
impl_partial_eq!($T<'_> = RawStr);
impl_partial_eq!($T<'_> = &RawStr);
)
}
impl_traits!(Path);
impl_traits!(Query);