path_segments.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. // Copyright 2016 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. use parser::{self, SchemeType, to_u32};
  9. use std::str;
  10. use Url;
  11. /// Exposes methods to manipulate the path of an URL that is not cannot-be-base.
  12. ///
  13. /// The path always starts with a `/` slash, and is made of slash-separated segments.
  14. /// There is always at least one segment (which may be the empty string).
  15. ///
  16. /// Examples:
  17. ///
  18. /// ```rust
  19. /// use url::Url;
  20. /// # use std::error::Error;
  21. ///
  22. /// # fn run() -> Result<(), Box<Error>> {
  23. /// let mut url = Url::parse("mailto:me@example.com")?;
  24. /// assert!(url.path_segments_mut().is_err());
  25. ///
  26. /// let mut url = Url::parse("http://example.net/foo/index.html")?;
  27. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  28. /// .pop().push("img").push("2/100%.png");
  29. /// assert_eq!(url.as_str(), "http://example.net/foo/img/2%2F100%25.png");
  30. /// # Ok(())
  31. /// # }
  32. /// # run().unwrap();
  33. /// ```
  34. pub struct PathSegmentsMut<'a> {
  35. url: &'a mut Url,
  36. after_first_slash: usize,
  37. after_path: String,
  38. old_after_path_position: u32,
  39. }
  40. // Not re-exported outside the crate
  41. pub fn new(url: &mut Url) -> PathSegmentsMut {
  42. let after_path = url.take_after_path();
  43. let old_after_path_position = to_u32(url.serialization.len()).unwrap();
  44. debug_assert!(url.byte_at(url.path_start) == b'/');
  45. PathSegmentsMut {
  46. after_first_slash: url.path_start as usize + "/".len(),
  47. url: url,
  48. old_after_path_position: old_after_path_position,
  49. after_path: after_path,
  50. }
  51. }
  52. impl<'a> Drop for PathSegmentsMut<'a> {
  53. fn drop(&mut self) {
  54. self.url.restore_after_path(self.old_after_path_position, &self.after_path)
  55. }
  56. }
  57. impl<'a> PathSegmentsMut<'a> {
  58. /// Remove all segments in the path, leaving the minimal `url.path() == "/"`.
  59. ///
  60. /// Returns `&mut Self` so that method calls can be chained.
  61. ///
  62. /// Example:
  63. ///
  64. /// ```rust
  65. /// use url::Url;
  66. /// # use std::error::Error;
  67. ///
  68. /// # fn run() -> Result<(), Box<Error>> {
  69. /// let mut url = Url::parse("https://github.com/servo/rust-url/")?;
  70. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  71. /// .clear().push("logout");
  72. /// assert_eq!(url.as_str(), "https://github.com/logout");
  73. /// # Ok(())
  74. /// # }
  75. /// # run().unwrap();
  76. /// ```
  77. pub fn clear(&mut self) -> &mut Self {
  78. self.url.serialization.truncate(self.after_first_slash);
  79. self
  80. }
  81. /// Remove the last segment of this URL’s path if it is empty,
  82. /// except if these was only one segment to begin with.
  83. ///
  84. /// In other words, remove one path trailing slash, if any,
  85. /// unless it is also the initial slash (so this does nothing if `url.path() == "/")`.
  86. ///
  87. /// Returns `&mut Self` so that method calls can be chained.
  88. ///
  89. /// Example:
  90. ///
  91. /// ```rust
  92. /// use url::Url;
  93. /// # use std::error::Error;
  94. ///
  95. /// # fn run() -> Result<(), Box<Error>> {
  96. /// let mut url = Url::parse("https://github.com/servo/rust-url/")?;
  97. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  98. /// .push("pulls");
  99. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url//pulls");
  100. ///
  101. /// let mut url = Url::parse("https://github.com/servo/rust-url/")?;
  102. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  103. /// .pop_if_empty().push("pulls");
  104. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url/pulls");
  105. /// # Ok(())
  106. /// # }
  107. /// # run().unwrap();
  108. /// ```
  109. pub fn pop_if_empty(&mut self) -> &mut Self {
  110. if self.url.serialization[self.after_first_slash..].ends_with('/') {
  111. self.url.serialization.pop();
  112. }
  113. self
  114. }
  115. /// Remove the last segment of this URL’s path.
  116. ///
  117. /// If the path only has one segment, make it empty such that `url.path() == "/"`.
  118. ///
  119. /// Returns `&mut Self` so that method calls can be chained.
  120. pub fn pop(&mut self) -> &mut Self {
  121. let last_slash = self.url.serialization[self.after_first_slash..].rfind('/').unwrap_or(0);
  122. self.url.serialization.truncate(self.after_first_slash + last_slash);
  123. self
  124. }
  125. /// Append the given segment at the end of this URL’s path.
  126. ///
  127. /// See the documentation for `.extend()`.
  128. ///
  129. /// Returns `&mut Self` so that method calls can be chained.
  130. pub fn push(&mut self, segment: &str) -> &mut Self {
  131. self.extend(Some(segment))
  132. }
  133. /// Append each segment from the given iterator at the end of this URL’s path.
  134. ///
  135. /// Each segment is percent-encoded like in `Url::parse` or `Url::join`,
  136. /// except that `%` and `/` characters are also encoded (to `%25` and `%2F`).
  137. /// This is unlike `Url::parse` where `%` is left as-is in case some of the input
  138. /// is already percent-encoded, and `/` denotes a path segment separator.)
  139. ///
  140. /// Note that, in addition to slashes between new segments,
  141. /// this always adds a slash between the existing path and the new segments
  142. /// *except* if the existing path is `"/"`.
  143. /// If the previous last segment was empty (if the path had a trailing slash)
  144. /// the path after `.extend()` will contain two consecutive slashes.
  145. /// If that is undesired, call `.pop_if_empty()` first.
  146. ///
  147. /// To obtain a behavior similar to `Url::join`, call `.pop()` unconditionally first.
  148. ///
  149. /// Returns `&mut Self` so that method calls can be chained.
  150. ///
  151. /// Example:
  152. ///
  153. /// ```rust
  154. /// use url::Url;
  155. /// # use std::error::Error;
  156. ///
  157. /// # fn run() -> Result<(), Box<Error>> {
  158. /// let mut url = Url::parse("https://github.com/")?;
  159. /// let org = "servo";
  160. /// let repo = "rust-url";
  161. /// let issue_number = "188";
  162. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  163. /// .extend(&[org, repo, "issues", issue_number]);
  164. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url/issues/188");
  165. /// # Ok(())
  166. /// # }
  167. /// # run().unwrap();
  168. /// ```
  169. ///
  170. /// In order to make sure that parsing the serialization of an URL gives the same URL,
  171. /// a segment is ignored if it is `"."` or `".."`:
  172. ///
  173. /// ```rust
  174. /// use url::Url;
  175. /// # use std::error::Error;
  176. ///
  177. /// # fn run() -> Result<(), Box<Error>> {
  178. /// let mut url = Url::parse("https://github.com/servo")?;
  179. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  180. /// .extend(&["..", "rust-url", ".", "pulls"]);
  181. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url/pulls");
  182. /// # Ok(())
  183. /// # }
  184. /// # run().unwrap();
  185. /// ```
  186. pub fn extend<I>(&mut self, segments: I) -> &mut Self
  187. where I: IntoIterator, I::Item: AsRef<str> {
  188. let scheme_type = SchemeType::from(self.url.scheme());
  189. let path_start = self.url.path_start as usize;
  190. self.url.mutate(|parser| {
  191. parser.context = parser::Context::PathSegmentSetter;
  192. for segment in segments {
  193. let segment = segment.as_ref();
  194. if matches!(segment, "." | "..") {
  195. continue
  196. }
  197. if parser.serialization.len() > path_start + 1 {
  198. parser.serialization.push('/');
  199. }
  200. let mut has_host = true; // FIXME account for this?
  201. parser.parse_path(scheme_type, &mut has_host, path_start,
  202. parser::Input::new(segment));
  203. }
  204. });
  205. self
  206. }
  207. }