]> git.lizzy.rs Git - rust.git/blob - src/liburl/lib.rs
auto merge of #17654 : gereeter/rust/no-unnecessary-cell, r=alexcrichton
[rust.git] / src / liburl / lib.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Types/fns concerning URLs (see RFC 3986)
12
13 #![crate_name = "url"]
14 #![deprecated="This is being removed. Use rust-url instead. http://servo.github.io/rust-url/"]
15 #![allow(deprecated)]
16 #![crate_type = "rlib"]
17 #![crate_type = "dylib"]
18 #![license = "MIT/ASL2"]
19 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
20        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
21        html_root_url = "http://doc.rust-lang.org/master/",
22        html_playground_url = "http://play.rust-lang.org/")]
23 #![feature(default_type_params)]
24
25 use std::collections::HashMap;
26 use std::collections::hashmap::{Occupied, Vacant};
27 use std::fmt;
28 use std::from_str::FromStr;
29 use std::hash;
30 use std::uint;
31 use std::path::BytesContainer;
32
33 /// A Uniform Resource Locator (URL).  A URL is a form of URI (Uniform Resource
34 /// Identifier) that includes network location information, such as hostname or
35 /// port number.
36 ///
37 /// # Example
38 ///
39 /// ```rust
40 /// # #![allow(deprecated)]
41 /// use url::Url;
42 ///
43 /// let raw = "https://username@example.com:8080/foo/bar?baz=qux#quz";
44 /// match Url::parse(raw) {
45 ///     Ok(u) => println!("Parsed '{}'", u),
46 ///     Err(e) => println!("Couldn't parse '{}': {}", raw, e),
47 /// }
48 /// ```
49 #[deriving(Clone, PartialEq, Eq)]
50 pub struct Url {
51     /// The scheme part of a URL, such as `https` in the above example.
52     pub scheme: String,
53     /// A URL subcomponent for user authentication.  `username` in the above example.
54     pub user: Option<UserInfo>,
55     /// A domain name or IP address.  For example, `example.com`.
56     pub host: String,
57     /// A TCP port number, for example `8080`.
58     pub port: Option<u16>,
59     /// The path component of a URL, for example `/foo/bar?baz=qux#quz`.
60     pub path: Path,
61 }
62
63 #[deriving(Clone, PartialEq, Eq)]
64 pub struct Path {
65     /// The path component of a URL, for example `/foo/bar`.
66     pub path: String,
67     /// The query component of a URL.
68     /// `vec![("baz".to_string(), "qux".to_string())]` represents the fragment
69     /// `baz=qux` in the above example.
70     pub query: Query,
71     /// The fragment component, such as `quz`. Not including the leading `#` character.
72     pub fragment: Option<String>
73 }
74
75 /// An optional subcomponent of a URI authority component.
76 #[deriving(Clone, PartialEq, Eq)]
77 pub struct UserInfo {
78     /// The user name.
79     pub user: String,
80     /// Password or other scheme-specific authentication information.
81     pub pass: Option<String>
82 }
83
84 /// Represents the query component of a URI.
85 pub type Query = Vec<(String, String)>;
86
87 impl Url {
88     pub fn new(scheme: String,
89                user: Option<UserInfo>,
90                host: String,
91                port: Option<u16>,
92                path: String,
93                query: Query,
94                fragment: Option<String>)
95                -> Url {
96         Url {
97             scheme: scheme,
98             user: user,
99             host: host,
100             port: port,
101             path: Path::new(path, query, fragment)
102         }
103     }
104
105     /// Parses a URL, converting it from a string to a `Url` representation.
106     ///
107     /// # Arguments
108     /// * rawurl - a string representing the full URL, including scheme.
109     ///
110     /// # Return value
111     ///
112     /// `Err(e)` if the string did not represent a valid URL, where `e` is a
113     /// `String` error message. Otherwise, `Ok(u)` where `u` is a `Url` struct
114     /// representing the URL.
115     pub fn parse(rawurl: &str) -> DecodeResult<Url> {
116         // scheme
117         let (scheme, rest) = try!(get_scheme(rawurl));
118
119         // authority
120         let (userinfo, host, port, rest) = try!(get_authority(rest));
121
122         // path
123         let has_authority = host.len() > 0;
124         let (path, rest) = try!(get_path(rest, has_authority));
125
126         // query and fragment
127         let (query, fragment) = try!(get_query_fragment(rest));
128
129         let url = Url::new(scheme.to_string(),
130                             userinfo,
131                             host.to_string(),
132                             port,
133                             path,
134                             query,
135                             fragment);
136         Ok(url)
137     }
138 }
139
140 #[deprecated="use `Url::parse`"]
141 pub fn from_str(s: &str) -> Result<Url, String> {
142     Url::parse(s)
143 }
144
145 impl Path {
146     pub fn new(path: String,
147                query: Query,
148                fragment: Option<String>)
149                -> Path {
150         Path {
151             path: path,
152             query: query,
153             fragment: fragment,
154         }
155     }
156
157     /// Parses a URL path, converting it from a string to a `Path` representation.
158     ///
159     /// # Arguments
160     /// * rawpath - a string representing the path component of a URL.
161     ///
162     /// # Return value
163     ///
164     /// `Err(e)` if the string did not represent a valid URL path, where `e` is a
165     /// `String` error message. Otherwise, `Ok(p)` where `p` is a `Path` struct
166     /// representing the URL path.
167     pub fn parse(rawpath: &str) -> DecodeResult<Path> {
168         let (path, rest) = try!(get_path(rawpath, false));
169
170         // query and fragment
171         let (query, fragment) = try!(get_query_fragment(rest.as_slice()));
172
173         Ok(Path{ path: path, query: query, fragment: fragment })
174     }
175 }
176
177 #[deprecated="use `Path::parse`"]
178 pub fn path_from_str(s: &str) -> Result<Path, String> {
179     Path::parse(s)
180 }
181
182 impl UserInfo {
183     #[inline]
184     pub fn new(user: String, pass: Option<String>) -> UserInfo {
185         UserInfo { user: user, pass: pass }
186     }
187 }
188
189 fn encode_inner<T: BytesContainer>(c: T, full_url: bool) -> String {
190     c.container_as_bytes().iter().fold(String::new(), |mut out, &b| {
191         match b as char {
192             // unreserved:
193             'A' ... 'Z'
194             | 'a' ... 'z'
195             | '0' ... '9'
196             | '-' | '.' | '_' | '~' => out.push_char(b as char),
197
198             // gen-delims:
199             ':' | '/' | '?' | '#' | '[' | ']' | '@' |
200             // sub-delims:
201             '!' | '$' | '&' | '"' | '(' | ')' | '*' |
202             '+' | ',' | ';' | '='
203                 if full_url => out.push_char(b as char),
204
205             ch => out.push_str(format!("%{:02X}", ch as uint).as_slice()),
206         };
207
208         out
209     })
210 }
211
212 /// Encodes a URI by replacing reserved characters with percent-encoded
213 /// character sequences.
214 ///
215 /// This function is compliant with RFC 3986.
216 ///
217 /// # Example
218 ///
219 /// ```rust
220 /// # #![allow(deprecated)]
221 /// use url::encode;
222 ///
223 /// let url = encode("https://example.com/Rust (programming language)");
224 /// println!("{}", url); // https://example.com/Rust%20(programming%20language)
225 /// ```
226 pub fn encode<T: BytesContainer>(container: T) -> String {
227     encode_inner(container, true)
228 }
229
230
231 /// Encodes a URI component by replacing reserved characters with percent-
232 /// encoded character sequences.
233 ///
234 /// This function is compliant with RFC 3986.
235 pub fn encode_component<T: BytesContainer>(container: T) -> String {
236     encode_inner(container, false)
237 }
238
239 pub type DecodeResult<T> = Result<T, String>;
240
241 /// Decodes a percent-encoded string representing a URI.
242 ///
243 /// This will only decode escape sequences generated by `encode`.
244 ///
245 /// # Example
246 ///
247 /// ```rust
248 /// # #![allow(deprecated)]
249 /// use url::decode;
250 ///
251 /// let url = decode("https://example.com/Rust%20(programming%20language)");
252 /// println!("{}", url); // https://example.com/Rust (programming language)
253 /// ```
254 pub fn decode<T: BytesContainer>(container: T) -> DecodeResult<String> {
255     decode_inner(container, true)
256 }
257
258 /// Decode a string encoded with percent encoding.
259 pub fn decode_component<T: BytesContainer>(container: T) -> DecodeResult<String> {
260     decode_inner(container, false)
261 }
262
263 fn decode_inner<T: BytesContainer>(c: T, full_url: bool) -> DecodeResult<String> {
264     let mut out = String::new();
265     let mut iter = c.container_as_bytes().iter().map(|&b| b);
266
267     loop {
268         match iter.next() {
269             Some(b) => match b as char {
270                 '%' => {
271                     let bytes = match (iter.next(), iter.next()) {
272                         (Some(one), Some(two)) => [one as u8, two as u8],
273                         _ => return Err(format!("Malformed input: found '%' \
274                                                 without two trailing bytes")),
275                     };
276
277                     // Only decode some characters if full_url:
278                     match uint::parse_bytes(bytes, 16u).unwrap() as u8 as char {
279                         // gen-delims:
280                         ':' | '/' | '?' | '#' | '[' | ']' | '@' |
281
282                         // sub-delims:
283                         '!' | '$' | '&' | '"' | '(' | ')' | '*' |
284                         '+' | ',' | ';' | '='
285                             if full_url => {
286                             out.push_char('%');
287                             out.push_char(bytes[0u] as char);
288                             out.push_char(bytes[1u] as char);
289                         }
290
291                         ch => out.push_char(ch)
292                     }
293                 }
294                 ch => out.push_char(ch)
295             },
296             None => return Ok(out),
297         }
298     }
299 }
300
301 /// Encode a hashmap to the 'application/x-www-form-urlencoded' media type.
302 pub fn encode_form_urlencoded(m: &HashMap<String, Vec<String>>) -> String {
303     fn encode_plus<T: Str>(s: &T) -> String {
304         s.as_slice().bytes().fold(String::new(), |mut out, b| {
305             match b as char {
306               'A' ... 'Z'
307               | 'a' ... 'z'
308               | '0' ... '9'
309               | '_' | '.' | '-' => out.push_char(b as char),
310               ' ' => out.push_char('+'),
311               ch => out.push_str(format!("%{:X}", ch as uint).as_slice())
312             }
313
314             out
315         })
316     }
317
318     let mut first = true;
319     m.iter().fold(String::new(), |mut out, (key, values)| {
320         let key = encode_plus(key);
321
322         for value in values.iter() {
323             if first {
324                 first = false;
325             } else {
326                 out.push_char('&');
327             }
328
329             out.push_str(key.as_slice());
330             out.push_char('=');
331             out.push_str(encode_plus(value).as_slice());
332         }
333
334         out
335     })
336 }
337
338 /// Decode a string encoded with the 'application/x-www-form-urlencoded' media
339 /// type into a hashmap.
340 pub fn decode_form_urlencoded(s: &[u8])
341                             -> DecodeResult<HashMap<String, Vec<String>>> {
342     fn maybe_push_value(map: &mut HashMap<String, Vec<String>>,
343                         key: String,
344                         value: String) {
345         if key.len() > 0 && value.len() > 0 {
346             match map.entry(key) {
347                 Vacant(entry) => { entry.set(vec![value]); },
348                 Occupied(mut entry) => { entry.get_mut().push(value); },
349             }
350         }
351     }
352
353     let mut out = HashMap::new();
354     let mut iter = s.iter().map(|&x| x);
355
356     let mut key = String::new();
357     let mut value = String::new();
358     let mut parsing_key = true;
359
360     loop {
361         match iter.next() {
362             Some(b) => match b as char {
363                 '&' | ';' => {
364                     maybe_push_value(&mut out, key, value);
365
366                     parsing_key = true;
367                     key = String::new();
368                     value = String::new();
369                 }
370                 '=' => parsing_key = false,
371                 ch => {
372                     let ch = match ch {
373                         '%' => {
374                             let bytes = match (iter.next(), iter.next()) {
375                                 (Some(one), Some(two)) => [one as u8, two as u8],
376                                 _ => return Err(format!("Malformed input: found \
377                                                 '%' without two trailing bytes"))
378                             };
379
380                             uint::parse_bytes(bytes, 16u).unwrap() as u8 as char
381                         }
382                         '+' => ' ',
383                         ch => ch
384                     };
385
386                     if parsing_key {
387                         key.push_char(ch)
388                     } else {
389                         value.push_char(ch)
390                     }
391                 }
392             },
393             None => {
394                 maybe_push_value(&mut out, key, value);
395                 return Ok(out)
396             }
397         }
398     }
399 }
400
401 fn split_char_first(s: &str, c: char) -> (&str, &str) {
402     let mut iter = s.splitn(1, c);
403
404     match (iter.next(), iter.next()) {
405         (Some(a), Some(b)) => (a, b),
406         (Some(a), None) => (a, ""),
407         (None, _) => unreachable!(),
408     }
409 }
410
411 impl fmt::Show for UserInfo {
412     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
413         match self.pass {
414             Some(ref pass) => write!(f, "{}:{}@", self.user, *pass),
415             None => write!(f, "{}@", self.user),
416         }
417     }
418 }
419
420 fn query_from_str(rawquery: &str) -> DecodeResult<Query> {
421     let mut query: Query = vec!();
422     if !rawquery.is_empty() {
423         for p in rawquery.split('&') {
424             let (k, v) = split_char_first(p, '=');
425             query.push((try!(decode_component(k)),
426                         try!(decode_component(v))));
427         }
428     }
429
430     Ok(query)
431 }
432
433 /// Converts an instance of a URI `Query` type to a string.
434 ///
435 /// # Example
436 ///
437 /// ```rust
438 /// # #![allow(deprecated)]
439 /// let query = vec![("title".to_string(), "The Village".to_string()),
440 ///                  ("north".to_string(), "52.91".to_string()),
441 ///                  ("west".to_string(), "4.10".to_string())];
442 /// println!("{}", url::query_to_str(&query));  // title=The%20Village&north=52.91&west=4.10
443 /// ```
444 pub fn query_to_str(query: &Query) -> String {
445     query.iter().enumerate().fold(String::new(), |mut out, (i, &(ref k, ref v))| {
446         if i != 0 {
447             out.push_char('&');
448         }
449
450         out.push_str(encode_component(k.as_slice()).as_slice());
451         out.push_char('=');
452         out.push_str(encode_component(v.as_slice()).as_slice());
453         out
454     })
455 }
456
457 /// Returns a tuple of the URI scheme and the rest of the URI, or a parsing error.
458 ///
459 /// Does not include the separating `:` character.
460 ///
461 /// # Example
462 ///
463 /// ```rust
464 /// # #![allow(deprecated)]
465 /// use url::get_scheme;
466 ///
467 /// let scheme = match get_scheme("https://example.com/") {
468 ///     Ok((sch, _)) => sch,
469 ///     Err(_) => "(None)",
470 /// };
471 /// println!("Scheme in use: {}.", scheme); // Scheme in use: https.
472 /// ```
473 pub fn get_scheme(rawurl: &str) -> DecodeResult<(&str, &str)> {
474     for (i,c) in rawurl.chars().enumerate() {
475         let result = match c {
476             'A' ... 'Z'
477             | 'a' ... 'z' => continue,
478             '0' ... '9' | '+' | '-' | '.' => {
479                 if i != 0 { continue }
480
481                 Err("url: Scheme must begin with a letter.".to_string())
482             }
483             ':' => {
484                 if i == 0 {
485                     Err("url: Scheme cannot be empty.".to_string())
486                 } else {
487                     Ok((rawurl.slice(0,i), rawurl.slice(i+1,rawurl.len())))
488                 }
489             }
490             _ => Err("url: Invalid character in scheme.".to_string()),
491         };
492
493         return result;
494     }
495
496     Err("url: Scheme must be terminated with a colon.".to_string())
497 }
498
499 // returns userinfo, host, port, and unparsed part, or an error
500 fn get_authority(rawurl: &str) ->
501     DecodeResult<(Option<UserInfo>, &str, Option<u16>, &str)> {
502     enum State {
503         Start, // starting state
504         PassHostPort, // could be in user or port
505         Ip6Port, // either in ipv6 host or port
506         Ip6Host, // are in an ipv6 host
507         InHost, // are in a host - may be ipv6, but don't know yet
508         InPort // are in port
509     }
510
511     #[deriving(Clone, PartialEq)]
512     enum Input {
513         Digit, // all digits
514         Hex, // digits and letters a-f
515         Unreserved // all other legal characters
516     }
517
518     if !rawurl.starts_with("//") {
519         // there is no authority.
520         return Ok((None, "", None, rawurl));
521     }
522
523     let len = rawurl.len();
524     let mut st = Start;
525     let mut input = Digit; // most restricted, start here.
526
527     let mut userinfo = None;
528     let mut host = "";
529     let mut port = None;
530
531     let mut colon_count = 0u;
532     let mut pos = 0;
533     let mut begin = 2;
534     let mut end = len;
535
536     for (i,c) in rawurl.chars().enumerate()
537                                // ignore the leading '//' handled by early return
538                                .skip(2) {
539         // deal with input class first
540         match c {
541             '0' ... '9' => (),
542             'A' ... 'F'
543             | 'a' ... 'f' => {
544                 if input == Digit {
545                     input = Hex;
546                 }
547             }
548             'G' ... 'Z'
549             | 'g' ... 'z'
550             | '-' | '.' | '_' | '~' | '%'
551             | '&' |'\'' | '(' | ')' | '+'
552             | '!' | '*' | ',' | ';' | '=' => input = Unreserved,
553             ':' | '@' | '?' | '#' | '/' => {
554                 // separators, don't change anything
555             }
556             _ => return Err("Illegal character in authority".to_string()),
557         }
558
559         // now process states
560         match c {
561           ':' => {
562             colon_count += 1;
563             match st {
564               Start => {
565                 pos = i;
566                 st = PassHostPort;
567               }
568               PassHostPort => {
569                 // multiple colons means ipv6 address.
570                 if input == Unreserved {
571                     return Err(
572                         "Illegal characters in IPv6 address.".to_string());
573                 }
574                 st = Ip6Host;
575               }
576               InHost => {
577                 pos = i;
578                 if input == Unreserved {
579                     // must be port
580                     host = rawurl.slice(begin, i);
581                     st = InPort;
582                 } else {
583                     // can't be sure whether this is an ipv6 address or a port
584                     st = Ip6Port;
585                 }
586               }
587               Ip6Port => {
588                 if input == Unreserved {
589                     return Err("Illegal characters in authority.".to_string());
590                 }
591                 st = Ip6Host;
592               }
593               Ip6Host => {
594                 if colon_count > 7 {
595                     host = rawurl.slice(begin, i);
596                     pos = i;
597                     st = InPort;
598                 }
599               }
600               _ => return Err("Invalid ':' in authority.".to_string()),
601             }
602             input = Digit; // reset input class
603           }
604
605           '@' => {
606             input = Digit; // reset input class
607             colon_count = 0; // reset count
608             match st {
609               Start => {
610                 let user = rawurl.slice(begin, i).to_string();
611                 userinfo = Some(UserInfo::new(user, None));
612                 st = InHost;
613               }
614               PassHostPort => {
615                 let user = rawurl.slice(begin, pos).to_string();
616                 let pass = rawurl.slice(pos+1, i).to_string();
617                 userinfo = Some(UserInfo::new(user, Some(pass)));
618                 st = InHost;
619               }
620               _ => return Err("Invalid '@' in authority.".to_string()),
621             }
622             begin = i+1;
623           }
624
625           '?' | '#' | '/' => {
626             end = i;
627             break;
628           }
629           _ => ()
630         }
631     }
632
633     // finish up
634     match st {
635       Start => host = rawurl.slice(begin, end),
636       PassHostPort
637       | Ip6Port => {
638         if input != Digit {
639             return Err("Non-digit characters in port.".to_string());
640         }
641         host = rawurl.slice(begin, pos);
642         port = Some(rawurl.slice(pos+1, end));
643       }
644       Ip6Host
645       | InHost => host = rawurl.slice(begin, end),
646       InPort => {
647         if input != Digit {
648             return Err("Non-digit characters in port.".to_string());
649         }
650         port = Some(rawurl.slice(pos+1, end));
651       }
652     }
653
654     let rest = rawurl.slice(end, len);
655     // If we have a port string, ensure it parses to u16.
656     let port = match port {
657         None => None,
658         opt => match opt.and_then(|p| FromStr::from_str(p)) {
659             None => return Err(format!("Failed to parse port: {}", port)),
660             opt => opt
661         }
662     };
663
664     Ok((userinfo, host, port, rest))
665 }
666
667
668 // returns the path and unparsed part of url, or an error
669 fn get_path(rawurl: &str, is_authority: bool) -> DecodeResult<(String, &str)> {
670     let len = rawurl.len();
671     let mut end = len;
672     for (i,c) in rawurl.chars().enumerate() {
673         match c {
674           'A' ... 'Z'
675           | 'a' ... 'z'
676           | '0' ... '9'
677           | '&' |'\'' | '(' | ')' | '.'
678           | '@' | ':' | '%' | '/' | '+'
679           | '!' | '*' | ',' | ';' | '='
680           | '_' | '-' | '~' => continue,
681           '?' | '#' => {
682             end = i;
683             break;
684           }
685           _ => return Err("Invalid character in path.".to_string())
686         }
687     }
688
689     if is_authority && end != 0 && !rawurl.starts_with("/") {
690         Err("Non-empty path must begin with \
691             '/' in presence of authority.".to_string())
692     } else {
693         Ok((try!(decode_component(rawurl.slice(0, end))),
694             rawurl.slice(end, len)))
695     }
696 }
697
698 // returns the parsed query and the fragment, if present
699 fn get_query_fragment(rawurl: &str) -> DecodeResult<(Query, Option<String>)> {
700     let (before_fragment, raw_fragment) = split_char_first(rawurl, '#');
701
702     // Parse the fragment if available
703     let fragment = match raw_fragment {
704         "" => None,
705         raw => Some(try!(decode_component(raw)))
706     };
707
708     match before_fragment.slice_shift_char() {
709         (Some('?'), rest) => Ok((try!(query_from_str(rest)), fragment)),
710         (None, "") => Ok((vec!(), fragment)),
711         _ => Err(format!("Query didn't start with '?': '{}..'", before_fragment)),
712     }
713 }
714
715 impl FromStr for Url {
716     fn from_str(s: &str) -> Option<Url> {
717         Url::parse(s).ok()
718     }
719 }
720
721 impl FromStr for Path {
722     fn from_str(s: &str) -> Option<Path> {
723         Path::parse(s).ok()
724     }
725 }
726
727 impl fmt::Show for Url {
728     /// Converts a URL from `Url` to string representation.
729     ///
730     /// # Returns
731     ///
732     /// A string that contains the formatted URL. Note that this will usually
733     /// be an inverse of `from_str` but might strip out unneeded separators;
734     /// for example, "http://somehost.com?", when parsed and formatted, will
735     /// result in just "http://somehost.com".
736     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
737         try!(write!(f, "{}:", self.scheme));
738
739         if !self.host.is_empty() {
740             try!(write!(f, "//"));
741             match self.user {
742                 Some(ref user) => try!(write!(f, "{}", *user)),
743                 None => {}
744             }
745             match self.port {
746                 Some(ref port) => try!(write!(f, "{}:{}", self.host,
747                                                 *port)),
748                 None => try!(write!(f, "{}", self.host)),
749             }
750         }
751
752         write!(f, "{}", self.path)
753     }
754 }
755
756 impl fmt::Show for Path {
757     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
758         try!(write!(f, "{}", self.path));
759         if !self.query.is_empty() {
760             try!(write!(f, "?{}", query_to_str(&self.query)))
761         }
762
763         match self.fragment {
764             Some(ref fragment) => {
765                 write!(f, "#{}", encode_component(fragment.as_slice()))
766             }
767             None => Ok(())
768         }
769     }
770 }
771
772 impl<S: hash::Writer> hash::Hash<S> for Url {
773     fn hash(&self, state: &mut S) {
774         self.to_string().hash(state)
775     }
776 }
777
778 impl<S: hash::Writer> hash::Hash<S> for Path {
779     fn hash(&self, state: &mut S) {
780         self.to_string().hash(state)
781     }
782 }
783
784 // Put a few tests outside of the 'test' module so they can test the internal
785 // functions and those functions don't need 'pub'
786
787 #[test]
788 fn test_split_char_first() {
789     let (u,v) = split_char_first("hello, sweet world", ',');
790     assert_eq!(u, "hello");
791     assert_eq!(v, " sweet world");
792
793     let (u,v) = split_char_first("hello sweet world", ',');
794     assert_eq!(u, "hello sweet world");
795     assert_eq!(v, "");
796 }
797
798 #[test]
799 fn test_get_authority() {
800     let (u, h, p, r) = get_authority(
801         "//user:pass@rust-lang.org/something").unwrap();
802     assert_eq!(u, Some(UserInfo::new("user".to_string(), Some("pass".to_string()))));
803     assert_eq!(h, "rust-lang.org");
804     assert!(p.is_none());
805     assert_eq!(r, "/something");
806
807     let (u, h, p, r) = get_authority(
808         "//rust-lang.org:8000?something").unwrap();
809     assert!(u.is_none());
810     assert_eq!(h, "rust-lang.org");
811     assert_eq!(p, Some(8000));
812     assert_eq!(r, "?something");
813
814     let (u, h, p, r) = get_authority("//rust-lang.org#blah").unwrap();
815     assert!(u.is_none());
816     assert_eq!(h, "rust-lang.org");
817     assert!(p.is_none());
818     assert_eq!(r, "#blah");
819
820     // ipv6 tests
821     let (_, h, _, _) = get_authority(
822         "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap();
823     assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334");
824
825     let (_, h, p, _) = get_authority(
826         "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap();
827     assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334");
828     assert_eq!(p, Some(8000));
829
830     let (u, h, p, _) = get_authority(
831         "//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah"
832     ).unwrap();
833     assert_eq!(u, Some(UserInfo::new("us".to_string(), Some("p".to_string()))));
834     assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334");
835     assert_eq!(p, Some(8000));
836
837     // invalid authorities;
838     assert!(get_authority("//user:pass@rust-lang:something").is_err());
839     assert!(get_authority("//user@rust-lang:something:/path").is_err());
840     assert!(get_authority(
841         "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:800a").is_err());
842     assert!(get_authority(
843         "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00").is_err());
844     // outside u16 range
845     assert!(get_authority("//user:pass@rust-lang:65536").is_err());
846
847     // these parse as empty, because they don't start with '//'
848     let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap();
849     assert_eq!(h, "");
850     let (_, h, _, _) = get_authority("rust-lang.org").unwrap();
851     assert_eq!(h, "");
852 }
853
854 #[test]
855 fn test_get_path() {
856     let (p, r) = get_path("/something+%20orother", true).unwrap();
857     assert_eq!(p, "/something+ orother".to_string());
858     assert_eq!(r, "");
859     let (p, r) = get_path("test@email.com#fragment", false).unwrap();
860     assert_eq!(p, "test@email.com".to_string());
861     assert_eq!(r, "#fragment");
862     let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap();
863     assert_eq!(p, "/gen/:addr=".to_string());
864     assert_eq!(r, "?q=v");
865
866     //failure cases
867     assert!(get_path("something?q", true).is_err());
868 }
869
870 #[cfg(test)]
871 mod tests {
872     use {encode_form_urlencoded, decode_form_urlencoded, decode, encode,
873         encode_component, decode_component, UserInfo, get_scheme, Url, Path};
874
875     use std::collections::HashMap;
876     use std::path::BytesContainer;
877
878     #[test]
879     fn test_url_parse() {
880         let url = "http://user:pass@rust-lang.org:8080/doc/~u?s=v#something";
881         let u = from_str::<Url>(url).unwrap();
882
883         assert_eq!(u.scheme, "http".to_string());
884         assert_eq!(u.user, Some(UserInfo::new("user".to_string(), Some("pass".to_string()))));
885         assert_eq!(u.host, "rust-lang.org".to_string());
886         assert_eq!(u.port, Some(8080));
887         assert_eq!(u.path.path, "/doc/~u".to_string());
888         assert_eq!(u.path.query, vec!(("s".to_string(), "v".to_string())));
889         assert_eq!(u.path.fragment, Some("something".to_string()));
890     }
891
892     #[test]
893     fn test_path_parse() {
894         let path = "/doc/~u?s=v#something";
895         let u = from_str::<Path>(path).unwrap();
896
897         assert_eq!(u.path, "/doc/~u".to_string());
898         assert_eq!(u.query, vec!(("s".to_string(), "v".to_string())));
899         assert_eq!(u.fragment, Some("something".to_string()));
900     }
901
902     #[test]
903     fn test_url_parse_host_slash() {
904         let urlstr = "http://0.42.42.42/";
905         let url = from_str::<Url>(urlstr).unwrap();
906         assert_eq!(url.host, "0.42.42.42".to_string());
907         assert_eq!(url.path.path, "/".to_string());
908     }
909
910     #[test]
911     fn test_path_parse_host_slash() {
912         let pathstr = "/";
913         let path = from_str::<Path>(pathstr).unwrap();
914         assert_eq!(path.path, "/".to_string());
915     }
916
917     #[test]
918     fn test_url_host_with_port() {
919         let urlstr = "scheme://host:1234";
920         let url = from_str::<Url>(urlstr).unwrap();
921         assert_eq!(url.scheme, "scheme".to_string());
922         assert_eq!(url.host, "host".to_string());
923         assert_eq!(url.port, Some(1234));
924         // is empty path really correct? Other tests think so
925         assert_eq!(url.path.path, "".to_string());
926
927         let urlstr = "scheme://host:1234/";
928         let url = from_str::<Url>(urlstr).unwrap();
929         assert_eq!(url.scheme, "scheme".to_string());
930         assert_eq!(url.host, "host".to_string());
931         assert_eq!(url.port, Some(1234));
932         assert_eq!(url.path.path, "/".to_string());
933     }
934
935     #[test]
936     fn test_url_with_underscores() {
937         let urlstr = "http://dotcom.com/file_name.html";
938         let url = from_str::<Url>(urlstr).unwrap();
939         assert_eq!(url.path.path, "/file_name.html".to_string());
940     }
941
942     #[test]
943     fn test_path_with_underscores() {
944         let pathstr = "/file_name.html";
945         let path = from_str::<Path>(pathstr).unwrap();
946         assert_eq!(path.path, "/file_name.html".to_string());
947     }
948
949     #[test]
950     fn test_url_with_dashes() {
951         let urlstr = "http://dotcom.com/file-name.html";
952         let url = from_str::<Url>(urlstr).unwrap();
953         assert_eq!(url.path.path, "/file-name.html".to_string());
954     }
955
956     #[test]
957     fn test_path_with_dashes() {
958         let pathstr = "/file-name.html";
959         let path = from_str::<Path>(pathstr).unwrap();
960         assert_eq!(path.path, "/file-name.html".to_string());
961     }
962
963     #[test]
964     fn test_no_scheme() {
965         assert!(get_scheme("noschemehere.html").is_err());
966     }
967
968     #[test]
969     fn test_invalid_scheme_errors() {
970         assert!(Url::parse("99://something").is_err());
971         assert!(Url::parse("://something").is_err());
972     }
973
974     #[test]
975     fn test_full_url_parse_and_format() {
976         let url = "http://user:pass@rust-lang.org/doc?s=v#something";
977         let u = from_str::<Url>(url).unwrap();
978         assert_eq!(format!("{}", u).as_slice(), url);
979     }
980
981     #[test]
982     fn test_userless_url_parse_and_format() {
983         let url = "http://rust-lang.org/doc?s=v#something";
984         let u = from_str::<Url>(url).unwrap();
985         assert_eq!(format!("{}", u).as_slice(), url);
986     }
987
988     #[test]
989     fn test_queryless_url_parse_and_format() {
990         let url = "http://user:pass@rust-lang.org/doc#something";
991         let u = from_str::<Url>(url).unwrap();
992         assert_eq!(format!("{}", u).as_slice(), url);
993     }
994
995     #[test]
996     fn test_empty_query_url_parse_and_format() {
997         let url = "http://user:pass@rust-lang.org/doc?#something";
998         let should_be = "http://user:pass@rust-lang.org/doc#something";
999         let u = from_str::<Url>(url).unwrap();
1000         assert_eq!(format!("{}", u).as_slice(), should_be);
1001     }
1002
1003     #[test]
1004     fn test_fragmentless_url_parse_and_format() {
1005         let url = "http://user:pass@rust-lang.org/doc?q=v";
1006         let u = from_str::<Url>(url).unwrap();
1007         assert_eq!(format!("{}", u).as_slice(), url);
1008     }
1009
1010     #[test]
1011     fn test_minimal_url_parse_and_format() {
1012         let url = "http://rust-lang.org/doc";
1013         let u = from_str::<Url>(url).unwrap();
1014         assert_eq!(format!("{}", u).as_slice(), url);
1015     }
1016
1017     #[test]
1018     fn test_url_with_port_parse_and_format() {
1019         let url = "http://rust-lang.org:80/doc";
1020         let u = from_str::<Url>(url).unwrap();
1021         assert_eq!(format!("{}", u).as_slice(), url);
1022     }
1023
1024     #[test]
1025     fn test_scheme_host_only_url_parse_and_format() {
1026         let url = "http://rust-lang.org";
1027         let u = from_str::<Url>(url).unwrap();
1028         assert_eq!(format!("{}", u).as_slice(), url);
1029     }
1030
1031     #[test]
1032     fn test_pathless_url_parse_and_format() {
1033         let url = "http://user:pass@rust-lang.org?q=v#something";
1034         let u = from_str::<Url>(url).unwrap();
1035         assert_eq!(format!("{}", u).as_slice(), url);
1036     }
1037
1038     #[test]
1039     fn test_scheme_host_fragment_only_url_parse_and_format() {
1040         let url = "http://rust-lang.org#something";
1041         let u = from_str::<Url>(url).unwrap();
1042         assert_eq!(format!("{}", u).as_slice(), url);
1043     }
1044
1045     #[test]
1046     fn test_url_component_encoding() {
1047         let url = "http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B";
1048         let u = from_str::<Url>(url).unwrap();
1049         assert!(u.path.path == "/doc uments".to_string());
1050         assert!(u.path.query == vec!(("ba%d ".to_string(), "#&+".to_string())));
1051     }
1052
1053     #[test]
1054     fn test_path_component_encoding() {
1055         let path = "/doc%20uments?ba%25d%20=%23%26%2B";
1056         let p = from_str::<Path>(path).unwrap();
1057         assert!(p.path == "/doc uments".to_string());
1058         assert!(p.query == vec!(("ba%d ".to_string(), "#&+".to_string())));
1059     }
1060
1061     #[test]
1062     fn test_url_without_authority() {
1063         let url = "mailto:test@email.com";
1064         let u = from_str::<Url>(url).unwrap();
1065         assert_eq!(format!("{}", u).as_slice(), url);
1066     }
1067
1068     #[test]
1069     fn test_encode() {
1070         fn t<T: BytesContainer>(input: T, expected: &str) {
1071             assert_eq!(encode(input), expected.to_string())
1072         }
1073
1074         t("", "");
1075         t("http://example.com", "http://example.com");
1076         t("foo bar% baz", "foo%20bar%25%20baz");
1077         t(" ", "%20");
1078         t("!", "!");
1079         t("\"", "\"");
1080         t("#", "#");
1081         t("$", "$");
1082         t("%", "%25");
1083         t("&", "&");
1084         t("'", "%27");
1085         t("(", "(");
1086         t(")", ")");
1087         t("*", "*");
1088         t("+", "+");
1089         t(",", ",");
1090         t("/", "/");
1091         t(":", ":");
1092         t(";", ";");
1093         t("=", "=");
1094         t("?", "?");
1095         t("@", "@");
1096         t("[", "[");
1097         t("]", "]");
1098         t("\0", "%00");
1099         t("\n", "%0A");
1100
1101         let a: &[_] = &[0u8, 10, 37];
1102         t(a, "%00%0A%25");
1103     }
1104
1105     #[test]
1106     fn test_encode_component() {
1107         fn t<T: BytesContainer>(input: T, expected: &str) {
1108             assert_eq!(encode_component(input), expected.to_string())
1109         }
1110
1111         t("", "");
1112         t("http://example.com", "http%3A%2F%2Fexample.com");
1113         t("foo bar% baz", "foo%20bar%25%20baz");
1114         t(" ", "%20");
1115         t("!", "%21");
1116         t("#", "%23");
1117         t("$", "%24");
1118         t("%", "%25");
1119         t("&", "%26");
1120         t("'", "%27");
1121         t("(", "%28");
1122         t(")", "%29");
1123         t("*", "%2A");
1124         t("+", "%2B");
1125         t(",", "%2C");
1126         t("/", "%2F");
1127         t(":", "%3A");
1128         t(";", "%3B");
1129         t("=", "%3D");
1130         t("?", "%3F");
1131         t("@", "%40");
1132         t("[", "%5B");
1133         t("]", "%5D");
1134         t("\0", "%00");
1135         t("\n", "%0A");
1136
1137         let a: &[_] = &[0u8, 10, 37];
1138         t(a, "%00%0A%25");
1139     }
1140
1141     #[test]
1142     fn test_decode() {
1143         fn t<T: BytesContainer>(input: T, expected: &str) {
1144             assert_eq!(decode(input), Ok(expected.to_string()))
1145         }
1146
1147         assert!(decode("sadsadsda%").is_err());
1148         assert!(decode("waeasd%4").is_err());
1149         t("", "");
1150         t("abc/def 123", "abc/def 123");
1151         t("abc%2Fdef%20123", "abc%2Fdef 123");
1152         t("%20", " ");
1153         t("%21", "%21");
1154         t("%22", "%22");
1155         t("%23", "%23");
1156         t("%24", "%24");
1157         t("%25", "%");
1158         t("%26", "%26");
1159         t("%27", "'");
1160         t("%28", "%28");
1161         t("%29", "%29");
1162         t("%2A", "%2A");
1163         t("%2B", "%2B");
1164         t("%2C", "%2C");
1165         t("%2F", "%2F");
1166         t("%3A", "%3A");
1167         t("%3B", "%3B");
1168         t("%3D", "%3D");
1169         t("%3F", "%3F");
1170         t("%40", "%40");
1171         t("%5B", "%5B");
1172         t("%5D", "%5D");
1173
1174         t("%00%0A%25".as_bytes(), "\0\n%");
1175     }
1176
1177     #[test]
1178     fn test_decode_component() {
1179         fn t<T: BytesContainer>(input: T, expected: &str) {
1180             assert_eq!(decode_component(input), Ok(expected.to_string()))
1181         }
1182
1183         assert!(decode_component("asacsa%").is_err());
1184         assert!(decode_component("acsas%4").is_err());
1185         t("", "");
1186         t("abc/def 123", "abc/def 123");
1187         t("abc%2Fdef%20123", "abc/def 123");
1188         t("%20", " ");
1189         t("%21", "!");
1190         t("%22", "\"");
1191         t("%23", "#");
1192         t("%24", "$");
1193         t("%25", "%");
1194         t("%26", "&");
1195         t("%27", "'");
1196         t("%28", "(");
1197         t("%29", ")");
1198         t("%2A", "*");
1199         t("%2B", "+");
1200         t("%2C", ",");
1201         t("%2F", "/");
1202         t("%3A", ":");
1203         t("%3B", ";");
1204         t("%3D", "=");
1205         t("%3F", "?");
1206         t("%40", "@");
1207         t("%5B", "[");
1208         t("%5D", "]");
1209
1210         t("%00%0A%25".as_bytes(), "\0\n%");
1211     }
1212
1213     #[test]
1214     fn test_encode_form_urlencoded() {
1215         let mut m = HashMap::new();
1216         assert_eq!(encode_form_urlencoded(&m), "".to_string());
1217
1218         m.insert("".to_string(), vec!());
1219         m.insert("foo".to_string(), vec!());
1220         assert_eq!(encode_form_urlencoded(&m), "".to_string());
1221
1222         let mut m = HashMap::new();
1223         m.insert("foo".to_string(), vec!("bar".to_string(), "123".to_string()));
1224         assert_eq!(encode_form_urlencoded(&m), "foo=bar&foo=123".to_string());
1225
1226         let mut m = HashMap::new();
1227         m.insert("foo bar".to_string(), vec!("abc".to_string(), "12 = 34".to_string()));
1228         assert_eq!(encode_form_urlencoded(&m),
1229                     "foo+bar=abc&foo+bar=12+%3D+34".to_string());
1230     }
1231
1232     #[test]
1233     fn test_decode_form_urlencoded() {
1234         assert_eq!(decode_form_urlencoded([]).unwrap().len(), 0);
1235
1236         let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes();
1237         let form = decode_form_urlencoded(s).unwrap();
1238         assert_eq!(form.len(), 2);
1239         assert_eq!(form.get(&"a".to_string()), &vec!("1".to_string()));
1240         assert_eq!(form.get(&"foo bar".to_string()),
1241                    &vec!("abc".to_string(), "12 = 34".to_string()));
1242     }
1243 }