Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New IntoUrl trait #177

Closed
wants to merge 40 commits into from
Closed
Changes from 1 commit
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
918352b
Make it possible to define new encode sets in other crates.
SimonSapin Dec 4, 2015
db9de70
Define encode sets based on another set.
SimonSapin Dec 4, 2015
691aec2
Remove the HTTP_VALUE encode set. It can be defined in another crate.
SimonSapin Dec 4, 2015
d140dc8
Rewrite ALL THE THINGS!
SimonSapin Dec 9, 2015
9edff44
Remove the dependency on uuid.
SimonSapin Feb 8, 2016
576bd2a
Add URL slicing/indexing by component.
SimonSapin Feb 8, 2016
7b11445
Add stubs with partial implementation for the WebIDL API.
SimonSapin Feb 8, 2016
c617ed1
Shorter Cargo.toml syntax.
SimonSapin Feb 8, 2016
22cf104
serde_serialization -> serde
SimonSapin Feb 8, 2016
0cb3f2b
Make rustc-serialize an optional dependency.
SimonSapin Feb 8, 2016
61a8185
Rename *{Start,End} posititons to {Before,After}*
SimonSapin Feb 9, 2016
813d270
Replace from_hex() with char::to_digit(16)
SimonSapin Feb 9, 2016
0b5ffb4
Make percent-decoding an iterator.
SimonSapin Feb 9, 2016
244d999
Make percent-encoding an iterator.
SimonSapin Feb 9, 2016
7b33b33
Add percent-encoding convienience wrappers.
SimonSapin Feb 9, 2016
ca9f87d
Update tests from https://github.com/w3c/web-platform-tests/blob/mast…
SimonSapin Feb 10, 2016
7a0e467
Remove Url::has_host
SimonSapin Feb 11, 2016
9a8d394
Remove unused ParseError variants
SimonSapin Feb 12, 2016
903f1d2
Make context a field of Parser.
SimonSapin Feb 11, 2016
a9b4e71
Remove the redundant is_relative field.
SimonSapin Feb 15, 2016
ded48a2
Add Url::domain and Url::ip_address
SimonSapin Feb 15, 2016
d3dba86
Implement ToSocketAddrs
SimonSapin Feb 15, 2016
088c3ed
Remove Url::ip_address for now
SimonSapin Feb 15, 2016
641f940
Add Unicode and ASCII serializations of origins
SimonSapin Feb 16, 2016
946d950
Test WebIdl::origin
SimonSapin Feb 16, 2016
4dff876
Add a fragment setter
SimonSapin Feb 11, 2016
0ae07ed
Add a query setter.
SimonSapin Feb 12, 2016
542feb0
Make Url::parse_with usable. (EncodingOverride is private.)
SimonSapin Feb 19, 2016
dd0436a
Add Origin::is_tuple
SimonSapin Feb 19, 2016
f7e0d7c
More consistent checks for URL with authority or path-only.
SimonSapin Feb 19, 2016
fd16b74
Re-export OpaqueOrigin. It is exposed publicly through Origin::Opaque
SimonSapin Feb 19, 2016
f1bdaa6
Add a scheme setter
SimonSapin Feb 19, 2016
158145f
Add host setters.
SimonSapin Feb 19, 2016
b1b0916
More setters
SimonSapin Feb 23, 2016
47e31ef
Add a path setter
SimonSapin Feb 26, 2016
e7a4dc0
Username and passowrd setters
SimonSapin Feb 26, 2016
5b26c89
More WebIDL implementations.
SimonSapin Feb 26, 2016
bf0f670
Port setters
SimonSapin Mar 1, 2016
b89d7d7
All setters.
SimonSapin Mar 1, 2016
3f9dcd4
New IntoUrl trait
cmbrandenburg Mar 4, 2016
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.

Always

Just for now

Implement ToSocketAddrs

  • Loading branch information
SimonSapin committed Mar 3, 2016
commit d3dba8633b9645d6a9b9a54be0e12ec0dccaf81e
@@ -8,7 +8,9 @@

use std::cmp;
use std::fmt::{self, Formatter, Write};
use std::net::{Ipv4Addr, Ipv6Addr};
use std::io;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
use std::vec;
use parser::{ParseResult, ParseError};
use percent_encoding::lossy_utf8_percent_decode;
use idna;
@@ -44,6 +46,7 @@ pub enum Host<S=String> {
}

impl<'a> Host<&'a str> {
/// Return a copy of `self` that owns an allocated `String` but does not borrow an `&Url`.
pub fn to_owned(&self) -> Host<String> {
match *self {
Host::Domain(domain) => Host::Domain(domain.to_owned()),
@@ -93,6 +96,66 @@ impl<S: AsRef<str>> fmt::Display for Host<S> {
}
}

/// This mostly exists because coherence rules don’t allow us to implement
/// `ToSocketAddrs for (Host<S>, u16)`.
pub struct HostAndPort<S=String> {
pub host: Host<S>,
pub port: u16,
}

impl<'a> HostAndPort<&'a str> {
/// Return a copy of `self` that owns an allocated `String` but does not borrow an `&Url`.
pub fn to_owned(&self) -> HostAndPort<String> {
HostAndPort {
host: self.host.to_owned(),
port: self.port
}
}
}

impl<S: AsRef<str>> ToSocketAddrs for HostAndPort<S> {
type Iter = SocketAddrs;

fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
let port = self.port;
match self.host {
Host::Domain(ref domain) => Ok(SocketAddrs {
state: SocketAddrsState::Domain(try!((domain.as_ref(), port).to_socket_addrs()))
}),
Host::Ipv4(address) => Ok(SocketAddrs {
state: SocketAddrsState::One(SocketAddr::V4(SocketAddrV4::new(address, port)))
}),
Host::Ipv6(address) => Ok(SocketAddrs {
state: SocketAddrsState::One(SocketAddr::V6(SocketAddrV6::new(address, port, 0, 0)))
}),
}
}
}

pub struct SocketAddrs {
state: SocketAddrsState
}

enum SocketAddrsState {
Domain(vec::IntoIter<SocketAddr>),
One(SocketAddr),
Done,
}

impl Iterator for SocketAddrs {
type Item = SocketAddr;
fn next(&mut self) -> Option<SocketAddr> {
match self.state {
SocketAddrsState::Domain(ref mut iter) => iter.next(),
SocketAddrsState::One(s) => {
self.state = SocketAddrsState::Done;
Some(s)
}
SocketAddrsState::Done => None
}
}
}

/// Parse `input` as a host.
/// If successful, write its serialization to `serialization`
/// and return the internal representation for `Url`.
@@ -131,14 +131,15 @@ use percent_encoding::{PATH_SEGMENT_ENCODE_SET, percent_encode, percent_decode};
use std::cmp;
use std::fmt;
use std::hash;
#[cfg(has_ipaddr)] use std::net::IpAddr;
use std::io;
use std::net::ToSocketAddrs;
use std::ops::{Range, RangeFrom, RangeTo};
use std::path::{Path, PathBuf};
use std::str;

pub use encoding::EncodingOverride;
pub use origin::Origin;
pub use host::Host;
pub use host::{Host, HostAndPort, SocketAddrs};
pub use parser::ParseError;
pub use slicing::Position;
pub use webidl::WebIdl;
@@ -291,12 +292,12 @@ impl Url {
///
/// This does **not** resolve domain names.
#[cfg(has_ipaddr)]
pub fn ip_address(&self) -> Option<IpAddr> {
pub fn ip_address(&self) -> Option<net::IpAddr> {
match self.host {
HostInternal::None => None,
HostInternal::Domain => None,
HostInternal::Ipv4(address) => Some(IpAddr::V4(address)),
HostInternal::Ipv6(address) => Some(IpAddr::V6(address)),
HostInternal::Ipv4(address) => Some(net::IpAddr::V4(address)),
HostInternal::Ipv6(address) => Some(net::IpAddr::V6(address)),
}
}

@@ -314,10 +315,52 @@ impl Url {
/// For URLs in these schemes, this method always returns `Some(_)`.
/// For other schemes, it is the same as `Url::port()`.
#[inline]
pub fn port_or_default(&self) -> Option<u16> {
pub fn port_or_known_default(&self) -> Option<u16> {
self.port.or_else(|| parser::default_port(self.scheme()))
}

/// If the URL has a host, return something that implements `ToSocketAddrs`.
///
/// If the URL has no port number and the scheme’s default port number is not known
/// (see `Url::port_or_known_default`),
/// the closure is called to obtain a port number.
/// Typically, this closure can match on the result `Url::scheme`
/// to have per-scheme default port numbers,
/// and panic for schemes it’s not prepared to handle.
/// For example:
///
/// ```rust
/// # use url::Url;
/// # use std::net::TcpStream;
/// # use std::io;
///
/// fn connect(url: &Url) -> io::Result<TcpStream> {
/// TcpStream::connect(try!(url.with_default_port(default_port)))
/// }
///
/// fn default_port(url: &Url) -> Result<u16, ()> {
/// match url.scheme() {
/// "git" => Ok(9418),
/// "git+ssh" => Ok(22),
/// "git+https" => Ok(443),
/// "git+http" => Ok(80),
/// _ => Err(()),
/// }
/// }
/// ```
pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
where F: FnOnce(&Url) -> Result<u16, ()> {
Ok(HostAndPort {
host: try!(self.host()
.ok_or(())
.or_else(|()| io_error("URL has no host"))),
port: try!(self.port_or_known_default()
.ok_or(())
.or_else(|()| f(self))
.or_else(|()| io_error("URL has no port number")))
})
}

/// Return the path for this URL, as a percent-encoded ASCII string.
/// For relative URLs, this starts with a '/' slash
/// and continues with slash-separated path segments.
@@ -466,6 +509,15 @@ impl Url {
}
}

/// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
impl ToSocketAddrs for Url {
type Iter = SocketAddrs;

fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
try!(self.with_default_port(|_| Err(()))).to_socket_addrs()
}
}

/// Parse a string as an URL, without a base URL or encoding override.
impl str::FromStr for Url {
type Err = ParseError;
@@ -697,3 +749,7 @@ fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Resul
"to_file_path() failed to produce an absolute Path");
Ok(path)
}

fn io_error<T>(reason: &str) -> io::Result<T> {
Err(io::Error::new(io::ErrorKind::InvalidData, reason))
}
@@ -23,7 +23,7 @@ impl Url {
},
"ftp" | "gopher" | "http" | "https" | "ws" | "wss" => {
Origin::Tuple(scheme.to_owned(), self.host().unwrap().to_owned(),
self.port_or_default().unwrap())
self.port_or_known_default().unwrap())
},
// TODO: Figure out what to do if the scheme is a file
"file" => Origin::new_opaque(),
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.