lib.rs 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  1. // Copyright 2013-2015 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. /*!
  9. rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  10. for the [Rust](http://rust-lang.org/) programming language.
  11. # URL parsing and data structures
  12. First, URL parsing may fail for various reasons and therefore returns a `Result`.
  13. ```
  14. use url::{Url, ParseError};
  15. assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
  16. ```
  17. Let’s parse a valid URL and look at its components.
  18. ```
  19. use url::{Url, Host, Position};
  20. # use url::ParseError;
  21. # fn run() -> Result<(), ParseError> {
  22. let issue_list_url = Url::parse(
  23. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  24. )?;
  25. assert!(issue_list_url.scheme() == "https");
  26. assert!(issue_list_url.username() == "");
  27. assert!(issue_list_url.password() == None);
  28. assert!(issue_list_url.host_str() == Some("github.com"));
  29. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  30. assert!(issue_list_url.port() == None);
  31. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  32. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  33. Some(vec!["rust-lang", "rust", "issues"]));
  34. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  35. assert!(&issue_list_url[Position::BeforePath..] == "/rust-lang/rust/issues?labels=E-easy&state=open");
  36. assert!(issue_list_url.fragment() == None);
  37. assert!(!issue_list_url.cannot_be_a_base());
  38. # Ok(())
  39. # }
  40. # run().unwrap();
  41. ```
  42. Some URLs are said to be *cannot-be-a-base*:
  43. they don’t have a username, password, host, or port,
  44. and their "path" is an arbitrary string rather than slash-separated segments:
  45. ```
  46. use url::Url;
  47. # use url::ParseError;
  48. # fn run() -> Result<(), ParseError> {
  49. let data_url = Url::parse("data:text/plain,Hello?World#")?;
  50. assert!(data_url.cannot_be_a_base());
  51. assert!(data_url.scheme() == "data");
  52. assert!(data_url.path() == "text/plain,Hello");
  53. assert!(data_url.path_segments().is_none());
  54. assert!(data_url.query() == Some("World"));
  55. assert!(data_url.fragment() == Some(""));
  56. # Ok(())
  57. # }
  58. # run().unwrap();
  59. ```
  60. # Base URL
  61. Many contexts allow URL *references* that can be relative to a *base URL*:
  62. ```html
  63. <link rel="stylesheet" href="../main.css">
  64. ```
  65. Since parsed URLs are absolute, giving a base is required for parsing relative URLs:
  66. ```
  67. use url::{Url, ParseError};
  68. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  69. ```
  70. Use the `join` method on an `Url` to use it as a base URL:
  71. ```
  72. use url::Url;
  73. # use url::ParseError;
  74. # fn run() -> Result<(), ParseError> {
  75. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html")?;
  76. let css_url = this_document.join("../main.css")?;
  77. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css");
  78. # Ok(())
  79. # }
  80. # run().unwrap();
  81. */
  82. #![doc(html_root_url = "https://docs.rs/url/1.7.0")]
  83. #[cfg(feature="rustc-serialize")] extern crate rustc_serialize;
  84. #[macro_use] extern crate matches;
  85. #[cfg(feature="serde")] extern crate serde;
  86. #[cfg(feature="heapsize")] #[macro_use] extern crate heapsize;
  87. pub extern crate idna;
  88. #[macro_use]
  89. pub extern crate percent_encoding;
  90. use encoding::EncodingOverride;
  91. #[cfg(feature = "heapsize")] use heapsize::HeapSizeOf;
  92. use host::HostInternal;
  93. use parser::{Parser, Context, SchemeType, to_u32, ViolationFn};
  94. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET,
  95. percent_encode, percent_decode, utf8_percent_encode};
  96. use std::borrow::Borrow;
  97. use std::cmp;
  98. #[cfg(feature = "serde")] use std::error::Error;
  99. use std::fmt::{self, Write, Debug, Formatter};
  100. use std::hash;
  101. use std::io;
  102. use std::mem;
  103. use std::net::{ToSocketAddrs, IpAddr};
  104. use std::ops::{Range, RangeFrom, RangeTo};
  105. use std::path::{Path, PathBuf};
  106. use std::str;
  107. pub use origin::{Origin, OpaqueOrigin};
  108. pub use host::{Host, HostAndPort, SocketAddrs};
  109. pub use path_segments::PathSegmentsMut;
  110. pub use parser::{ParseError, SyntaxViolation};
  111. pub use slicing::Position;
  112. mod encoding;
  113. mod host;
  114. mod origin;
  115. mod path_segments;
  116. mod parser;
  117. mod slicing;
  118. pub mod form_urlencoded;
  119. #[doc(hidden)] pub mod quirks;
  120. /// A parsed URL record.
  121. #[derive(Clone)]
  122. pub struct Url {
  123. /// Syntax in pseudo-BNF:
  124. ///
  125. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  126. /// non-hierarchical = non-hierarchical-path
  127. /// non-hierarchical-path = /* Does not start with "/" */
  128. /// hierarchical = authority? hierarchical-path
  129. /// authority = "//" userinfo? host [ ":" port ]?
  130. /// userinfo = username [ ":" password ]? "@"
  131. /// hierarchical-path = [ "/" path-segment ]+
  132. serialization: String,
  133. // Components
  134. scheme_end: u32, // Before ':'
  135. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  136. host_start: u32,
  137. host_end: u32,
  138. host: HostInternal,
  139. port: Option<u16>,
  140. path_start: u32, // Before initial '/', if any
  141. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  142. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  143. }
  144. #[cfg(feature = "heapsize")]
  145. impl HeapSizeOf for Url {
  146. fn heap_size_of_children(&self) -> usize {
  147. self.serialization.heap_size_of_children()
  148. }
  149. }
  150. /// Full configuration for the URL parser.
  151. #[derive(Copy, Clone)]
  152. pub struct ParseOptions<'a> {
  153. base_url: Option<&'a Url>,
  154. encoding_override: encoding::EncodingOverride,
  155. violation_fn: ViolationFn<'a>,
  156. }
  157. impl<'a> ParseOptions<'a> {
  158. /// Change the base URL
  159. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  160. self.base_url = new;
  161. self
  162. }
  163. /// Override the character encoding of query strings.
  164. /// This is a legacy concept only relevant for HTML.
  165. ///
  166. /// `EncodingRef` is defined in [rust-encoding](https://github.com/lifthrasiir/rust-encoding).
  167. ///
  168. /// This method is only available if the `query_encoding`
  169. /// [feature](http://doc.crates.io/manifest.html#the-features-section]) is enabled.
  170. #[cfg(feature = "query_encoding")]
  171. pub fn encoding_override(mut self, new: Option<encoding::EncodingRef>) -> Self {
  172. self.encoding_override = EncodingOverride::from_opt_encoding(new).to_output_encoding();
  173. self
  174. }
  175. /// Call the provided function or closure on non-fatal parse errors, passing
  176. /// a static string description. This method is deprecated in favor of
  177. /// `syntax_violation_callback` and is implemented as an adaptor for the
  178. /// latter, passing the `SyntaxViolation` description. Only the last value
  179. /// passed to either method will be used by a parser.
  180. #[deprecated]
  181. pub fn log_syntax_violation(mut self, new: Option<&'a Fn(&'static str)>) -> Self {
  182. self.violation_fn = match new {
  183. Some(f) => ViolationFn::OldFn(f),
  184. None => ViolationFn::NoOp
  185. };
  186. self
  187. }
  188. /// Call the provided function or closure for a non-fatal `SyntaxViolation`
  189. /// when it occurs during parsing. Note that since the provided function is
  190. /// `Fn`, the caller might need to utilize _interior mutability_, such as with
  191. /// a `RefCell`, to collect the violations.
  192. ///
  193. /// ## Example
  194. /// ```
  195. /// use std::cell::RefCell;
  196. /// use url::{Url, SyntaxViolation};
  197. /// # use url::ParseError;
  198. /// # fn run() -> Result<(), url::ParseError> {
  199. /// let violations = RefCell::new(Vec::new());
  200. /// let url = Url::options()
  201. /// .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v)))
  202. /// .parse("https:////example.com")?;
  203. /// assert_eq!(url.as_str(), "https://example.com/");
  204. /// assert_eq!(violations.into_inner(),
  205. /// vec!(SyntaxViolation::ExpectedDoubleSlash));
  206. /// # Ok(())
  207. /// # }
  208. /// # run().unwrap();
  209. /// ```
  210. pub fn syntax_violation_callback(mut self, new: Option<&'a Fn(SyntaxViolation)>) -> Self {
  211. self.violation_fn = match new {
  212. Some(f) => ViolationFn::NewFn(f),
  213. None => ViolationFn::NoOp
  214. };
  215. self
  216. }
  217. /// Parse an URL string with the configuration so far.
  218. pub fn parse(self, input: &str) -> Result<Url, ::ParseError> {
  219. Parser {
  220. serialization: String::with_capacity(input.len()),
  221. base_url: self.base_url,
  222. query_encoding_override: self.encoding_override,
  223. violation_fn: self.violation_fn,
  224. context: Context::UrlParser,
  225. }.parse_url(input)
  226. }
  227. }
  228. impl<'a> Debug for ParseOptions<'a> {
  229. fn fmt(&self, f: &mut Formatter) -> fmt::Result {
  230. write!(f,
  231. "ParseOptions {{ base_url: {:?}, encoding_override: {:?}, \
  232. violation_fn: {:?} }}",
  233. self.base_url,
  234. self.encoding_override,
  235. self.violation_fn)
  236. }
  237. }
  238. impl Url {
  239. /// Parse an absolute URL from a string.
  240. ///
  241. /// # Examples
  242. ///
  243. /// ```rust
  244. /// use url::Url;
  245. /// # use url::ParseError;
  246. ///
  247. /// # fn run() -> Result<(), ParseError> {
  248. /// let url = Url::parse("https://example.net")?;
  249. /// # Ok(())
  250. /// # }
  251. /// # run().unwrap();
  252. /// ```
  253. ///
  254. /// # Errors
  255. ///
  256. /// If the function can not parse an absolute URL from the given string,
  257. /// a [`ParseError`] variant will be returned.
  258. ///
  259. /// [`ParseError`]: enum.ParseError.html
  260. #[inline]
  261. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  262. Url::options().parse(input)
  263. }
  264. /// Parse an absolute URL from a string and add params to its query string.
  265. ///
  266. /// Existing params are not removed.
  267. ///
  268. /// # Examples
  269. ///
  270. /// ```rust
  271. /// use url::Url;
  272. /// # use url::ParseError;
  273. ///
  274. /// # fn run() -> Result<(), ParseError> {
  275. /// let url = Url::parse_with_params("https://example.net?dont=clobberme",
  276. /// &[("lang", "rust"), ("browser", "servo")])?;
  277. /// # Ok(())
  278. /// # }
  279. /// # run().unwrap();
  280. /// ```
  281. ///
  282. /// # Errors
  283. ///
  284. /// If the function can not parse an absolute URL from the given string,
  285. /// a [`ParseError`] variant will be returned.
  286. ///
  287. /// [`ParseError`]: enum.ParseError.html
  288. #[inline]
  289. pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, ::ParseError>
  290. where I: IntoIterator,
  291. I::Item: Borrow<(K, V)>,
  292. K: AsRef<str>,
  293. V: AsRef<str>
  294. {
  295. let mut url = Url::options().parse(input);
  296. if let Ok(ref mut url) = url {
  297. url.query_pairs_mut().extend_pairs(iter);
  298. }
  299. url
  300. }
  301. /// Parse a string as an URL, with this URL as the base URL.
  302. ///
  303. /// Note: a trailing slash is significant.
  304. /// Without it, the last path component is considered to be a “file” name
  305. /// to be removed to get at the “directory” that is used as the base:
  306. ///
  307. /// # Examples
  308. ///
  309. /// ```rust
  310. /// use url::Url;
  311. /// # use url::ParseError;
  312. ///
  313. /// # fn run() -> Result<(), ParseError> {
  314. /// let base = Url::parse("https://example.net/a/b.html")?;
  315. /// let url = base.join("c.png")?;
  316. /// assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png
  317. ///
  318. /// let base = Url::parse("https://example.net/a/b/")?;
  319. /// let url = base.join("c.png")?;
  320. /// assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
  321. /// # Ok(())
  322. /// # }
  323. /// # run().unwrap();
  324. /// ```
  325. ///
  326. /// # Errors
  327. ///
  328. /// If the function can not parse an URL from the given string
  329. /// with this URL as the base URL, a [`ParseError`] variant will be returned.
  330. ///
  331. /// [`ParseError`]: enum.ParseError.html
  332. #[inline]
  333. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  334. Url::options().base_url(Some(self)).parse(input)
  335. }
  336. /// Return a default `ParseOptions` that can fully configure the URL parser.
  337. ///
  338. /// # Examples
  339. ///
  340. /// Get default `ParseOptions`, then change base url
  341. ///
  342. /// ```rust
  343. /// use url::Url;
  344. /// # use url::ParseError;
  345. /// # fn run() -> Result<(), ParseError> {
  346. /// let options = Url::options();
  347. /// let api = Url::parse("https://api.example.com")?;
  348. /// let base_url = options.base_url(Some(&api));
  349. /// let version_url = base_url.parse("version.json")?;
  350. /// assert_eq!(version_url.as_str(), "https://api.example.com/version.json");
  351. /// # Ok(())
  352. /// # }
  353. /// # run().unwrap();
  354. /// ```
  355. pub fn options<'a>() -> ParseOptions<'a> {
  356. ParseOptions {
  357. base_url: None,
  358. encoding_override: EncodingOverride::utf8(),
  359. violation_fn: ViolationFn::NoOp,
  360. }
  361. }
  362. /// Return the serialization of this URL.
  363. ///
  364. /// This is fast since that serialization is already stored in the `Url` struct.
  365. ///
  366. /// # Examples
  367. ///
  368. /// ```rust
  369. /// use url::Url;
  370. /// # use url::ParseError;
  371. ///
  372. /// # fn run() -> Result<(), ParseError> {
  373. /// let url_str = "https://example.net/";
  374. /// let url = Url::parse(url_str)?;
  375. /// assert_eq!(url.as_str(), url_str);
  376. /// # Ok(())
  377. /// # }
  378. /// # run().unwrap();
  379. /// ```
  380. #[inline]
  381. pub fn as_str(&self) -> &str {
  382. &self.serialization
  383. }
  384. /// Return the serialization of this URL.
  385. ///
  386. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  387. ///
  388. /// # Examples
  389. ///
  390. /// ```rust
  391. /// use url::Url;
  392. /// # use url::ParseError;
  393. ///
  394. /// # fn run() -> Result<(), ParseError> {
  395. /// let url_str = "https://example.net/";
  396. /// let url = Url::parse(url_str)?;
  397. /// assert_eq!(url.into_string(), url_str);
  398. /// # Ok(())
  399. /// # }
  400. /// # run().unwrap();
  401. /// ```
  402. #[inline]
  403. pub fn into_string(self) -> String {
  404. self.serialization
  405. }
  406. /// For internal testing, not part of the public API.
  407. ///
  408. /// Methods of the `Url` struct assume a number of invariants.
  409. /// This checks each of these invariants and panic if one is not met.
  410. /// This is for testing rust-url itself.
  411. #[doc(hidden)]
  412. pub fn check_invariants(&self) -> Result<(), String> {
  413. macro_rules! assert {
  414. ($x: expr) => {
  415. if !$x {
  416. return Err(format!("!( {} ) for URL {:?}",
  417. stringify!($x), self.serialization))
  418. }
  419. }
  420. }
  421. macro_rules! assert_eq {
  422. ($a: expr, $b: expr) => {
  423. {
  424. let a = $a;
  425. let b = $b;
  426. if a != b {
  427. return Err(format!("{:?} != {:?} ({} != {}) for URL {:?}",
  428. a, b, stringify!($a), stringify!($b),
  429. self.serialization))
  430. }
  431. }
  432. }
  433. }
  434. assert!(self.scheme_end >= 1);
  435. assert!(matches!(self.byte_at(0), b'a'...b'z' | b'A'...b'Z'));
  436. assert!(self.slice(1..self.scheme_end).chars()
  437. .all(|c| matches!(c, 'a'...'z' | 'A'...'Z' | '0'...'9' | '+' | '-' | '.')));
  438. assert_eq!(self.byte_at(self.scheme_end), b':');
  439. if self.slice(self.scheme_end + 1 ..).starts_with("//") {
  440. // URL with authority
  441. match self.byte_at(self.username_end) {
  442. b':' => {
  443. assert!(self.host_start >= self.username_end + 2);
  444. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  445. }
  446. b'@' => assert!(self.host_start == self.username_end + 1),
  447. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  448. }
  449. assert!(self.host_start >= self.username_end);
  450. assert!(self.host_end >= self.host_start);
  451. let host_str = self.slice(self.host_start..self.host_end);
  452. match self.host {
  453. HostInternal::None => assert_eq!(host_str, ""),
  454. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  455. HostInternal::Ipv6(address) => {
  456. let h: Host<String> = Host::Ipv6(address);
  457. assert_eq!(host_str, h.to_string())
  458. }
  459. HostInternal::Domain => {
  460. if SchemeType::from(self.scheme()).is_special() {
  461. assert!(!host_str.is_empty())
  462. }
  463. }
  464. }
  465. if self.path_start == self.host_end {
  466. assert_eq!(self.port, None);
  467. } else {
  468. assert_eq!(self.byte_at(self.host_end), b':');
  469. let port_str = self.slice(self.host_end + 1..self.path_start);
  470. assert_eq!(self.port, Some(port_str.parse::<u16>().expect("Couldn't parse port?")));
  471. }
  472. assert_eq!(self.byte_at(self.path_start), b'/');
  473. } else {
  474. // Anarchist URL (no authority)
  475. assert_eq!(self.username_end, self.scheme_end + 1);
  476. assert_eq!(self.host_start, self.scheme_end + 1);
  477. assert_eq!(self.host_end, self.scheme_end + 1);
  478. assert_eq!(self.host, HostInternal::None);
  479. assert_eq!(self.port, None);
  480. assert_eq!(self.path_start, self.scheme_end + 1);
  481. }
  482. if let Some(start) = self.query_start {
  483. assert!(start > self.path_start);
  484. assert_eq!(self.byte_at(start), b'?');
  485. }
  486. if let Some(start) = self.fragment_start {
  487. assert!(start > self.path_start);
  488. assert_eq!(self.byte_at(start), b'#');
  489. }
  490. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  491. assert!(fragment_start > query_start);
  492. }
  493. let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
  494. assert_eq!(&self.serialization, &other.serialization);
  495. assert_eq!(self.scheme_end, other.scheme_end);
  496. assert_eq!(self.username_end, other.username_end);
  497. assert_eq!(self.host_start, other.host_start);
  498. assert_eq!(self.host_end, other.host_end);
  499. assert!(self.host == other.host ||
  500. // XXX No host round-trips to empty host.
  501. // See https://github.com/whatwg/url/issues/79
  502. (self.host_str(), other.host_str()) == (None, Some("")));
  503. assert_eq!(self.port, other.port);
  504. assert_eq!(self.path_start, other.path_start);
  505. assert_eq!(self.query_start, other.query_start);
  506. assert_eq!(self.fragment_start, other.fragment_start);
  507. Ok(())
  508. }
  509. /// Return the origin of this URL (<https://url.spec.whatwg.org/#origin>)
  510. ///
  511. /// Note: this returns an opaque origin for `file:` URLs, which causes
  512. /// `url.origin() != url.origin()`.
  513. ///
  514. /// # Examples
  515. ///
  516. /// URL with `ftp` scheme:
  517. ///
  518. /// ```rust
  519. /// use url::{Host, Origin, Url};
  520. /// # use url::ParseError;
  521. ///
  522. /// # fn run() -> Result<(), ParseError> {
  523. /// let url = Url::parse("ftp://example.com/foo")?;
  524. /// assert_eq!(url.origin(),
  525. /// Origin::Tuple("ftp".into(),
  526. /// Host::Domain("example.com".into()),
  527. /// 21));
  528. /// # Ok(())
  529. /// # }
  530. /// # run().unwrap();
  531. /// ```
  532. ///
  533. /// URL with `blob` scheme:
  534. ///
  535. /// ```rust
  536. /// use url::{Host, Origin, Url};
  537. /// # use url::ParseError;
  538. ///
  539. /// # fn run() -> Result<(), ParseError> {
  540. /// let url = Url::parse("blob:https://example.com/foo")?;
  541. /// assert_eq!(url.origin(),
  542. /// Origin::Tuple("https".into(),
  543. /// Host::Domain("example.com".into()),
  544. /// 443));
  545. /// # Ok(())
  546. /// # }
  547. /// # run().unwrap();
  548. /// ```
  549. ///
  550. /// URL with `file` scheme:
  551. ///
  552. /// ```rust
  553. /// use url::{Host, Origin, Url};
  554. /// # use url::ParseError;
  555. ///
  556. /// # fn run() -> Result<(), ParseError> {
  557. /// let url = Url::parse("file:///tmp/foo")?;
  558. /// assert!(!url.origin().is_tuple());
  559. ///
  560. /// let other_url = Url::parse("file:///tmp/foo")?;
  561. /// assert!(url.origin() != other_url.origin());
  562. /// # Ok(())
  563. /// # }
  564. /// # run().unwrap();
  565. /// ```
  566. ///
  567. /// URL with other scheme:
  568. ///
  569. /// ```rust
  570. /// use url::{Host, Origin, Url};
  571. /// # use url::ParseError;
  572. ///
  573. /// # fn run() -> Result<(), ParseError> {
  574. /// let url = Url::parse("foo:bar")?;
  575. /// assert!(!url.origin().is_tuple());
  576. /// # Ok(())
  577. /// # }
  578. /// # run().unwrap();
  579. /// ```
  580. #[inline]
  581. pub fn origin(&self) -> Origin {
  582. origin::url_origin(self)
  583. }
  584. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  585. ///
  586. /// # Examples
  587. ///
  588. /// ```
  589. /// use url::Url;
  590. /// # use url::ParseError;
  591. ///
  592. /// # fn run() -> Result<(), ParseError> {
  593. /// let url = Url::parse("file:///tmp/foo")?;
  594. /// assert_eq!(url.scheme(), "file");
  595. /// # Ok(())
  596. /// # }
  597. /// # run().unwrap();
  598. /// ```
  599. #[inline]
  600. pub fn scheme(&self) -> &str {
  601. self.slice(..self.scheme_end)
  602. }
  603. /// Return whether the URL has an 'authority',
  604. /// which can contain a username, password, host, and port number.
  605. ///
  606. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  607. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  608. ///
  609. /// # Examples
  610. ///
  611. /// ```
  612. /// use url::Url;
  613. /// # use url::ParseError;
  614. ///
  615. /// # fn run() -> Result<(), ParseError> {
  616. /// let url = Url::parse("ftp://rms@example.com")?;
  617. /// assert!(url.has_authority());
  618. ///
  619. /// let url = Url::parse("unix:/run/foo.socket")?;
  620. /// assert!(!url.has_authority());
  621. ///
  622. /// let url = Url::parse("data:text/plain,Stuff")?;
  623. /// assert!(!url.has_authority());
  624. /// # Ok(())
  625. /// # }
  626. /// # run().unwrap();
  627. /// ```
  628. #[inline]
  629. pub fn has_authority(&self) -> bool {
  630. debug_assert!(self.byte_at(self.scheme_end) == b':');
  631. self.slice(self.scheme_end..).starts_with("://")
  632. }
  633. /// Return whether this URL is a cannot-be-a-base URL,
  634. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  635. ///
  636. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  637. /// as is typically the case of `data:` and `mailto:` URLs.
  638. ///
  639. /// # Examples
  640. ///
  641. /// ```
  642. /// use url::Url;
  643. /// # use url::ParseError;
  644. ///
  645. /// # fn run() -> Result<(), ParseError> {
  646. /// let url = Url::parse("ftp://rms@example.com")?;
  647. /// assert!(!url.cannot_be_a_base());
  648. ///
  649. /// let url = Url::parse("unix:/run/foo.socket")?;
  650. /// assert!(!url.cannot_be_a_base());
  651. ///
  652. /// let url = Url::parse("data:text/plain,Stuff")?;
  653. /// assert!(url.cannot_be_a_base());
  654. /// # Ok(())
  655. /// # }
  656. /// # run().unwrap();
  657. /// ```
  658. #[inline]
  659. pub fn cannot_be_a_base(&self) -> bool {
  660. !self.slice(self.path_start..).starts_with('/')
  661. }
  662. /// Return the username for this URL (typically the empty string)
  663. /// as a percent-encoded ASCII string.
  664. ///
  665. /// # Examples
  666. ///
  667. /// ```
  668. /// use url::Url;
  669. /// # use url::ParseError;
  670. ///
  671. /// # fn run() -> Result<(), ParseError> {
  672. /// let url = Url::parse("ftp://rms@example.com")?;
  673. /// assert_eq!(url.username(), "rms");
  674. ///
  675. /// let url = Url::parse("ftp://:secret123@example.com")?;
  676. /// assert_eq!(url.username(), "");
  677. ///
  678. /// let url = Url::parse("https://example.com")?;
  679. /// assert_eq!(url.username(), "");
  680. /// # Ok(())
  681. /// # }
  682. /// # run().unwrap();
  683. /// ```
  684. pub fn username(&self) -> &str {
  685. if self.has_authority() {
  686. self.slice(self.scheme_end + ("://".len() as u32)..self.username_end)
  687. } else {
  688. ""
  689. }
  690. }
  691. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  692. ///
  693. /// # Examples
  694. ///
  695. /// ```
  696. /// use url::Url;
  697. /// # use url::ParseError;
  698. ///
  699. /// # fn run() -> Result<(), ParseError> {
  700. /// let url = Url::parse("ftp://rms:secret123@example.com")?;
  701. /// assert_eq!(url.password(), Some("secret123"));
  702. ///
  703. /// let url = Url::parse("ftp://:secret123@example.com")?;
  704. /// assert_eq!(url.password(), Some("secret123"));
  705. ///
  706. /// let url = Url::parse("ftp://rms@example.com")?;
  707. /// assert_eq!(url.password(), None);
  708. ///
  709. /// let url = Url::parse("https://example.com")?;
  710. /// assert_eq!(url.password(), None);
  711. /// # Ok(())
  712. /// # }
  713. /// # run().unwrap();
  714. /// ```
  715. pub fn password(&self) -> Option<&str> {
  716. // This ':' is not the one marking a port number since a host can not be empty.
  717. // (Except for file: URLs, which do not have port numbers.)
  718. if self.has_authority() && self.byte_at(self.username_end) == b':' {
  719. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  720. Some(self.slice(self.username_end + 1..self.host_start - 1))
  721. } else {
  722. None
  723. }
  724. }
  725. /// Equivalent to `url.host().is_some()`.
  726. ///
  727. /// # Examples
  728. ///
  729. /// ```
  730. /// use url::Url;
  731. /// # use url::ParseError;
  732. ///
  733. /// # fn run() -> Result<(), ParseError> {
  734. /// let url = Url::parse("ftp://rms@example.com")?;
  735. /// assert!(url.has_host());
  736. ///
  737. /// let url = Url::parse("unix:/run/foo.socket")?;
  738. /// assert!(!url.has_host());
  739. ///
  740. /// let url = Url::parse("data:text/plain,Stuff")?;
  741. /// assert!(!url.has_host());
  742. /// # Ok(())
  743. /// # }
  744. /// # run().unwrap();
  745. /// ```
  746. pub fn has_host(&self) -> bool {
  747. !matches!(self.host, HostInternal::None)
  748. }
  749. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  750. ///
  751. /// Non-ASCII domains are punycode-encoded per IDNA.
  752. /// IPv6 addresses are given between `[` and `]` brackets.
  753. ///
  754. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  755. /// don’t have a host.
  756. ///
  757. /// See also the `host` method.
  758. ///
  759. /// # Examples
  760. ///
  761. /// ```
  762. /// use url::Url;
  763. /// # use url::ParseError;
  764. ///
  765. /// # fn run() -> Result<(), ParseError> {
  766. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  767. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  768. ///
  769. /// let url = Url::parse("ftp://rms@example.com")?;
  770. /// assert_eq!(url.host_str(), Some("example.com"));
  771. ///
  772. /// let url = Url::parse("unix:/run/foo.socket")?;
  773. /// assert_eq!(url.host_str(), None);
  774. ///
  775. /// let url = Url::parse("data:text/plain,Stuff")?;
  776. /// assert_eq!(url.host_str(), None);
  777. /// # Ok(())
  778. /// # }
  779. /// # run().unwrap();
  780. /// ```
  781. pub fn host_str(&self) -> Option<&str> {
  782. if self.has_host() {
  783. Some(self.slice(self.host_start..self.host_end))
  784. } else {
  785. None
  786. }
  787. }
  788. /// Return the parsed representation of the host for this URL.
  789. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  790. ///
  791. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  792. /// don’t have a host.
  793. ///
  794. /// See also the `host_str` method.
  795. ///
  796. /// # Examples
  797. ///
  798. /// ```
  799. /// use url::Url;
  800. /// # use url::ParseError;
  801. ///
  802. /// # fn run() -> Result<(), ParseError> {
  803. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  804. /// assert!(url.host().is_some());
  805. ///
  806. /// let url = Url::parse("ftp://rms@example.com")?;
  807. /// assert!(url.host().is_some());
  808. ///
  809. /// let url = Url::parse("unix:/run/foo.socket")?;
  810. /// assert!(url.host().is_none());
  811. ///
  812. /// let url = Url::parse("data:text/plain,Stuff")?;
  813. /// assert!(url.host().is_none());
  814. /// # Ok(())
  815. /// # }
  816. /// # run().unwrap();
  817. /// ```
  818. pub fn host(&self) -> Option<Host<&str>> {
  819. match self.host {
  820. HostInternal::None => None,
  821. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  822. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  823. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  824. }
  825. }
  826. /// If this URL has a host and it is a domain name (not an IP address), return it.
  827. ///
  828. /// # Examples
  829. ///
  830. /// ```
  831. /// use url::Url;
  832. /// # use url::ParseError;
  833. ///
  834. /// # fn run() -> Result<(), ParseError> {
  835. /// let url = Url::parse("https://127.0.0.1/")?;
  836. /// assert_eq!(url.domain(), None);
  837. ///
  838. /// let url = Url::parse("mailto:rms@example.net")?;
  839. /// assert_eq!(url.domain(), None);
  840. ///
  841. /// let url = Url::parse("https://example.com/")?;
  842. /// assert_eq!(url.domain(), Some("example.com"));
  843. /// # Ok(())
  844. /// # }
  845. /// # run().unwrap();
  846. /// ```
  847. pub fn domain(&self) -> Option<&str> {
  848. match self.host {
  849. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  850. _ => None,
  851. }
  852. }
  853. /// Return the port number for this URL, if any.
  854. ///
  855. /// # Examples
  856. ///
  857. /// ```
  858. /// use url::Url;
  859. /// # use url::ParseError;
  860. ///
  861. /// # fn run() -> Result<(), ParseError> {
  862. /// let url = Url::parse("https://example.com")?;
  863. /// assert_eq!(url.port(), None);
  864. ///
  865. /// let url = Url::parse("ssh://example.com:22")?;
  866. /// assert_eq!(url.port(), Some(22));
  867. /// # Ok(())
  868. /// # }
  869. /// # run().unwrap();
  870. /// ```
  871. #[inline]
  872. pub fn port(&self) -> Option<u16> {
  873. self.port
  874. }
  875. /// Return the port number for this URL, or the default port number if it is known.
  876. ///
  877. /// This method only knows the default port number
  878. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  879. ///
  880. /// For URLs in these schemes, this method always returns `Some(_)`.
  881. /// For other schemes, it is the same as `Url::port()`.
  882. ///
  883. /// # Examples
  884. ///
  885. /// ```
  886. /// use url::Url;
  887. /// # use url::ParseError;
  888. ///
  889. /// # fn run() -> Result<(), ParseError> {
  890. /// let url = Url::parse("foo://example.com")?;
  891. /// assert_eq!(url.port_or_known_default(), None);
  892. ///
  893. /// let url = Url::parse("foo://example.com:1456")?;
  894. /// assert_eq!(url.port_or_known_default(), Some(1456));
  895. ///
  896. /// let url = Url::parse("https://example.com")?;
  897. /// assert_eq!(url.port_or_known_default(), Some(443));
  898. /// # Ok(())
  899. /// # }
  900. /// # run().unwrap();
  901. /// ```
  902. #[inline]
  903. pub fn port_or_known_default(&self) -> Option<u16> {
  904. self.port.or_else(|| parser::default_port(self.scheme()))
  905. }
  906. /// If the URL has a host, return something that implements `ToSocketAddrs`.
  907. ///
  908. /// If the URL has no port number and the scheme’s default port number is not known
  909. /// (see `Url::port_or_known_default`),
  910. /// the closure is called to obtain a port number.
  911. /// Typically, this closure can match on the result `Url::scheme`
  912. /// to have per-scheme default port numbers,
  913. /// and panic for schemes it’s not prepared to handle.
  914. /// For example:
  915. ///
  916. /// ```rust
  917. /// # use url::Url;
  918. /// # use std::net::TcpStream;
  919. /// # use std::io;
  920. /// fn connect(url: &Url) -> io::Result<TcpStream> {
  921. /// TcpStream::connect(url.with_default_port(default_port)?)
  922. /// }
  923. ///
  924. /// fn default_port(url: &Url) -> Result<u16, ()> {
  925. /// match url.scheme() {
  926. /// "git" => Ok(9418),
  927. /// "git+ssh" => Ok(22),
  928. /// "git+https" => Ok(443),
  929. /// "git+http" => Ok(80),
  930. /// _ => Err(()),
  931. /// }
  932. /// }
  933. /// ```
  934. pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
  935. where F: FnOnce(&Url) -> Result<u16, ()> {
  936. Ok(HostAndPort {
  937. host: self.host()
  938. .ok_or(())
  939. .or_else(|()| io_error("URL has no host"))?,
  940. port: self.port_or_known_default()
  941. .ok_or(())
  942. .or_else(|()| f(self))
  943. .or_else(|()| io_error("URL has no port number"))?
  944. })
  945. }
  946. /// Return the path for this URL, as a percent-encoded ASCII string.
  947. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  948. /// For other URLs, this starts with a '/' slash
  949. /// and continues with slash-separated path segments.
  950. ///
  951. /// # Examples
  952. ///
  953. /// ```rust
  954. /// use url::{Url, ParseError};
  955. ///
  956. /// # fn run() -> Result<(), ParseError> {
  957. /// let url = Url::parse("https://example.com/api/versions?page=2")?;
  958. /// assert_eq!(url.path(), "/api/versions");
  959. ///
  960. /// let url = Url::parse("https://example.com")?;
  961. /// assert_eq!(url.path(), "/");
  962. ///
  963. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  964. /// assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam");
  965. /// # Ok(())
  966. /// # }
  967. /// # run().unwrap();
  968. /// ```
  969. pub fn path(&self) -> &str {
  970. match (self.query_start, self.fragment_start) {
  971. (None, None) => self.slice(self.path_start..),
  972. (Some(next_component_start), _) |
  973. (None, Some(next_component_start)) => {
  974. self.slice(self.path_start..next_component_start)
  975. }
  976. }
  977. }
  978. /// Unless this URL is cannot-be-a-base,
  979. /// return an iterator of '/' slash-separated path segments,
  980. /// each as a percent-encoded ASCII string.
  981. ///
  982. /// Return `None` for cannot-be-a-base URLs.
  983. ///
  984. /// When `Some` is returned, the iterator always contains at least one string
  985. /// (which may be empty).
  986. ///
  987. /// # Examples
  988. ///
  989. /// ```
  990. /// use url::Url;
  991. /// # use std::error::Error;
  992. ///
  993. /// # fn run() -> Result<(), Box<Error>> {
  994. /// let url = Url::parse("https://example.com/foo/bar")?;
  995. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  996. /// assert_eq!(path_segments.next(), Some("foo"));
  997. /// assert_eq!(path_segments.next(), Some("bar"));
  998. /// assert_eq!(path_segments.next(), None);
  999. ///
  1000. /// let url = Url::parse("https://example.com")?;
  1001. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1002. /// assert_eq!(path_segments.next(), Some(""));
  1003. /// assert_eq!(path_segments.next(), None);
  1004. ///
  1005. /// let url = Url::parse("data:text/plain,HelloWorld")?;
  1006. /// assert!(url.path_segments().is_none());
  1007. ///
  1008. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  1009. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1010. /// assert_eq!(path_segments.next(), Some("countries"));
  1011. /// assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam"));
  1012. /// # Ok(())
  1013. /// # }
  1014. /// # run().unwrap();
  1015. /// ```
  1016. pub fn path_segments(&self) -> Option<str::Split<char>> {
  1017. let path = self.path();
  1018. if path.starts_with('/') {
  1019. Some(path[1..].split('/'))
  1020. } else {
  1021. None
  1022. }
  1023. }
  1024. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  1025. ///
  1026. /// # Examples
  1027. ///
  1028. /// ```rust
  1029. /// use url::Url;
  1030. /// # use url::ParseError;
  1031. ///
  1032. /// fn run() -> Result<(), ParseError> {
  1033. /// let url = Url::parse("https://example.com/products?page=2")?;
  1034. /// let query = url.query();
  1035. /// assert_eq!(query, Some("page=2"));
  1036. ///
  1037. /// let url = Url::parse("https://example.com/products")?;
  1038. /// let query = url.query();
  1039. /// assert!(query.is_none());
  1040. ///
  1041. /// let url = Url::parse("https://example.com/?country=español")?;
  1042. /// let query = url.query();
  1043. /// assert_eq!(query, Some("country=espa%C3%B1ol"));
  1044. /// # Ok(())
  1045. /// # }
  1046. /// # run().unwrap();
  1047. /// ```
  1048. pub fn query(&self) -> Option<&str> {
  1049. match (self.query_start, self.fragment_start) {
  1050. (None, _) => None,
  1051. (Some(query_start), None) => {
  1052. debug_assert!(self.byte_at(query_start) == b'?');
  1053. Some(self.slice(query_start + 1..))
  1054. }
  1055. (Some(query_start), Some(fragment_start)) => {
  1056. debug_assert!(self.byte_at(query_start) == b'?');
  1057. Some(self.slice(query_start + 1..fragment_start))
  1058. }
  1059. }
  1060. }
  1061. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  1062. /// and return an iterator of (key, value) pairs.
  1063. ///
  1064. /// # Examples
  1065. ///
  1066. /// ```rust
  1067. /// use std::borrow::Cow;
  1068. ///
  1069. /// use url::Url;
  1070. /// # use url::ParseError;
  1071. ///
  1072. /// # fn run() -> Result<(), ParseError> {
  1073. /// let url = Url::parse("https://example.com/products?page=2&sort=desc")?;
  1074. /// let mut pairs = url.query_pairs();
  1075. ///
  1076. /// assert_eq!(pairs.count(), 2);
  1077. ///
  1078. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("page"), Cow::Borrowed("2"))));
  1079. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("sort"), Cow::Borrowed("desc"))));
  1080. /// # Ok(())
  1081. /// # }
  1082. /// # run().unwrap();
  1083. ///
  1084. #[inline]
  1085. pub fn query_pairs(&self) -> form_urlencoded::Parse {
  1086. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  1087. }
  1088. /// Return this URL’s fragment identifier, if any.
  1089. ///
  1090. /// A fragment is the part of the URL after the `#` symbol.
  1091. /// The fragment is optional and, if present, contains a fragment identifier
  1092. /// that identifies a secondary resource, such as a section heading
  1093. /// of a document.
  1094. ///
  1095. /// In HTML, the fragment identifier is usually the id attribute of a an element
  1096. /// that is scrolled to on load. Browsers typically will not send the fragment portion
  1097. /// of a URL to the server.
  1098. ///
  1099. /// **Note:** the parser did *not* percent-encode this component,
  1100. /// but the input may have been percent-encoded already.
  1101. ///
  1102. /// # Examples
  1103. ///
  1104. /// ```rust
  1105. /// use url::Url;
  1106. /// # use url::ParseError;
  1107. ///
  1108. /// # fn run() -> Result<(), ParseError> {
  1109. /// let url = Url::parse("https://example.com/data.csv#row=4")?;
  1110. ///
  1111. /// assert_eq!(url.fragment(), Some("row=4"));
  1112. ///
  1113. /// let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?;
  1114. ///
  1115. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1116. /// # Ok(())
  1117. /// # }
  1118. /// # run().unwrap();
  1119. /// ```
  1120. pub fn fragment(&self) -> Option<&str> {
  1121. self.fragment_start.map(|start| {
  1122. debug_assert!(self.byte_at(start) == b'#');
  1123. self.slice(start + 1..)
  1124. })
  1125. }
  1126. fn mutate<F: FnOnce(&mut Parser) -> R, R>(&mut self, f: F) -> R {
  1127. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  1128. let result = f(&mut parser);
  1129. self.serialization = parser.serialization;
  1130. result
  1131. }
  1132. /// Change this URL’s fragment identifier.
  1133. ///
  1134. /// # Examples
  1135. ///
  1136. /// ```rust
  1137. /// use url::Url;
  1138. /// # use url::ParseError;
  1139. ///
  1140. /// # fn run() -> Result<(), ParseError> {
  1141. /// let mut url = Url::parse("https://example.com/data.csv")?;
  1142. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1143. /// url.set_fragment(Some("cell=4,1-6,2"));
  1144. /// assert_eq!(url.as_str(), "https://example.com/data.csv#cell=4,1-6,2");
  1145. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1146. ///
  1147. /// url.set_fragment(None);
  1148. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1149. /// assert!(url.fragment().is_none());
  1150. /// # Ok(())
  1151. /// # }
  1152. /// # run().unwrap();
  1153. /// ```
  1154. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  1155. // Remove any previous fragment
  1156. if let Some(start) = self.fragment_start {
  1157. debug_assert!(self.byte_at(start) == b'#');
  1158. self.serialization.truncate(start as usize);
  1159. }
  1160. // Write the new one
  1161. if let Some(input) = fragment {
  1162. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1163. self.serialization.push('#');
  1164. self.mutate(|parser| parser.parse_fragment(parser::Input::new(input)))
  1165. } else {
  1166. self.fragment_start = None
  1167. }
  1168. }
  1169. fn take_fragment(&mut self) -> Option<String> {
  1170. self.fragment_start.take().map(|start| {
  1171. debug_assert!(self.byte_at(start) == b'#');
  1172. let fragment = self.slice(start + 1..).to_owned();
  1173. self.serialization.truncate(start as usize);
  1174. fragment
  1175. })
  1176. }
  1177. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  1178. if let Some(ref fragment) = fragment {
  1179. assert!(self.fragment_start.is_none());
  1180. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1181. self.serialization.push('#');
  1182. self.serialization.push_str(fragment);
  1183. }
  1184. }
  1185. /// Change this URL’s query string.
  1186. ///
  1187. /// # Examples
  1188. ///
  1189. /// ```rust
  1190. /// use url::Url;
  1191. /// # use url::ParseError;
  1192. ///
  1193. /// # fn run() -> Result<(), ParseError> {
  1194. /// let mut url = Url::parse("https://example.com/products")?;
  1195. /// assert_eq!(url.as_str(), "https://example.com/products");
  1196. ///
  1197. /// url.set_query(Some("page=2"));
  1198. /// assert_eq!(url.as_str(), "https://example.com/products?page=2");
  1199. /// assert_eq!(url.query(), Some("page=2"));
  1200. /// # Ok(())
  1201. /// # }
  1202. /// # run().unwrap();
  1203. /// ```
  1204. pub fn set_query(&mut self, query: Option<&str>) {
  1205. let fragment = self.take_fragment();
  1206. // Remove any previous query
  1207. if let Some(start) = self.query_start.take() {
  1208. debug_assert!(self.byte_at(start) == b'?');
  1209. self.serialization.truncate(start as usize);
  1210. }
  1211. // Write the new query, if any
  1212. if let Some(input) = query {
  1213. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  1214. self.serialization.push('?');
  1215. let scheme_end = self.scheme_end;
  1216. self.mutate(|parser| parser.parse_query(scheme_end, parser::Input::new(input)));
  1217. }
  1218. self.restore_already_parsed_fragment(fragment);
  1219. }
  1220. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  1221. /// in `application/x-www-form-urlencoded` syntax.
  1222. ///
  1223. /// The return value has a method-chaining API:
  1224. ///
  1225. /// ```rust
  1226. /// # use url::{Url, ParseError};
  1227. ///
  1228. /// # fn run() -> Result<(), ParseError> {
  1229. /// let mut url = Url::parse("https://example.net?lang=fr#nav")?;
  1230. /// assert_eq!(url.query(), Some("lang=fr"));
  1231. ///
  1232. /// url.query_pairs_mut().append_pair("foo", "bar");
  1233. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  1234. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  1235. ///
  1236. /// url.query_pairs_mut()
  1237. /// .clear()
  1238. /// .append_pair("foo", "bar & baz")
  1239. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  1240. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  1241. /// assert_eq!(url.as_str(),
  1242. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  1243. /// # Ok(())
  1244. /// # }
  1245. /// # run().unwrap();
  1246. /// ```
  1247. ///
  1248. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  1249. /// not `url.set_query(None)`.
  1250. ///
  1251. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  1252. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<UrlQuery> {
  1253. let fragment = self.take_fragment();
  1254. let query_start;
  1255. if let Some(start) = self.query_start {
  1256. debug_assert!(self.byte_at(start) == b'?');
  1257. query_start = start as usize;
  1258. } else {
  1259. query_start = self.serialization.len();
  1260. self.query_start = Some(to_u32(query_start).unwrap());
  1261. self.serialization.push('?');
  1262. }
  1263. let query = UrlQuery { url: Some(self), fragment: fragment };
  1264. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  1265. }
  1266. fn take_after_path(&mut self) -> String {
  1267. match (self.query_start, self.fragment_start) {
  1268. (Some(i), _) | (None, Some(i)) => {
  1269. let after_path = self.slice(i..).to_owned();
  1270. self.serialization.truncate(i as usize);
  1271. after_path
  1272. },
  1273. (None, None) => String::new(),
  1274. }
  1275. }
  1276. /// Change this URL’s path.
  1277. ///
  1278. /// # Examples
  1279. ///
  1280. /// ```rust
  1281. /// use url::Url;
  1282. /// # use url::ParseError;
  1283. ///
  1284. /// # fn run() -> Result<(), ParseError> {
  1285. /// let mut url = Url::parse("https://example.com")?;
  1286. /// url.set_path("api/comments");
  1287. /// assert_eq!(url.as_str(), "https://example.com/api/comments");
  1288. /// assert_eq!(url.path(), "/api/comments");
  1289. ///
  1290. /// let mut url = Url::parse("https://example.com/api")?;
  1291. /// url.set_path("data/report.csv");
  1292. /// assert_eq!(url.as_str(), "https://example.com/data/report.csv");
  1293. /// assert_eq!(url.path(), "/data/report.csv");
  1294. /// # Ok(())
  1295. /// # }
  1296. /// # run().unwrap();
  1297. /// ```
  1298. pub fn set_path(&mut self, mut path: &str) {
  1299. let after_path = self.take_after_path();
  1300. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  1301. let cannot_be_a_base = self.cannot_be_a_base();
  1302. let scheme_type = SchemeType::from(self.scheme());
  1303. self.serialization.truncate(self.path_start as usize);
  1304. self.mutate(|parser| {
  1305. if cannot_be_a_base {
  1306. if path.starts_with('/') {
  1307. parser.serialization.push_str("%2F");
  1308. path = &path[1..];
  1309. }
  1310. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  1311. } else {
  1312. let mut has_host = true; // FIXME
  1313. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  1314. }
  1315. });
  1316. self.restore_after_path(old_after_path_pos, &after_path);
  1317. }
  1318. /// Return an object with methods to manipulate this URL’s path segments.
  1319. ///
  1320. /// Return `Err(())` if this URL is cannot-be-a-base.
  1321. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut, ()> {
  1322. if self.cannot_be_a_base() {
  1323. Err(())
  1324. } else {
  1325. Ok(path_segments::new(self))
  1326. }
  1327. }
  1328. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  1329. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  1330. let adjust = |index: &mut u32| {
  1331. *index -= old_after_path_position;
  1332. *index += new_after_path_position;
  1333. };
  1334. if let Some(ref mut index) = self.query_start { adjust(index) }
  1335. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1336. self.serialization.push_str(after_path)
  1337. }
  1338. /// Change this URL’s port number.
  1339. ///
  1340. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  1341. /// do nothing and return `Err`.
  1342. ///
  1343. /// # Examples
  1344. ///
  1345. /// ```
  1346. /// use url::Url;
  1347. /// # use std::error::Error;
  1348. ///
  1349. /// # fn run() -> Result<(), Box<Error>> {
  1350. /// let mut url = Url::parse("ssh://example.net:2048/")?;
  1351. ///
  1352. /// url.set_port(Some(4096)).map_err(|_| "cannot be base")?;
  1353. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  1354. ///
  1355. /// url.set_port(None).map_err(|_| "cannot be base")?;
  1356. /// assert_eq!(url.as_str(), "ssh://example.net/");
  1357. /// # Ok(())
  1358. /// # }
  1359. /// # run().unwrap();
  1360. /// ```
  1361. ///
  1362. /// Cannot set port for cannot-be-a-base URLs:
  1363. ///
  1364. /// ```
  1365. /// use url::Url;
  1366. /// # use url::ParseError;
  1367. ///
  1368. /// # fn run() -> Result<(), ParseError> {
  1369. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1370. ///
  1371. /// let result = url.set_port(Some(80));
  1372. /// assert!(result.is_err());
  1373. ///
  1374. /// let result = url.set_port(None);
  1375. /// assert!(result.is_err());
  1376. /// # Ok(())
  1377. /// # }
  1378. /// # run().unwrap();
  1379. /// ```
  1380. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  1381. // has_host implies !cannot_be_a_base
  1382. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1383. return Err(())
  1384. }
  1385. if port.is_some() && port == parser::default_port(self.scheme()) {
  1386. port = None
  1387. }
  1388. self.set_port_internal(port);
  1389. Ok(())
  1390. }
  1391. fn set_port_internal(&mut self, port: Option<u16>) {
  1392. match (self.port, port) {
  1393. (None, None) => {}
  1394. (Some(_), None) => {
  1395. self.serialization.drain(self.host_end as usize .. self.path_start as usize);
  1396. let offset = self.path_start - self.host_end;
  1397. self.path_start = self.host_end;
  1398. if let Some(ref mut index) = self.query_start { *index -= offset }
  1399. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1400. }
  1401. (Some(old), Some(new)) if old == new => {}
  1402. (_, Some(new)) => {
  1403. let path_and_after = self.slice(self.path_start..).to_owned();
  1404. self.serialization.truncate(self.host_end as usize);
  1405. write!(&mut self.serialization, ":{}", new).unwrap();
  1406. let old_path_start = self.path_start;
  1407. let new_path_start = to_u32(self.serialization.len()).unwrap();
  1408. self.path_start = new_path_start;
  1409. let adjust = |index: &mut u32| {
  1410. *index -= old_path_start;
  1411. *index += new_path_start;
  1412. };
  1413. if let Some(ref mut index) = self.query_start { adjust(index) }
  1414. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1415. self.serialization.push_str(&path_and_after);
  1416. }
  1417. }
  1418. self.port = port;
  1419. }
  1420. /// Change this URL’s host.
  1421. ///
  1422. /// Removing the host (calling this with `None`)
  1423. /// will also remove any username, password, and port number.
  1424. ///
  1425. /// # Examples
  1426. ///
  1427. /// Change host:
  1428. ///
  1429. /// ```
  1430. /// use url::Url;
  1431. /// # use url::ParseError;
  1432. ///
  1433. /// # fn run() -> Result<(), ParseError> {
  1434. /// let mut url = Url::parse("https://example.net")?;
  1435. /// let result = url.set_host(Some("rust-lang.org"));
  1436. /// assert!(result.is_ok());
  1437. /// assert_eq!(url.as_str(), "https://rust-lang.org/");
  1438. /// # Ok(())
  1439. /// # }
  1440. /// # run().unwrap();
  1441. /// ```
  1442. ///
  1443. /// Remove host:
  1444. ///
  1445. /// ```
  1446. /// use url::Url;
  1447. /// # use url::ParseError;
  1448. ///
  1449. /// # fn run() -> Result<(), ParseError> {
  1450. /// let mut url = Url::parse("foo://example.net")?;
  1451. /// let result = url.set_host(None);
  1452. /// assert!(result.is_ok());
  1453. /// assert_eq!(url.as_str(), "foo:/");
  1454. /// # Ok(())
  1455. /// # }
  1456. /// # run().unwrap();
  1457. /// ```
  1458. ///
  1459. /// Cannot remove host for 'special' schemes (e.g. `http`):
  1460. ///
  1461. /// ```
  1462. /// use url::Url;
  1463. /// # use url::ParseError;
  1464. ///
  1465. /// # fn run() -> Result<(), ParseError> {
  1466. /// let mut url = Url::parse("https://example.net")?;
  1467. /// let result = url.set_host(None);
  1468. /// assert!(result.is_err());
  1469. /// assert_eq!(url.as_str(), "https://example.net/");
  1470. /// # Ok(())
  1471. /// # }
  1472. /// # run().unwrap();
  1473. /// ```
  1474. ///
  1475. /// Cannot change or remove host for cannot-be-a-base URLs:
  1476. ///
  1477. /// ```
  1478. /// use url::Url;
  1479. /// # use url::ParseError;
  1480. ///
  1481. /// # fn run() -> Result<(), ParseError> {
  1482. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1483. ///
  1484. /// let result = url.set_host(Some("rust-lang.org"));
  1485. /// assert!(result.is_err());
  1486. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1487. ///
  1488. /// let result = url.set_host(None);
  1489. /// assert!(result.is_err());
  1490. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1491. /// # Ok(())
  1492. /// # }
  1493. /// # run().unwrap();
  1494. /// ```
  1495. ///
  1496. /// # Errors
  1497. ///
  1498. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  1499. /// a [`ParseError`] variant will be returned.
  1500. ///
  1501. /// [`ParseError`]: enum.ParseError.html
  1502. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  1503. if self.cannot_be_a_base() {
  1504. return Err(ParseError::SetHostOnCannotBeABaseUrl)
  1505. }
  1506. if let Some(host) = host {
  1507. if host == "" && SchemeType::from(self.scheme()).is_special() {
  1508. return Err(ParseError::EmptyHost);
  1509. }
  1510. if SchemeType::from(self.scheme()).is_special() {
  1511. self.set_host_internal(Host::parse(host)?, None)
  1512. } else {
  1513. self.set_host_internal(Host::parse_opaque(host)?, None)
  1514. }
  1515. } else if self.has_host() {
  1516. if SchemeType::from(self.scheme()).is_special() {
  1517. return Err(ParseError::EmptyHost)
  1518. }
  1519. debug_assert!(self.byte_at(self.scheme_end) == b':');
  1520. debug_assert!(self.byte_at(self.path_start) == b'/');
  1521. let new_path_start = self.scheme_end + 1;
  1522. self.serialization.drain(new_path_start as usize..self.path_start as usize);
  1523. let offset = self.path_start - new_path_start;
  1524. self.path_start = new_path_start;
  1525. self.username_end = new_path_start;
  1526. self.host_start = new_path_start;
  1527. self.host_end = new_path_start;
  1528. self.port = None;
  1529. if let Some(ref mut index) = self.query_start { *index -= offset }
  1530. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1531. }
  1532. Ok(())
  1533. }
  1534. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  1535. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  1536. let old_suffix_pos = if opt_new_port.is_some() { self.path_start } else { self.host_end };
  1537. let suffix = self.slice(old_suffix_pos..).to_owned();
  1538. self.serialization.truncate(self.host_start as usize);
  1539. if !self.has_authority() {
  1540. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  1541. debug_assert!(self.username_end == self.host_start);
  1542. self.serialization.push('/');
  1543. self.serialization.push('/');
  1544. self.username_end += 2;
  1545. self.host_start += 2;
  1546. }
  1547. write!(&mut self.serialization, "{}", host).unwrap();
  1548. self.host_end = to_u32(self.serialization.len()).unwrap();
  1549. self.host = host.into();
  1550. if let Some(new_port) = opt_new_port {
  1551. self.port = new_port;
  1552. if let Some(port) = new_port {
  1553. write!(&mut self.serialization, ":{}", port).unwrap();
  1554. }
  1555. }
  1556. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  1557. self.serialization.push_str(&suffix);
  1558. let adjust = |index: &mut u32| {
  1559. *index -= old_suffix_pos;
  1560. *index += new_suffix_pos;
  1561. };
  1562. adjust(&mut self.path_start);
  1563. if let Some(ref mut index) = self.query_start { adjust(index) }
  1564. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1565. }
  1566. /// Change this URL’s host to the given IP address.
  1567. ///
  1568. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1569. ///
  1570. /// Compared to `Url::set_host`, this skips the host parser.
  1571. ///
  1572. /// # Examples
  1573. ///
  1574. /// ```rust
  1575. /// use url::{Url, ParseError};
  1576. ///
  1577. /// # fn run() -> Result<(), ParseError> {
  1578. /// let mut url = Url::parse("http://example.com")?;
  1579. /// url.set_ip_host("127.0.0.1".parse().unwrap());
  1580. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  1581. /// assert_eq!(url.as_str(), "http://127.0.0.1/");
  1582. /// # Ok(())
  1583. /// # }
  1584. /// # run().unwrap();
  1585. /// ```
  1586. ///
  1587. /// Cannot change URL's from mailto(cannot-be-base) to ip:
  1588. ///
  1589. /// ```rust
  1590. /// use url::{Url, ParseError};
  1591. ///
  1592. /// # fn run() -> Result<(), ParseError> {
  1593. /// let mut url = Url::parse("mailto:rms@example.com")?;
  1594. /// let result = url.set_ip_host("127.0.0.1".parse().unwrap());
  1595. ///
  1596. /// assert_eq!(url.as_str(), "mailto:rms@example.com");
  1597. /// assert!(result.is_err());
  1598. /// # Ok(())
  1599. /// # }
  1600. /// # run().unwrap();
  1601. /// ```
  1602. ///
  1603. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1604. if self.cannot_be_a_base() {
  1605. return Err(())
  1606. }
  1607. let address = match address {
  1608. IpAddr::V4(address) => Host::Ipv4(address),
  1609. IpAddr::V6(address) => Host::Ipv6(address),
  1610. };
  1611. self.set_host_internal(address, None);
  1612. Ok(())
  1613. }
  1614. /// Change this URL’s password.
  1615. ///
  1616. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1617. ///
  1618. /// # Examples
  1619. ///
  1620. /// ```rust
  1621. /// use url::{Url, ParseError};
  1622. ///
  1623. /// # fn run() -> Result<(), ParseError> {
  1624. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1625. /// let result = url.set_password(Some("secret_password"));
  1626. /// assert!(result.is_err());
  1627. ///
  1628. /// let mut url = Url::parse("ftp://user1:secret1@example.com")?;
  1629. /// let result = url.set_password(Some("secret_password"));
  1630. /// assert_eq!(url.password(), Some("secret_password"));
  1631. ///
  1632. /// let mut url = Url::parse("ftp://user2:@example.com")?;
  1633. /// let result = url.set_password(Some("secret2"));
  1634. /// assert!(result.is_ok());
  1635. /// assert_eq!(url.password(), Some("secret2"));
  1636. /// # Ok(())
  1637. /// # }
  1638. /// # run().unwrap();
  1639. /// ```
  1640. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1641. // has_host implies !cannot_be_a_base
  1642. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1643. return Err(())
  1644. }
  1645. if let Some(password) = password {
  1646. let host_and_after = self.slice(self.host_start..).to_owned();
  1647. self.serialization.truncate(self.username_end as usize);
  1648. self.serialization.push(':');
  1649. self.serialization.extend(utf8_percent_encode(password, USERINFO_ENCODE_SET));
  1650. self.serialization.push('@');
  1651. let old_host_start = self.host_start;
  1652. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1653. let adjust = |index: &mut u32| {
  1654. *index -= old_host_start;
  1655. *index += new_host_start;
  1656. };
  1657. self.host_start = new_host_start;
  1658. adjust(&mut self.host_end);
  1659. adjust(&mut self.path_start);
  1660. if let Some(ref mut index) = self.query_start { adjust(index) }
  1661. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1662. self.serialization.push_str(&host_and_after);
  1663. } else if self.byte_at(self.username_end) == b':' { // If there is a password to remove
  1664. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1665. debug_assert!(has_username_or_password);
  1666. let username_start = self.scheme_end + 3;
  1667. let empty_username = username_start == self.username_end;
  1668. let start = self.username_end; // Remove the ':'
  1669. let end = if empty_username {
  1670. self.host_start // Remove the '@' as well
  1671. } else {
  1672. self.host_start - 1 // Keep the '@' to separate the username from the host
  1673. };
  1674. self.serialization.drain(start as usize .. end as usize);
  1675. let offset = end - start;
  1676. self.host_start -= offset;
  1677. self.host_end -= offset;
  1678. self.path_start -= offset;
  1679. if let Some(ref mut index) = self.query_start { *index -= offset }
  1680. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1681. }
  1682. Ok(())
  1683. }
  1684. /// Change this URL’s username.
  1685. ///
  1686. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1687. /// # Examples
  1688. ///
  1689. /// Cannot setup username from mailto(cannot-be-base)
  1690. ///
  1691. /// ```rust
  1692. /// use url::{Url, ParseError};
  1693. ///
  1694. /// # fn run() -> Result<(), ParseError> {
  1695. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1696. /// let result = url.set_username("user1");
  1697. /// assert_eq!(url.as_str(), "mailto:rmz@example.com");
  1698. /// assert!(result.is_err());
  1699. /// # Ok(())
  1700. /// # }
  1701. /// # run().unwrap();
  1702. /// ```
  1703. ///
  1704. /// Setup username to user1
  1705. ///
  1706. /// ```rust
  1707. /// use url::{Url, ParseError};
  1708. ///
  1709. /// # fn run() -> Result<(), ParseError> {
  1710. /// let mut url = Url::parse("ftp://:secre1@example.com/")?;
  1711. /// let result = url.set_username("user1");
  1712. /// assert!(result.is_ok());
  1713. /// assert_eq!(url.username(), "user1");
  1714. /// assert_eq!(url.as_str(), "ftp://user1:secre1@example.com/");
  1715. /// # Ok(())
  1716. /// # }
  1717. /// # run().unwrap();
  1718. /// ```
  1719. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1720. // has_host implies !cannot_be_a_base
  1721. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1722. return Err(())
  1723. }
  1724. let username_start = self.scheme_end + 3;
  1725. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  1726. if self.slice(username_start..self.username_end) == username {
  1727. return Ok(())
  1728. }
  1729. let after_username = self.slice(self.username_end..).to_owned();
  1730. self.serialization.truncate(username_start as usize);
  1731. self.serialization.extend(utf8_percent_encode(username, USERINFO_ENCODE_SET));
  1732. let mut removed_bytes = self.username_end;
  1733. self.username_end = to_u32(self.serialization.len()).unwrap();
  1734. let mut added_bytes = self.username_end;
  1735. let new_username_is_empty = self.username_end == username_start;
  1736. match (new_username_is_empty, after_username.chars().next()) {
  1737. (true, Some('@')) => {
  1738. removed_bytes += 1;
  1739. self.serialization.push_str(&after_username[1..]);
  1740. }
  1741. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  1742. self.serialization.push_str(&after_username);
  1743. }
  1744. (false, _) => {
  1745. added_bytes += 1;
  1746. self.serialization.push('@');
  1747. self.serialization.push_str(&after_username);
  1748. }
  1749. }
  1750. let adjust = |index: &mut u32| {
  1751. *index -= removed_bytes;
  1752. *index += added_bytes;
  1753. };
  1754. adjust(&mut self.host_start);
  1755. adjust(&mut self.host_end);
  1756. adjust(&mut self.path_start);
  1757. if let Some(ref mut index) = self.query_start { adjust(index) }
  1758. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1759. Ok(())
  1760. }
  1761. /// Change this URL’s scheme.
  1762. ///
  1763. /// Do nothing and return `Err` if:
  1764. ///
  1765. /// * The new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  1766. /// * This URL is cannot-be-a-base and the new scheme is one of
  1767. /// `http`, `https`, `ws`, `wss`, `ftp`, or `gopher`
  1768. ///
  1769. /// # Examples
  1770. ///
  1771. /// Change the URL’s scheme from `https` to `foo`:
  1772. ///
  1773. /// ```
  1774. /// use url::Url;
  1775. /// # use url::ParseError;
  1776. ///
  1777. /// # fn run() -> Result<(), ParseError> {
  1778. /// let mut url = Url::parse("https://example.net")?;
  1779. /// let result = url.set_scheme("foo");
  1780. /// assert_eq!(url.as_str(), "foo://example.net/");
  1781. /// assert!(result.is_ok());
  1782. /// # Ok(())
  1783. /// # }
  1784. /// # run().unwrap();
  1785. /// ```
  1786. ///
  1787. ///
  1788. /// Cannot change URL’s scheme from `https` to `foõ`:
  1789. ///
  1790. /// ```
  1791. /// use url::Url;
  1792. /// # use url::ParseError;
  1793. ///
  1794. /// # fn run() -> Result<(), ParseError> {
  1795. /// let mut url = Url::parse("https://example.net")?;
  1796. /// let result = url.set_scheme("foõ");
  1797. /// assert_eq!(url.as_str(), "https://example.net/");
  1798. /// assert!(result.is_err());
  1799. /// # Ok(())
  1800. /// # }
  1801. /// # run().unwrap();
  1802. /// ```
  1803. ///
  1804. /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
  1805. ///
  1806. /// ```
  1807. /// use url::Url;
  1808. /// # use url::ParseError;
  1809. ///
  1810. /// # fn run() -> Result<(), ParseError> {
  1811. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1812. /// let result = url.set_scheme("https");
  1813. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1814. /// assert!(result.is_err());
  1815. /// # Ok(())
  1816. /// # }
  1817. /// # run().unwrap();
  1818. /// ```
  1819. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  1820. let mut parser = Parser::for_setter(String::new());
  1821. let remaining = parser.parse_scheme(parser::Input::new(scheme))?;
  1822. if !remaining.is_empty() ||
  1823. (!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
  1824. return Err(())
  1825. }
  1826. let old_scheme_end = self.scheme_end;
  1827. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  1828. let adjust = |index: &mut u32| {
  1829. *index -= old_scheme_end;
  1830. *index += new_scheme_end;
  1831. };
  1832. self.scheme_end = new_scheme_end;
  1833. adjust(&mut self.username_end);
  1834. adjust(&mut self.host_start);
  1835. adjust(&mut self.host_end);
  1836. adjust(&mut self.path_start);
  1837. if let Some(ref mut index) = self.query_start { adjust(index) }
  1838. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1839. parser.serialization.push_str(self.slice(old_scheme_end..));
  1840. self.serialization = parser.serialization;
  1841. Ok(())
  1842. }
  1843. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  1844. ///
  1845. /// This returns `Err` if the given path is not absolute or,
  1846. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  1847. ///
  1848. /// # Examples
  1849. ///
  1850. /// On Unix-like platforms:
  1851. ///
  1852. /// ```
  1853. /// # if cfg!(unix) {
  1854. /// use url::Url;
  1855. ///
  1856. /// # fn run() -> Result<(), ()> {
  1857. /// let url = Url::from_file_path("/tmp/foo.txt")?;
  1858. /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
  1859. ///
  1860. /// let url = Url::from_file_path("../foo.txt");
  1861. /// assert!(url.is_err());
  1862. ///
  1863. /// let url = Url::from_file_path("https://google.com/");
  1864. /// assert!(url.is_err());
  1865. /// # Ok(())
  1866. /// # }
  1867. /// # run().unwrap();
  1868. /// # }
  1869. /// ```
  1870. #[cfg(any(unix, windows, target_os="redox"))]
  1871. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1872. let mut serialization = "file://".to_owned();
  1873. let host_start = serialization.len() as u32;
  1874. let (host_end, host) = path_to_file_url_segments(path.as_ref(), &mut serialization)?;
  1875. Ok(Url {
  1876. serialization: serialization,
  1877. scheme_end: "file".len() as u32,
  1878. username_end: host_start,
  1879. host_start: host_start,
  1880. host_end: host_end,
  1881. host: host,
  1882. port: None,
  1883. path_start: host_end,
  1884. query_start: None,
  1885. fragment_start: None,
  1886. })
  1887. }
  1888. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  1889. ///
  1890. /// This returns `Err` if the given path is not absolute or,
  1891. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  1892. ///
  1893. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  1894. /// so that the entire path is considered when using this URL as a base URL.
  1895. ///
  1896. /// For example:
  1897. ///
  1898. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  1899. /// as the base URL is `file:///var/www/index.html`
  1900. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  1901. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  1902. ///
  1903. /// Note that `std::path` does not consider trailing slashes significant
  1904. /// and usually does not include them (e.g. in `Path::parent()`).
  1905. #[cfg(any(unix, windows, target_os="redox"))]
  1906. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1907. let mut url = Url::from_file_path(path)?;
  1908. if !url.serialization.ends_with('/') {
  1909. url.serialization.push('/')
  1910. }
  1911. Ok(url)
  1912. }
  1913. /// Serialize with Serde using the internal representation of the `Url` struct.
  1914. ///
  1915. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  1916. /// for speed, compared to the `Deserialize` trait impl.
  1917. ///
  1918. /// This method is only available if the `serde` Cargo feature is enabled.
  1919. #[cfg(feature = "serde")]
  1920. #[deny(unused)]
  1921. pub fn serialize_internal<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  1922. use serde::Serialize;
  1923. // Destructuring first lets us ensure that adding or removing fields forces this method
  1924. // to be updated
  1925. let Url { ref serialization, ref scheme_end,
  1926. ref username_end, ref host_start,
  1927. ref host_end, ref host, ref port,
  1928. ref path_start, ref query_start,
  1929. ref fragment_start} = *self;
  1930. (serialization, scheme_end, username_end,
  1931. host_start, host_end, host, port, path_start,
  1932. query_start, fragment_start).serialize(serializer)
  1933. }
  1934. /// Serialize with Serde using the internal representation of the `Url` struct.
  1935. ///
  1936. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  1937. /// for speed, compared to the `Deserialize` trait impl.
  1938. ///
  1939. /// This method is only available if the `serde` Cargo feature is enabled.
  1940. #[cfg(feature = "serde")]
  1941. #[deny(unused)]
  1942. pub fn deserialize_internal<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: serde::Deserializer {
  1943. use serde::{Deserialize, Error};
  1944. let (serialization, scheme_end, username_end,
  1945. host_start, host_end, host, port, path_start,
  1946. query_start, fragment_start) = Deserialize::deserialize(deserializer)?;
  1947. let url = Url {
  1948. serialization: serialization,
  1949. scheme_end: scheme_end,
  1950. username_end: username_end,
  1951. host_start: host_start,
  1952. host_end: host_end,
  1953. host: host,
  1954. port: port,
  1955. path_start: path_start,
  1956. query_start: query_start,
  1957. fragment_start: fragment_start
  1958. };
  1959. if cfg!(debug_assertions) {
  1960. url.check_invariants().map_err(|ref reason| Error::invalid_value(&reason))?
  1961. }
  1962. Ok(url)
  1963. }
  1964. /// Assuming the URL is in the `file` scheme or similar,
  1965. /// convert its path to an absolute `std::path::Path`.
  1966. ///
  1967. /// **Note:** This does not actually check the URL’s `scheme`,
  1968. /// and may give nonsensical results for other schemes.
  1969. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  1970. ///
  1971. /// ```
  1972. /// # use url::Url;
  1973. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  1974. /// let path = url.to_file_path();
  1975. /// ```
  1976. ///
  1977. /// Returns `Err` if the host is neither empty nor `"localhost"` (except on Windows, where
  1978. /// `file:` URLs may have a non-local host),
  1979. /// or if `Path::new_opt()` returns `None`.
  1980. /// (That is, if the percent-decoded path contains a NUL byte or,
  1981. /// for a Windows path, is not UTF-8.)
  1982. #[inline]
  1983. #[cfg(any(unix, windows, target_os="redox"))]
  1984. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  1985. if let Some(segments) = self.path_segments() {
  1986. let host = match self.host() {
  1987. None | Some(Host::Domain("localhost")) => None,
  1988. Some(_) if cfg!(windows) && self.scheme() == "file" => {
  1989. Some(&self.serialization[self.host_start as usize .. self.host_end as usize])
  1990. },
  1991. _ => return Err(())
  1992. };
  1993. return file_url_segments_to_pathbuf(host, segments);
  1994. }
  1995. Err(())
  1996. }
  1997. // Private helper methods:
  1998. #[inline]
  1999. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  2000. range.slice_of(&self.serialization)
  2001. }
  2002. #[inline]
  2003. fn byte_at(&self, i: u32) -> u8 {
  2004. self.serialization.as_bytes()[i as usize]
  2005. }
  2006. }
  2007. /// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
  2008. impl ToSocketAddrs for Url {
  2009. type Iter = SocketAddrs;
  2010. fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
  2011. self.with_default_port(|_| Err(()))?.to_socket_addrs()
  2012. }
  2013. }
  2014. /// Parse a string as an URL, without a base URL or encoding override.
  2015. impl str::FromStr for Url {
  2016. type Err = ParseError;
  2017. #[inline]
  2018. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  2019. Url::parse(input)
  2020. }
  2021. }
  2022. /// Display the serialization of this URL.
  2023. impl fmt::Display for Url {
  2024. #[inline]
  2025. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2026. fmt::Display::fmt(&self.serialization, formatter)
  2027. }
  2028. }
  2029. /// Debug the serialization of this URL.
  2030. impl fmt::Debug for Url {
  2031. #[inline]
  2032. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2033. fmt::Debug::fmt(&self.serialization, formatter)
  2034. }
  2035. }
  2036. /// URLs compare like their serialization.
  2037. impl Eq for Url {}
  2038. /// URLs compare like their serialization.
  2039. impl PartialEq for Url {
  2040. #[inline]
  2041. fn eq(&self, other: &Self) -> bool {
  2042. self.serialization == other.serialization
  2043. }
  2044. }
  2045. /// URLs compare like their serialization.
  2046. impl Ord for Url {
  2047. #[inline]
  2048. fn cmp(&self, other: &Self) -> cmp::Ordering {
  2049. self.serialization.cmp(&other.serialization)
  2050. }
  2051. }
  2052. /// URLs compare like their serialization.
  2053. impl PartialOrd for Url {
  2054. #[inline]
  2055. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  2056. self.serialization.partial_cmp(&other.serialization)
  2057. }
  2058. }
  2059. /// URLs hash like their serialization.
  2060. impl hash::Hash for Url {
  2061. #[inline]
  2062. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  2063. hash::Hash::hash(&self.serialization, state)
  2064. }
  2065. }
  2066. /// Return the serialization of this URL.
  2067. impl AsRef<str> for Url {
  2068. #[inline]
  2069. fn as_ref(&self) -> &str {
  2070. &self.serialization
  2071. }
  2072. }
  2073. trait RangeArg {
  2074. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  2075. }
  2076. impl RangeArg for Range<u32> {
  2077. #[inline]
  2078. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2079. &s[self.start as usize .. self.end as usize]
  2080. }
  2081. }
  2082. impl RangeArg for RangeFrom<u32> {
  2083. #[inline]
  2084. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2085. &s[self.start as usize ..]
  2086. }
  2087. }
  2088. impl RangeArg for RangeTo<u32> {
  2089. #[inline]
  2090. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2091. &s[.. self.end as usize]
  2092. }
  2093. }
  2094. #[cfg(feature="rustc-serialize")]
  2095. impl rustc_serialize::Encodable for Url {
  2096. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  2097. encoder.emit_str(self.as_str())
  2098. }
  2099. }
  2100. #[cfg(feature="rustc-serialize")]
  2101. impl rustc_serialize::Decodable for Url {
  2102. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  2103. Url::parse(&*decoder.read_str()?).map_err(|error| {
  2104. decoder.error(&format!("URL parsing error: {}", error))
  2105. })
  2106. }
  2107. }
  2108. /// Serializes this URL into a `serde` stream.
  2109. ///
  2110. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2111. #[cfg(feature="serde")]
  2112. impl serde::Serialize for Url {
  2113. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  2114. serializer.serialize_str(self.as_str())
  2115. }
  2116. }
  2117. /// Deserializes this URL from a `serde` stream.
  2118. ///
  2119. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2120. #[cfg(feature="serde")]
  2121. impl serde::Deserialize for Url {
  2122. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  2123. let string_representation: String = serde::Deserialize::deserialize(deserializer)?;
  2124. Url::parse(&string_representation).map_err(|err| {
  2125. serde::Error::invalid_value(err.description())
  2126. })
  2127. }
  2128. }
  2129. #[cfg(any(unix, target_os = "redox"))]
  2130. fn path_to_file_url_segments(path: &Path, serialization: &mut String)
  2131. -> Result<(u32, HostInternal), ()> {
  2132. use std::os::unix::prelude::OsStrExt;
  2133. if !path.is_absolute() {
  2134. return Err(())
  2135. }
  2136. let host_end = to_u32(serialization.len()).unwrap();
  2137. let mut empty = true;
  2138. // skip the root component
  2139. for component in path.components().skip(1) {
  2140. empty = false;
  2141. serialization.push('/');
  2142. serialization.extend(percent_encode(
  2143. component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET));
  2144. }
  2145. if empty {
  2146. // An URL’s path must not be empty.
  2147. serialization.push('/');
  2148. }
  2149. Ok((host_end, HostInternal::None))
  2150. }
  2151. #[cfg(windows)]
  2152. fn path_to_file_url_segments(path: &Path, serialization: &mut String)
  2153. -> Result<(u32, HostInternal), ()> {
  2154. path_to_file_url_segments_windows(path, serialization)
  2155. }
  2156. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2157. #[cfg_attr(not(windows), allow(dead_code))]
  2158. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String)
  2159. -> Result<(u32, HostInternal), ()> {
  2160. use std::path::{Prefix, Component};
  2161. if !path.is_absolute() {
  2162. return Err(())
  2163. }
  2164. let mut components = path.components();
  2165. let host_end;
  2166. let host_internal;
  2167. match components.next() {
  2168. Some(Component::Prefix(ref p)) => match p.kind() {
  2169. Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
  2170. host_end = to_u32(serialization.len()).unwrap();
  2171. host_internal = HostInternal::None;
  2172. serialization.push('/');
  2173. serialization.push(letter as char);
  2174. serialization.push(':');
  2175. },
  2176. Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
  2177. let host = Host::parse(server.to_str().ok_or(())?).map_err(|_| ())?;
  2178. write!(serialization, "{}", host).unwrap();
  2179. host_end = to_u32(serialization.len()).unwrap();
  2180. host_internal = host.into();
  2181. serialization.push('/');
  2182. let share = share.to_str().ok_or(())?;
  2183. serialization.extend(percent_encode(share.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  2184. },
  2185. _ => return Err(())
  2186. },
  2187. _ => return Err(())
  2188. }
  2189. for component in components {
  2190. if component == Component::RootDir { continue }
  2191. // FIXME: somehow work with non-unicode?
  2192. let component = component.as_os_str().to_str().ok_or(())?;
  2193. serialization.push('/');
  2194. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  2195. }
  2196. Ok((host_end, host_internal))
  2197. }
  2198. #[cfg(any(unix, target_os = "redox"))]
  2199. fn file_url_segments_to_pathbuf(host: Option<&str>, segments: str::Split<char>) -> Result<PathBuf, ()> {
  2200. use std::ffi::OsStr;
  2201. use std::os::unix::prelude::OsStrExt;
  2202. use std::path::PathBuf;
  2203. if host.is_some() {
  2204. return Err(());
  2205. }
  2206. let mut bytes = if cfg!(target_os = "redox") {
  2207. b"file:".to_vec()
  2208. } else {
  2209. Vec::new()
  2210. };
  2211. for segment in segments {
  2212. bytes.push(b'/');
  2213. bytes.extend(percent_decode(segment.as_bytes()));
  2214. }
  2215. let os_str = OsStr::from_bytes(&bytes);
  2216. let path = PathBuf::from(os_str);
  2217. debug_assert!(path.is_absolute(),
  2218. "to_file_path() failed to produce an absolute Path");
  2219. Ok(path)
  2220. }
  2221. #[cfg(windows)]
  2222. fn file_url_segments_to_pathbuf(host: Option<&str>, segments: str::Split<char>) -> Result<PathBuf, ()> {
  2223. file_url_segments_to_pathbuf_windows(host, segments)
  2224. }
  2225. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2226. #[cfg_attr(not(windows), allow(dead_code))]
  2227. fn file_url_segments_to_pathbuf_windows(host: Option<&str>, mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  2228. let mut string = if let Some(host) = host {
  2229. r"\\".to_owned() + host
  2230. } else {
  2231. let first = segments.next().ok_or(())?;
  2232. match first.len() {
  2233. 2 => {
  2234. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  2235. return Err(())
  2236. }
  2237. first.to_owned()
  2238. },
  2239. 4 => {
  2240. if !first.starts_with(parser::ascii_alpha) {
  2241. return Err(())
  2242. }
  2243. let bytes = first.as_bytes();
  2244. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  2245. return Err(())
  2246. }
  2247. first[0..1].to_owned() + ":"
  2248. },
  2249. _ => return Err(()),
  2250. }
  2251. };
  2252. for segment in segments {
  2253. string.push('\\');
  2254. // Currently non-unicode windows paths cannot be represented
  2255. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  2256. Ok(s) => string.push_str(&s),
  2257. Err(..) => return Err(()),
  2258. }
  2259. }
  2260. let path = PathBuf::from(string);
  2261. debug_assert!(path.is_absolute(),
  2262. "to_file_path() failed to produce an absolute Path");
  2263. Ok(path)
  2264. }
  2265. fn io_error<T>(reason: &str) -> io::Result<T> {
  2266. Err(io::Error::new(io::ErrorKind::InvalidData, reason))
  2267. }
  2268. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  2269. #[derive(Debug)]
  2270. pub struct UrlQuery<'a> {
  2271. url: Option<&'a mut Url>,
  2272. fragment: Option<String>,
  2273. }
  2274. impl<'a> Drop for UrlQuery<'a> {
  2275. fn drop(&mut self) {
  2276. if let Some(url) = self.url.take() {
  2277. url.restore_already_parsed_fragment(self.fragment.take())
  2278. }
  2279. }
  2280. }
  2281. /// Define a new struct
  2282. /// that implements the [`EncodeSet`](percent_encoding/trait.EncodeSet.html) trait,
  2283. /// for use in [`percent_decode()`](percent_encoding/fn.percent_encode.html)
  2284. /// and related functions.
  2285. ///
  2286. /// Parameters are characters to include in the set in addition to those of the base set.
  2287. /// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set).
  2288. ///
  2289. /// Example
  2290. /// =======
  2291. ///
  2292. /// ```rust
  2293. /// #[macro_use] extern crate url;
  2294. /// use url::percent_encoding::{utf8_percent_encode, SIMPLE_ENCODE_SET};
  2295. /// define_encode_set! {
  2296. /// /// This encode set is used in the URL parser for query strings.
  2297. /// pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'}
  2298. /// }
  2299. /// # fn main() {
  2300. /// assert_eq!(utf8_percent_encode("foo bar", QUERY_ENCODE_SET).collect::<String>(), "foo%20bar");
  2301. /// # }
  2302. /// ```
  2303. #[macro_export]
  2304. macro_rules! define_encode_set {
  2305. ($(#[$attr: meta])* pub $name: ident = [$base_set: expr] | {$($ch: pat),*}) => {
  2306. $(#[$attr])*
  2307. #[derive(Copy, Clone)]
  2308. #[allow(non_camel_case_types)]
  2309. pub struct $name;
  2310. impl $crate::percent_encoding::EncodeSet for $name {
  2311. #[inline]
  2312. fn contains(&self, byte: u8) -> bool {
  2313. match byte as char {
  2314. $(
  2315. $ch => true,
  2316. )*
  2317. _ => $base_set.contains(byte)
  2318. }
  2319. }
  2320. }
  2321. }
  2322. }