path_segments.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 crate::parser::{self, to_u32, SchemeType};
  9. use crate::Url;
  10. use std::str;
  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<dyn 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. #[derive(Debug)]
  35. pub struct PathSegmentsMut<'a> {
  36. url: &'a mut Url,
  37. after_first_slash: usize,
  38. after_path: String,
  39. old_after_path_position: u32,
  40. }
  41. // Not re-exported outside the crate
  42. pub fn new(url: &mut Url) -> PathSegmentsMut<'_> {
  43. let after_path = url.take_after_path();
  44. let old_after_path_position = to_u32(url.serialization.len()).unwrap();
  45. // Special urls always have a non empty path
  46. if SchemeType::from(url.scheme()).is_special() {
  47. debug_assert!(url.byte_at(url.path_start) == b'/');
  48. } else {
  49. debug_assert!(
  50. url.serialization.len() == url.path_start as usize
  51. || url.byte_at(url.path_start) == b'/'
  52. );
  53. }
  54. PathSegmentsMut {
  55. after_first_slash: url.path_start as usize + "/".len(),
  56. url,
  57. old_after_path_position,
  58. after_path,
  59. }
  60. }
  61. impl<'a> Drop for PathSegmentsMut<'a> {
  62. fn drop(&mut self) {
  63. self.url
  64. .restore_after_path(self.old_after_path_position, &self.after_path)
  65. }
  66. }
  67. impl<'a> PathSegmentsMut<'a> {
  68. /// Remove all segments in the path, leaving the minimal `url.path() == "/"`.
  69. ///
  70. /// Returns `&mut Self` so that method calls can be chained.
  71. ///
  72. /// Example:
  73. ///
  74. /// ```rust
  75. /// use url::Url;
  76. /// # use std::error::Error;
  77. ///
  78. /// # fn run() -> Result<(), Box<dyn Error>> {
  79. /// let mut url = Url::parse("https://github.com/servo/rust-url/")?;
  80. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  81. /// .clear().push("logout");
  82. /// assert_eq!(url.as_str(), "https://github.com/logout");
  83. /// # Ok(())
  84. /// # }
  85. /// # run().unwrap();
  86. /// ```
  87. pub fn clear(&mut self) -> &mut Self {
  88. self.url.serialization.truncate(self.after_first_slash);
  89. self
  90. }
  91. /// Remove the last segment of this URL’s path if it is empty,
  92. /// except if these was only one segment to begin with.
  93. ///
  94. /// In other words, remove one path trailing slash, if any,
  95. /// unless it is also the initial slash (so this does nothing if `url.path() == "/")`.
  96. ///
  97. /// Returns `&mut Self` so that method calls can be chained.
  98. ///
  99. /// Example:
  100. ///
  101. /// ```rust
  102. /// use url::Url;
  103. /// # use std::error::Error;
  104. ///
  105. /// # fn run() -> Result<(), Box<dyn Error>> {
  106. /// let mut url = Url::parse("https://github.com/servo/rust-url/")?;
  107. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  108. /// .push("pulls");
  109. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url//pulls");
  110. ///
  111. /// let mut url = Url::parse("https://github.com/servo/rust-url/")?;
  112. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  113. /// .pop_if_empty().push("pulls");
  114. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url/pulls");
  115. /// # Ok(())
  116. /// # }
  117. /// # run().unwrap();
  118. /// ```
  119. pub fn pop_if_empty(&mut self) -> &mut Self {
  120. if self.after_first_slash >= self.url.serialization.len() {
  121. return self;
  122. }
  123. if self.url.serialization[self.after_first_slash..].ends_with('/') {
  124. self.url.serialization.pop();
  125. }
  126. self
  127. }
  128. /// Remove the last segment of this URL’s path.
  129. ///
  130. /// If the path only has one segment, make it empty such that `url.path() == "/"`.
  131. ///
  132. /// Returns `&mut Self` so that method calls can be chained.
  133. pub fn pop(&mut self) -> &mut Self {
  134. if self.after_first_slash >= self.url.serialization.len() {
  135. return self;
  136. }
  137. let last_slash = self.url.serialization[self.after_first_slash..]
  138. .rfind('/')
  139. .unwrap_or(0);
  140. self.url
  141. .serialization
  142. .truncate(self.after_first_slash + last_slash);
  143. self
  144. }
  145. /// Append the given segment at the end of this URL’s path.
  146. ///
  147. /// See the documentation for `.extend()`.
  148. ///
  149. /// Returns `&mut Self` so that method calls can be chained.
  150. pub fn push(&mut self, segment: &str) -> &mut Self {
  151. self.extend(Some(segment))
  152. }
  153. /// Append each segment from the given iterator at the end of this URL’s path.
  154. ///
  155. /// Each segment is percent-encoded like in `Url::parse` or `Url::join`,
  156. /// except that `%` and `/` characters are also encoded (to `%25` and `%2F`).
  157. /// This is unlike `Url::parse` where `%` is left as-is in case some of the input
  158. /// is already percent-encoded, and `/` denotes a path segment separator.)
  159. ///
  160. /// Note that, in addition to slashes between new segments,
  161. /// this always adds a slash between the existing path and the new segments
  162. /// *except* if the existing path is `"/"`.
  163. /// If the previous last segment was empty (if the path had a trailing slash)
  164. /// the path after `.extend()` will contain two consecutive slashes.
  165. /// If that is undesired, call `.pop_if_empty()` first.
  166. ///
  167. /// To obtain a behavior similar to `Url::join`, call `.pop()` unconditionally first.
  168. ///
  169. /// Returns `&mut Self` so that method calls can be chained.
  170. ///
  171. /// Example:
  172. ///
  173. /// ```rust
  174. /// use url::Url;
  175. /// # use std::error::Error;
  176. ///
  177. /// # fn run() -> Result<(), Box<dyn Error>> {
  178. /// let mut url = Url::parse("https://github.com/")?;
  179. /// let org = "servo";
  180. /// let repo = "rust-url";
  181. /// let issue_number = "188";
  182. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  183. /// .extend(&[org, repo, "issues", issue_number]);
  184. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url/issues/188");
  185. /// # Ok(())
  186. /// # }
  187. /// # run().unwrap();
  188. /// ```
  189. ///
  190. /// In order to make sure that parsing the serialization of an URL gives the same URL,
  191. /// a segment is ignored if it is `"."` or `".."`:
  192. ///
  193. /// ```rust
  194. /// use url::Url;
  195. /// # use std::error::Error;
  196. ///
  197. /// # fn run() -> Result<(), Box<dyn Error>> {
  198. /// let mut url = Url::parse("https://github.com/servo")?;
  199. /// url.path_segments_mut().map_err(|_| "cannot be base")?
  200. /// .extend(&["..", "rust-url", ".", "pulls"]);
  201. /// assert_eq!(url.as_str(), "https://github.com/servo/rust-url/pulls");
  202. /// # Ok(())
  203. /// # }
  204. /// # run().unwrap();
  205. /// ```
  206. pub fn extend<I>(&mut self, segments: I) -> &mut Self
  207. where
  208. I: IntoIterator,
  209. I::Item: AsRef<str>,
  210. {
  211. let scheme_type = SchemeType::from(self.url.scheme());
  212. let path_start = self.url.path_start as usize;
  213. self.url.mutate(|parser| {
  214. parser.context = parser::Context::PathSegmentSetter;
  215. for segment in segments {
  216. let segment = segment.as_ref();
  217. if matches!(segment, "." | "..") {
  218. continue;
  219. }
  220. if parser.serialization.len() > path_start + 1
  221. // Non special url's path might still be empty
  222. || parser.serialization.len() == path_start
  223. {
  224. parser.serialization.push('/');
  225. }
  226. let mut has_host = true; // FIXME account for this?
  227. parser.parse_path(
  228. scheme_type,
  229. &mut has_host,
  230. path_start,
  231. parser::Input::new(segment),
  232. );
  233. }
  234. });
  235. self
  236. }
  237. }