Skip to content

Commit 8fa7a98

Browse files
SimonSapinseanmonstar
authored andcommitted
refactor(hyper): Update to rust-url 1.0
BREAKING CHANGE: The re-exported Url type has breaking changes.
1 parent 4bdf52a commit 8fa7a98

File tree

9 files changed

+54
-54
lines changed

9 files changed

+54
-54
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ time = "0.1"
2222
traitobject = "0.0.1"
2323
typeable = "0.1"
2424
unicase = "1.0"
25-
url = "0.5"
25+
url = "1.0"
2626

2727
[dependencies.cookie]
2828
version = "0.2"

src/client/mod.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,13 @@ use std::fmt;
6262

6363
use std::time::Duration;
6464

65-
use url::UrlParser;
65+
use url::Url;
6666
use url::ParseError as UrlError;
6767

6868
use header::{Headers, Header, HeaderFormat};
6969
use header::{ContentLength, Location};
7070
use method::Method;
7171
use net::{NetworkConnector, NetworkStream};
72-
use {Url};
7372
use Error;
7473

7574
pub use self::pool::Pool;
@@ -264,7 +263,7 @@ impl<'a> RequestBuilder<'a> {
264263
loop {
265264
let message = {
266265
let (host, port) = try!(get_host_and_port(&url));
267-
try!(client.protocol.new_message(&host, port, &*url.scheme))
266+
try!(client.protocol.new_message(&host, port, url.scheme()))
268267
};
269268
let mut req = try!(Request::with_message(method.clone(), url.clone(), message));
270269
headers.as_ref().map(|headers| req.headers_mut().extend(headers.iter()));
@@ -292,7 +291,7 @@ impl<'a> RequestBuilder<'a> {
292291
// punching borrowck here
293292
let loc = match res.headers.get::<Location>() {
294293
Some(&Location(ref loc)) => {
295-
Some(UrlParser::new().base_url(&url).parse(&loc[..]))
294+
Some(url.join(loc))
296295
}
297296
None => {
298297
debug!("no Location header");
@@ -439,13 +438,13 @@ impl Default for RedirectPolicy {
439438
}
440439
}
441440

442-
fn get_host_and_port(url: &Url) -> ::Result<(String, u16)> {
443-
let host = match url.serialize_host() {
441+
fn get_host_and_port(url: &Url) -> ::Result<(&str, u16)> {
442+
let host = match url.host_str() {
444443
Some(host) => host,
445444
None => return Err(Error::Uri(UrlError::EmptyHost))
446445
};
447446
trace!("host={:?}", host);
448-
let port = match url.port_or_default() {
447+
let port = match url.port_or_known_default() {
449448
Some(port) => port,
450449
None => return Err(Error::Uri(UrlError::InvalidPort))
451450
};
@@ -498,7 +497,7 @@ mod tests {
498497
#[test]
499498
fn test_redirect_followif() {
500499
fn follow_if(url: &Url) -> bool {
501-
!url.serialize().contains("127.0.0.3")
500+
!url.as_str().contains("127.0.0.3")
502501
}
503502
let mut client = Client::with_connector(MockRedirectPolicy);
504503
client.set_redirect_policy(RedirectPolicy::FollowIf(follow_if));

src/client/request.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,14 @@ impl Request<Fresh> {
6161
/// properly initialized by the caller (e.g. a TCP connection's already established).
6262
pub fn with_message(method: Method, url: Url, message: Box<HttpMessage>)
6363
-> ::Result<Request<Fresh>> {
64-
let (host, port) = try!(get_host_and_port(&url));
6564
let mut headers = Headers::new();
66-
headers.set(Host {
67-
hostname: host,
68-
port: Some(port),
69-
});
65+
{
66+
let (host, port) = try!(get_host_and_port(&url));
67+
headers.set(Host {
68+
hostname: host.to_owned(),
69+
port: Some(port),
70+
});
71+
}
7072

7173
Ok(Request {
7274
method: method,
@@ -89,8 +91,10 @@ impl Request<Fresh> {
8991
-> ::Result<Request<Fresh>> where
9092
C: NetworkConnector<Stream=S>,
9193
S: Into<Box<NetworkStream + Send>> {
92-
let (host, port) = try!(get_host_and_port(&url));
93-
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
94+
let stream = {
95+
let (host, port) = try!(get_host_and_port(&url));
96+
try!(connector.connect(host, port, url.scheme())).into()
97+
};
9498

9599
Request::with_message(method, url, Box::new(Http11Message::with_stream(stream)))
96100
}
@@ -223,7 +227,8 @@ mod tests {
223227
let mut req = Request::with_connector(
224228
Post, url, &mut MockConnector
225229
).unwrap();
226-
let body = form_urlencoded::serialize(vec!(("q","value")).into_iter());
230+
let mut body = String::new();
231+
form_urlencoded::Serializer::new(&mut body).append_pair("q", "value");
227232
req.headers_mut().set(ContentLength(body.len() as u64));
228233
let bytes = run_request(req);
229234
let s = from_utf8(&bytes[..]).unwrap();

src/header/common/content_disposition.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use unicase::UniCase;
1212
use url::percent_encoding;
1313

1414
use header::{Header, HeaderFormat, parsing};
15-
use header::parsing::parse_extended_value;
15+
use header::parsing::{parse_extended_value, HTTP_VALUE};
1616
use header::shared::Charset;
1717

1818
/// The implied disposition of the content of the HTTP body
@@ -184,8 +184,7 @@ impl fmt::Display for ContentDisposition {
184184
};
185185
try!(write!(f, "'"));
186186
try!(f.write_str(
187-
&*percent_encoding::percent_encode(
188-
bytes, percent_encoding::HTTP_VALUE_ENCODE_SET)))
187+
&percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string()))
189188
}
190189
},
191190
DispositionParam::Ext(ref k, ref v) => try!(write!(f, "; {}=\"{}\"", k, v)),

src/header/parsing.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {
118118
// Interpret the third piece as a sequence of value characters
119119
let value: Vec<u8> = match parts.next() {
120120
None => return Err(::Error::Header),
121-
Some(v) => percent_encoding::percent_decode(v.as_bytes()),
121+
Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
122122
};
123123

124124
Ok(ExtendedValue {
@@ -128,11 +128,19 @@ pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {
128128
})
129129
}
130130

131+
define_encode_set! {
132+
/// This encode set is used for HTTP header values and is defined at
133+
/// https://tools.ietf.org/html/rfc5987#section-3.2
134+
pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
135+
' ', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?',
136+
'[', '\\', ']', '{', '}'
137+
}
138+
}
139+
131140
impl Display for ExtendedValue {
132141
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133142
let encoded_value =
134-
percent_encoding::percent_encode(&self.value[..],
135-
percent_encoding::HTTP_VALUE_ENCODE_SET);
143+
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
136144
if let Some(ref lang) = self.language_tag {
137145
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
138146
} else {

src/http/h1.rs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use std::net::Shutdown;
77
use std::time::Duration;
88

99
use httparse;
10+
use url::Position as UrlPosition;
1011

1112
use buffer::BufReader;
1213
use Error;
@@ -142,25 +143,23 @@ impl HttpMessage for Http11Message {
142143
};
143144
let mut stream = BufWriter::new(stream);
144145

145-
let mut uri = head.url.serialize_path().unwrap();
146-
if let Some(ref q) = head.url.query {
147-
uri.push('?');
148-
uri.push_str(&q[..]);
146+
{
147+
let uri = &head.url[UrlPosition::BeforePath..UrlPosition::AfterQuery];
148+
149+
let version = version::HttpVersion::Http11;
150+
debug!("request line: {:?} {:?} {:?}", head.method, uri, version);
151+
match write!(&mut stream, "{} {} {}{}",
152+
head.method, uri, version, LINE_ENDING) {
153+
Err(e) => {
154+
res = Err(From::from(e));
155+
// TODO What should we do if the BufWriter doesn't wanna
156+
// relinquish the stream?
157+
return Stream::Idle(stream.into_inner().ok().unwrap());
158+
},
159+
Ok(_) => {},
160+
};
149161
}
150162

151-
let version = version::HttpVersion::Http11;
152-
debug!("request line: {:?} {:?} {:?}", head.method, uri, version);
153-
match write!(&mut stream, "{} {} {}{}",
154-
head.method, uri, version, LINE_ENDING) {
155-
Err(e) => {
156-
res = Err(From::from(e));
157-
// TODO What should we do if the BufWriter doesn't wanna
158-
// relinquish the stream?
159-
return Stream::Idle(stream.into_inner().ok().unwrap());
160-
},
161-
Ok(_) => {},
162-
};
163-
164163
let stream = {
165164
let write_headers = |mut stream: BufWriter<Box<NetworkStream + Send>>, head: &RequestHead| {
166165
debug!("headers={:?}", head.headers);

src/http/h2.rs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use http::{
1515
};
1616
use net::{NetworkStream, NetworkConnector};
1717
use net::{HttpConnector, HttpStream};
18-
use url::Url;
18+
use url::Position as UrlPosition;
1919
use header::Headers;
2020

2121
use header;
@@ -262,16 +262,6 @@ impl<S> Read for Http2Message<S> where S: CloneableStream {
262262
}
263263
}
264264

265-
/// A helper function that prepares the path of a request by extracting it from the given `Url`.
266-
fn prepare_path(url: Url) -> Vec<u8> {
267-
let mut uri = url.serialize_path().unwrap();
268-
if let Some(ref q) = url.query {
269-
uri.push('?');
270-
uri.push_str(&q[..]);
271-
}
272-
uri.into_bytes()
273-
}
274-
275265
/// A helper function that prepares the headers that should be sent in an HTTP/2 message.
276266
///
277267
/// Adapts the `Headers` into a list of octet string pairs.
@@ -374,7 +364,7 @@ impl<S> HttpMessage for Http2Message<S> where S: CloneableStream {
374364
let (RequestHead { headers, method, url }, body) = (request.head, request.body);
375365

376366
let method = method.as_ref().as_bytes();
377-
let path = prepare_path(url);
367+
let path = url[UrlPosition::BeforePath..UrlPosition::AfterQuery].as_bytes();
378368
let extra_headers = prepare_headers(headers);
379369
let body = prepare_body(body);
380370

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@
130130
131131
extern crate rustc_serialize as serialize;
132132
extern crate time;
133-
extern crate url;
133+
#[macro_use] extern crate url;
134134
#[cfg(feature = "openssl")]
135135
extern crate openssl;
136136
#[cfg(feature = "security-framework")]

src/uri.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl FromStr for RequestUri {
5656
fn from_str(s: &str) -> Result<RequestUri, Error> {
5757
let bytes = s.as_bytes();
5858
if bytes == [] {
59-
Err(Error::Uri(UrlError::InvalidCharacter))
59+
Err(Error::Uri(UrlError::RelativeUrlWithoutBase))
6060
} else if bytes == b"*" {
6161
Ok(RequestUri::Star)
6262
} else if bytes.starts_with(b"/") {

0 commit comments

Comments
 (0)