path_segments.rs 7.7 KB

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