Upgrade to rust-url 1.0 and hyper 0.9

This commit is contained in:
Simon Sapin 2016-04-21 00:18:37 +02:00
parent 305c283602
commit 7932ab6ac2
76 changed files with 524 additions and 888 deletions

View file

@ -74,7 +74,7 @@ fnv = "1.0"
heapsize = "0.3.0"
heapsize_plugin = "0.1.2"
html5ever = {version = "0.5.1", features = ["heap_size", "unstable"]}
hyper = { version = "0.8", features = [ "serde-serialization" ] }
hyper = { version = "0.9", features = [ "serde-serialization" ] }
image = "0.9"
libc = "0.2"
log = "0.3.5"
@ -94,6 +94,6 @@ smallvec = "0.1"
string_cache = {version = "0.2.12", features = ["heap_size", "unstable"]}
time = "0.1.12"
unicase = "1.0"
url = {version = "0.5.7", features = ["heap_size"]}
url = {version = "1.0.0", features = ["heap_size"]}
uuid = { version = "0.2", features = ["v4"] }
websocket = "0.16.1"
websocket = "0.17"

View file

@ -26,7 +26,7 @@ use std::borrow::ToOwned;
use std::sync::{Arc, Mutex};
use time::{self, Timespec, now};
use unicase::UniCase;
use url::{SchemeData, Url};
use url::Url;
use util::thread::spawn_named;
/// Interface for network listeners concerned with CORS checks. Proper network requests
@ -67,14 +67,13 @@ impl CORSRequest {
headers: Headers,
same_origin_data_url_flag: bool)
-> Result<Option<CORSRequest>, ()> {
if referer.scheme == destination.scheme && referer.host() == destination.host() &&
referer.port() == destination.port() {
if referer.origin() == destination.origin() {
return Ok(None); // Not cross-origin, proceed with a normal fetch
}
match &*destination.scheme {
match destination.scheme() {
// As per (https://fetch.spec.whatwg.org/#main-fetch 5.1.9), about URLs can be fetched
// the same as a basic request.
"about" if destination.path() == Some(&["blank".to_owned()]) => Ok(None),
"about" if destination.path() == "blank" => Ok(None),
// As per (https://fetch.spec.whatwg.org/#main-fetch 5.1.9), data URLs can be fetched
// the same as a basic request if the request's method is GET and the
// same-origin data-URL flag is set.
@ -98,11 +97,9 @@ impl CORSRequest {
method: Method,
headers: Headers)
-> CORSRequest {
if let SchemeData::Relative(ref mut data) = referer.scheme_data {
data.path = vec![];
}
referer.fragment = None;
referer.query = None;
referer.set_fragment(None);
referer.set_query(None);
referer.set_path("");
CORSRequest {
origin: referer,
destination: destination,
@ -404,8 +401,10 @@ impl CORSCache {
self.cleanup();
// Credentials are not yet implemented here
self.0.iter_mut().find(|e| {
e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() &&
e.origin.port() == request.origin.port() && e.url == request.destination &&
e.origin.scheme() == request.origin.scheme() &&
e.origin.host_str() == request.origin.host_str() &&
e.origin.port() == request.origin.port() &&
e.url == request.destination &&
e.header_or_method.match_header(header_name)
})
}
@ -430,8 +429,10 @@ impl CORSCache {
self.cleanup();
// Credentials are not yet implemented here
self.0.iter_mut().find(|e| {
e.origin.scheme == request.origin.scheme && e.origin.host() == request.origin.host() &&
e.origin.port() == request.origin.port() && e.url == request.destination &&
e.origin.scheme() == request.origin.scheme() &&
e.origin.host_str() == request.origin.host_str() &&
e.origin.port() == request.origin.port() &&
e.url == request.destination &&
e.header_or_method.match_method(method)
})
}
@ -484,7 +485,7 @@ fn is_simple_method(m: &Method) -> bool {
pub fn allow_cross_origin_request(req: &CORSRequest, headers: &Headers) -> bool {
match headers.get::<AccessControlAllowOrigin>() {
Some(&AccessControlAllowOrigin::Any) => true, // Not always true, depends on credentials mode
Some(&AccessControlAllowOrigin::Value(ref url)) => req.origin.serialize() == *url,
Some(&AccessControlAllowOrigin::Value(ref url)) => req.origin.as_str() == *url,
Some(&AccessControlAllowOrigin::Null) |
None => false,
}

View file

@ -218,7 +218,7 @@ impl DedicatedWorkerGlobalScope {
parent_sender: Box<ScriptChan + Send>,
own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>) {
let serialized_worker_url = worker_url.serialize();
let serialized_worker_url = worker_url.to_string();
spawn_named(format!("WebWorker for {}", serialized_worker_url), move || {
thread_state::initialize(SCRIPT | IN_WORKER);

View file

@ -515,7 +515,7 @@ impl Document {
self.GetDocumentElement()
} else {
// Step 3 & 4
String::from_utf8(percent_decode(fragid.as_bytes())).ok()
percent_decode(fragid.as_bytes()).decode_utf8().ok()
// Step 5
.and_then(|decoded_fragid| self.get_element_by_id(&Atom::from(decoded_fragid)))
// Step 6
@ -1585,7 +1585,7 @@ impl LayoutDocumentHelpers for LayoutJS<Document> {
/// https://url.spec.whatwg.org/#network-scheme
fn url_has_network_scheme(url: &Url) -> bool {
match &*url.scheme {
match url.scheme() {
"ftp" | "http" | "https" => true,
_ => false,
}
@ -1844,7 +1844,7 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-document-url
fn URL(&self) -> DOMString {
DOMString::from(self.url().serialize())
DOMString::from(self.url().as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
@ -1886,7 +1886,7 @@ impl DocumentMethods for Document {
if let Some(host) = self.origin.host() {
// Step 4.
DOMString::from(host.serialize())
DOMString::from(host.to_string())
} else {
// Step 3.
DOMString::new()

View file

@ -1113,7 +1113,7 @@ impl Element {
// https://html.spec.whatwg.org/multipage/#reflect
// XXXManishearth this doesn't handle `javascript:` urls properly
match base.join(&url) {
Ok(parsed) => DOMString::from(parsed.serialize()),
Ok(parsed) => DOMString::from(parsed.into_string()),
Err(_) => DOMString::from(""),
}
}

View file

@ -82,7 +82,7 @@ impl EventSourceMethods for EventSource {
// https://html.spec.whatwg.org/multipage/#dom-eventsource-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.serialize())
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-eventsource-withcredentials

View file

@ -397,7 +397,7 @@ impl EventTarget {
// Step 1.6
let window = document.window();
let url_serialized = CString::new(handler.url.serialize()).unwrap();
let url_serialized = CString::new(handler.url.to_string()).unwrap();
let name = CString::new(&**ty).unwrap();
static mut ARG_NAMES: [*const c_char; 1] = [b"event\0" as *const u8 as *const c_char];

View file

@ -28,7 +28,7 @@ use dom::virtualmethods::VirtualMethods;
use num_traits::ToPrimitive;
use std::default::Default;
use string_cache::Atom;
use url::{Url, UrlParser};
use url::Url;
use util::str::DOMString;
#[dom_struct]
@ -63,9 +63,7 @@ impl HTMLAnchorElement {
let attribute = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href"));
*self.url.borrow_mut() = attribute.and_then(|attribute| {
let document = document_from_node(self);
let mut parser = UrlParser::new();
parser.base_url(document.url());
parser.parse(&attribute.value()).ok()
document.url().join(&attribute.value()).ok()
});
}
@ -74,8 +72,7 @@ impl HTMLAnchorElement {
// Step 1.
match *self.url.borrow() {
None => return,
Some(ref url) if url.scheme == "blob" &&
url.non_relative_scheme_data().is_some() => return,
Some(ref url) if url.scheme() == "blob" && url.cannot_be_a_base() => return,
_ => (),
}
@ -86,7 +83,7 @@ impl HTMLAnchorElement {
// https://html.spec.whatwg.org/multipage/#update-href
fn update_href(&self) {
self.upcast::<Element>().set_string_attribute(&atom!("href"),
self.url.borrow().as_ref().unwrap().serialize().into());
self.url.borrow().as_ref().unwrap().as_str().into());
}
}
@ -167,7 +164,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.scheme == "javascript" { return; }
if url.scheme() == "javascript" { return; }
// Steps 4-5.
UrlHelper::SetHash(url, value);
// Step 6.
@ -201,7 +198,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.non_relative_scheme_data().is_some() {
if url.cannot_be_a_base() {
return;
}
// Step 4.
@ -233,7 +230,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.non_relative_scheme_data().is_some() {
if url.cannot_be_a_base() {
return;
}
// Step 4.
@ -258,7 +255,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
}
},
// Step 5.
Some(ref url) => url.serialize(),
Some(ref url) => url.as_str().to_owned(),
})
}
@ -289,7 +286,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.host().is_none() || url.non_relative_scheme_data().is_some() {
if url.host().is_none() || url.cannot_be_a_base() {
return;
}
// Step 4.
@ -319,7 +316,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.non_relative_scheme_data().is_some() { return; }
if url.cannot_be_a_base() { return; }
// Step 5.
UrlHelper::SetPathname(url, value);
// Step 6.
@ -348,8 +345,8 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.host().is_none() ||
url.non_relative_scheme_data().is_some() ||
url.scheme == "file" {
url.cannot_be_a_base() ||
url.scheme() == "file" {
return;
}
// Step 4.
@ -435,7 +432,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement {
// Step 3.
if let Some(url) = self.url.borrow_mut().as_mut() {
if url.host().is_none() || url.non_relative_scheme_data().is_some() {
if url.host().is_none() || url.cannot_be_a_base() {
return;
}
@ -535,7 +532,7 @@ fn follow_hyperlink(subject: &Element, hyperlink_suffix: Option<String>) {
};
// Step 7.
debug!("following hyperlink to {}", url.serialize());
debug!("following hyperlink to {}", url);
let window = document.window();
window.load_url(url);
}

View file

@ -68,7 +68,7 @@ impl HTMLBaseElementMethods for HTMLBaseElement {
// Step 1.
if !self.upcast::<Element>().has_attribute(&atom!("href")) {
return DOMString::from(document.base_url().serialize());
return DOMString::from(document.base_url().as_str());
}
// Step 2.
@ -81,7 +81,7 @@ impl HTMLBaseElementMethods for HTMLBaseElement {
let url_record = fallback_base_url.join(&*url);
// Step 5, 6.
DOMString::from(url_record.ok().map_or("".to_owned(), |record| record.serialize()))
DOMString::from(url_record.as_ref().map(|url| url.as_str()).unwrap_or(""))
}
// https://html.spec.whatwg.org/multipage/#dom-base-href

View file

@ -44,7 +44,7 @@ use std::cell::Cell;
use std::sync::mpsc::Sender;
use string_cache::Atom;
use task_source::dom_manipulation::DOMManipulationTask;
use url::form_urlencoded::serialize;
use url::form_urlencoded;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Clone, Copy, HeapSizeOf)]
@ -269,7 +269,7 @@ impl HTMLFormElement {
let mut action = submitter.action();
// Step 8
if action.is_empty() {
action = DOMString::from(base.serialize());
action = DOMString::from(base.as_str());
}
// Step 9-11
let action_components = match base.join(&action) {
@ -277,8 +277,7 @@ impl HTMLFormElement {
Err(_) => return
};
// Step 12-15
let _action = action_components.serialize();
let scheme = action_components.scheme.clone();
let scheme = action_components.scheme().to_owned();
let enctype = submitter.enctype();
let method = submitter.method();
let _target = submitter.target();
@ -290,7 +289,9 @@ impl HTMLFormElement {
FormEncType::UrlEncoded => {
let mime: mime::Mime = "application/x-www-form-urlencoded".parse().unwrap();
load_data.headers.set(ContentType(mime));
serialize(form_data.iter().map(|d| (&*d.name, &*d.value)))
form_urlencoded::Serializer::new(String::new())
.extend_pairs(form_data.into_iter().map(|field| (field.name, field.value)))
.finish()
}
_ => "".to_owned() // TODO: Add serializers for the other encoding types
};
@ -302,7 +303,8 @@ impl HTMLFormElement {
(_, FormMethod::FormDialog) => return, // Unimplemented
// https://html.spec.whatwg.org/multipage/#submit-mutate-action
("http", FormMethod::FormGet) | ("https", FormMethod::FormGet) => {
load_data.url.query = Some(parsed_data);
// FIXME(SimonSapin): use url.query_pairs_mut() here.
load_data.url.set_query(Some(&*parsed_data));
self.plan_to_navigate(load_data, &win);
}
// https://html.spec.whatwg.org/multipage/#submit-body

View file

@ -316,7 +316,7 @@ impl HTMLImageElementMethods for HTMLImageElement {
fn CurrentSrc(&self) -> DOMString {
let ref url = self.current_request.borrow().url;
match *url {
Some(ref url) => DOMString::from(url.serialize()),
Some(ref url) => DOMString::from(url.as_str()),
None => DOMString::from(""),
}
}

View file

@ -448,7 +448,7 @@ impl HTMLScriptElement {
let window = window_from_node(self);
let mut rval = RootedValue::new(window.get_cx(), UndefinedValue());
window.evaluate_script_on_global_with_result(&*source,
&*url.serialize(),
url.as_str(),
rval.handle_mut());
// Step 2.b.7.

View file

@ -99,7 +99,7 @@ macro_rules! make_url_or_base_getter(
let url = element.get_url_attribute(&atom!($htmlname));
if url.is_empty() {
let window = window_from_node(self);
DOMString::from(window.get_url().serialize())
DOMString::from(window.get_url().into_string())
} else {
url
}

View file

@ -274,8 +274,7 @@ impl AsyncResponseListener for ParserContext {
match content_type {
Some(ContentType(Mime(TopLevel::Image, _, _))) => {
self.is_synthesized_document = true;
let page = format!("<html><body><img src='{}' /></body></html>",
self.url.serialize());
let page = format!("<html><body><img src='{}' /></body></html>", self.url);
parser.pending_input().borrow_mut().push(page);
parser.parse_sync();
},
@ -336,7 +335,7 @@ impl AsyncResponseListener for ParserContext {
parser.r().document().finish_load(LoadType::PageSource(self.url.clone()));
if let Err(err) = status {
debug!("Failed to load page URL {}, error: {:?}", self.url.serialize(), err);
debug!("Failed to load page URL {}, error: {:?}", self.url, err);
// TODO(Savago): we should send a notification to callers #5463.
}

View file

@ -13,7 +13,7 @@ use dom::urlhelper::UrlHelper;
use dom::urlsearchparams::URLSearchParams;
use std::borrow::ToOwned;
use std::default::Default;
use url::{Host, Url, UrlParser};
use url::{Host, Url};
use util::str::DOMString;
// https://url.spec.whatwg.org/#url
@ -42,8 +42,9 @@ impl URL {
global, URLBinding::Wrap)
}
pub fn set_query(&self, query: String) {
self.url.borrow_mut().query = Some(query);
pub fn set_query_pairs(&self, pairs: &[(String, String)]) {
let mut url = self.url.borrow_mut();
url.query_pairs_mut().clear().extend_pairs(pairs);
}
}
@ -68,17 +69,11 @@ impl URL {
}
};
// Step 3.
let parsed_url = {
let mut parser = UrlParser::new();
if let Some(parsed_base) = parsed_base.as_ref() {
parser.base_url(parsed_base);
}
match parser.parse(&url.0) {
Ok(url) => url,
Err(error) => {
// Step 4.
return Err(Error::Type(format!("could not parse URL: {}", error)));
}
let parsed_url = match Url::options().base_url(parsed_base.as_ref()).parse(&url.0) {
Ok(url) => url,
Err(error) => {
// Step 4.
return Err(Error::Type(format!("could not parse URL: {}", error)));
}
};
// Step 5: Skip (see step 8 below).
@ -207,7 +202,7 @@ impl URLMethods for URL {
fn SetSearch(&self, value: USVString) {
UrlHelper::SetSearch(&mut self.url.borrow_mut(), value);
if let Some(search_params) = self.search_params.get() {
search_params.set_list(self.url.borrow().query_pairs().unwrap_or_else(|| vec![]));
search_params.set_list(self.url.borrow().query_pairs().into_owned().collect());
}
}

View file

@ -4,166 +4,31 @@
use dom::bindings::str::USVString;
use std::borrow::ToOwned;
use std::fmt::Write;
use url::urlutils::{UrlUtils, UrlUtilsWrapper};
use url::{Origin, SchemeData, Url, UrlParser};
use url::{Url, quirks};
#[derive(HeapSizeOf)]
pub struct UrlHelper;
impl UrlHelper {
pub fn Hash(url: &Url) -> USVString {
USVString(match url.fragment {
None => "".to_owned(),
Some(ref hash) if hash.is_empty() => "".to_owned(),
Some(ref hash) => format!("#{}", hash)
})
}
pub fn SetHash(url: &mut Url, value: USVString) {
url.fragment = Some(String::new());
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_fragment(&value.0);
}
pub fn Host(url: &Url) -> USVString {
USVString(match url.scheme_data {
SchemeData::NonRelative(..) => "".to_owned(),
SchemeData::Relative(ref scheme_data) => {
let mut host = scheme_data.host.serialize();
if let Some(port) = scheme_data.port {
write!(host, ":{}", port).unwrap();
}
host
},
})
}
pub fn SetHost(url: &mut Url, value: USVString) {
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_host(&value.0);
}
pub fn Origin(url: &Url) -> USVString {
USVString(match url.origin() {
Origin::UID(_) => {
// https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin
// If the origin in question is not a scheme/host/port tuple,
// then return the literal string "null" and abort these steps.
"null".to_owned()
},
Origin::Tuple(protocol, host, _) => {
let mut origin =
format!(
"{protocol}://{host}",
protocol = protocol,
host = host
);
if let Some(port) =
// https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin
// only append the port # to the serialized origin if the port is different from
// the default port for the protocol. If url.scheme_data.port is None, that
// indicates that the port is a default port
url.relative_scheme_data().and_then(|scheme| scheme.port) {
write!(origin, ":{}", port).unwrap();
};
origin
}
})
}
pub fn Hostname(url: &Url) -> USVString {
USVString(url.serialize_host().unwrap_or_else(|| "".to_owned()))
}
pub fn SetHostname(url: &mut Url, value: USVString) {
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_host_and_port(&value.0);
}
pub fn Href(url: &Url) -> USVString {
USVString(url.serialize())
}
pub fn Password(url: &Url) -> USVString {
USVString(url.password().unwrap_or("").to_owned())
}
pub fn SetPassword(url: &mut Url, value: USVString) {
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_password(&value.0);
}
pub fn Pathname(url: &Url) -> USVString {
USVString(match url.scheme_data {
SchemeData::NonRelative(ref scheme_data) => scheme_data.clone(),
SchemeData::Relative(..) => url.serialize_path().unwrap()
})
}
pub fn SetPathname(url: &mut Url, value: USVString) {
if let Some(path) = url.path_mut() {
path.clear();
}
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_path(&value.0);
}
pub fn Port(url: &Url) -> USVString {
USVString(match url.port() {
None => "".to_owned(),
Some(port) => port.to_string(),
})
}
pub fn SetPort(url: &mut Url, value: USVString) {
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_port(&value.0);
}
pub fn Protocol(url: &Url) -> USVString {
USVString(format!("{}:", url.scheme.clone()))
}
pub fn SetProtocol(url: &mut Url, value: USVString) {
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_scheme(&value.0);
}
// https://html.spec.whatwg.org/multipage/#same-origin
pub fn SameOrigin(urlA: &Url, urlB: &Url) -> bool {
if urlA.host() != urlB.host() {
return false
}
if urlA.scheme != urlB.scheme {
return false
}
if urlA.port() != urlB.port() {
return false
}
true
}
pub fn Search(url: &Url) -> USVString {
USVString(match url.query {
None => "".to_owned(),
Some(ref query) if query.is_empty() => "".to_owned(),
Some(ref query) => format!("?{}", query)
})
}
pub fn SetSearch(url: &mut Url, value: USVString) {
url.query = Some(String::new());
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_query(&value.0);
}
pub fn Username(url: &Url) -> USVString {
USVString(url.username().unwrap_or("").to_owned())
}
pub fn SetUsername(url: &mut Url, value: USVString) {
let mut wrapper = UrlUtilsWrapper { url: url, parser: &UrlParser::new() };
let _ = wrapper.set_username(&value.0);
}
pub fn SameOrigin(urlA: &Url, urlB: &Url) -> bool { urlA.origin() == urlB.origin() }
pub fn Origin(url: &Url) -> USVString { USVString(quirks::origin(url)) }
pub fn Href(url: &Url) -> USVString { USVString(quirks::href(url).to_owned()) }
pub fn Hash(url: &Url) -> USVString { USVString(quirks::hash(url).to_owned()) }
pub fn Host(url: &Url) -> USVString { USVString(quirks::host(url).to_owned()) }
pub fn Port(url: &Url) -> USVString { USVString(quirks::port(url).to_owned()) }
pub fn Search(url: &Url) -> USVString { USVString(quirks::search(url).to_owned()) }
pub fn Hostname(url: &Url) -> USVString { USVString(quirks::hostname(url).to_owned()) }
pub fn Password(url: &Url) -> USVString { USVString(quirks::password(url).to_owned()) }
pub fn Pathname(url: &Url) -> USVString { USVString(quirks::pathname(url).to_owned()) }
pub fn Protocol(url: &Url) -> USVString { USVString(quirks::protocol(url).to_owned()) }
pub fn Username(url: &Url) -> USVString { USVString(quirks::username(url).to_owned()) }
pub fn SetHash(url: &mut Url, value: USVString) { quirks::set_hash(url, &value.0) }
pub fn SetHost(url: &mut Url, value: USVString) { let _ = quirks::set_host(url, &value.0); }
pub fn SetPort(url: &mut Url, value: USVString) { let _ = quirks::set_port(url, &value.0); }
pub fn SetSearch(url: &mut Url, value: USVString) { quirks::set_search(url, &value.0) }
pub fn SetPathname(url: &mut Url, value: USVString) { quirks::set_pathname(url, &value.0) }
pub fn SetHostname(url: &mut Url, value: USVString) { let _ = quirks::set_hostname(url, &value.0); }
pub fn SetPassword(url: &mut Url, value: USVString) { let _ = quirks::set_password(url, &value.0); }
pub fn SetProtocol(url: &mut Url, value: USVString) { let _ = quirks::set_protocol(url, &value.0); }
pub fn SetUsername(url: &mut Url, value: USVString) { let _ = quirks::set_username(url, &value.0); }
}

View file

@ -14,7 +14,7 @@ use dom::bindings::str::USVString;
use dom::bindings::weakref::MutableWeakRef;
use dom::url::URL;
use encoding::types::EncodingRef;
use url::form_urlencoded::{parse, serialize_with_encoding};
use url::form_urlencoded;
use util::str::DOMString;
// https://url.spec.whatwg.org/#interface-urlsearchparams
@ -49,7 +49,8 @@ impl URLSearchParams {
match init {
Some(USVStringOrURLSearchParams::USVString(init)) => {
// Step 2.
*query.list.borrow_mut() = parse(init.0.as_bytes());
*query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes())
.into_owned().collect();
},
Some(USVStringOrURLSearchParams::URLSearchParams(init)) => {
// Step 3.
@ -145,7 +146,10 @@ impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
pub fn serialize(&self, encoding: Option<EncodingRef>) -> String {
let list = self.list.borrow();
serialize_with_encoding(list.iter(), encoding)
form_urlencoded::Serializer::new(String::new())
.encoding_override(encoding)
.extend_pairs(&*list)
.finish()
}
}
@ -154,7 +158,7 @@ impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
fn update_steps(&self) {
if let Some(url) = self.url.root() {
url.set_query(self.serialize(None));
url.set_query_pairs(&self.list.borrow())
}
}
}

View file

@ -210,7 +210,7 @@ impl WebSocket {
// Step 2: Disallow https -> ws connections.
// Step 3: Potentially block access to some ports.
let port: u16 = resource_url.port_or_default().unwrap();
let port: u16 = resource_url.port_or_known_default().unwrap();
if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) {
return Err(Error::Security);
@ -356,7 +356,7 @@ impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.serialize())
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate

View file

@ -225,7 +225,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
};
match self.runtime.evaluate_script(
self.reflector().get_jsobject(), source, url.serialize(), 1) {
self.reflector().get_jsobject(), source, url.to_string(), 1) {
Ok(_) => (),
Err(_) => {
println!("evaluate_script failed");
@ -317,7 +317,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
impl WorkerGlobalScope {
pub fn execute_script(&self, source: DOMString) {
match self.runtime.evaluate_script(
self.reflector().get_jsobject(), String::from(source), self.worker_url.serialize(), 1) {
self.reflector().get_jsobject(), String::from(source), self.worker_url.to_string(), 1) {
Ok(_) => (),
Err(_) => {
if self.is_closing() {

View file

@ -60,8 +60,7 @@ use std::sync::{Arc, Mutex};
use string_cache::Atom;
use time;
use timers::{OneshotTimerCallback, OneshotTimerHandle};
use url::Url;
use url::percent_encoding::{utf8_percent_encode, USERNAME_ENCODE_SET, PASSWORD_ENCODE_SET};
use url::{Url, Position};
use util::prefs;
use util::str::DOMString;
@ -360,15 +359,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
// Step 9
if parsed_url.host().is_some() {
if let Some(scheme_data) = parsed_url.relative_scheme_data_mut() {
if let Some(user_str) = username {
scheme_data.username = utf8_percent_encode(&user_str.0, USERNAME_ENCODE_SET);
// ensure that the password is mutated when a username is provided
scheme_data.password = password.map(|pass_str| {
utf8_percent_encode(&pass_str.0, PASSWORD_ENCODE_SET)
});
}
if let Some(user_str) = username {
parsed_url.set_username(&user_str.0).unwrap();
let password = password.as_ref().map(|pass_str| &*pass_str.0);
parsed_url.set_password(password).unwrap();
}
}
@ -628,24 +622,8 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
true);
match cors_request {
Ok(None) => {
let mut buf = String::new();
buf.push_str(&referer_url.scheme);
buf.push_str("://");
if let Some(ref h) = referer_url.serialize_host() {
buf.push_str(h);
}
if let Some(ref p) = referer_url.port().as_ref() {
buf.push_str(":");
buf.push_str(&p.to_string());
}
if let Some(ref h) = referer_url.serialize_path() {
buf.push_str(h);
}
self.request_headers.borrow_mut().set_raw("Referer".to_owned(), vec![buf.into_bytes()]);
let bytes = referer_url[..Position::AfterPath].as_bytes().to_vec();
self.request_headers.borrow_mut().set_raw("Referer".to_owned(), vec![bytes]);
},
Ok(Some(ref req)) => self.insert_trusted_header("origin".to_owned(),
req.origin.to_string()),
@ -909,7 +887,7 @@ impl XMLHttpRequest {
debug!("Bypassing cross origin check");
}
*self.response_url.borrow_mut() = metadata.final_url.serialize_no_fragment();
*self.response_url.borrow_mut() = metadata.final_url[..Position::AfterQuery].to_owned();
// XXXManishearth Clear cache entries in case of a network error
self.process_partial_response(XHRProgress::HeadersReceived(gen_id, metadata.headers, metadata.status));

View file

@ -2,9 +2,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::cell::RefCell;
use ref_filter_map::ref_filter_map;
use std::cell::{RefCell, Ref};
use std::rc::Rc;
use url::{OpaqueOrigin, Origin as UrlOrigin};
use url::Origin as UrlOrigin;
use url::{Url, Host};
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
@ -21,9 +22,8 @@ no_jsmanaged_fields!(Origin);
impl Origin {
/// Create a new origin comprising a unique, opaque identifier.
pub fn opaque_identifier() -> Origin {
let opaque = UrlOrigin::UID(OpaqueOrigin::new());
Origin {
inner: Rc::new(RefCell::new(opaque)),
inner: Rc::new(RefCell::new(UrlOrigin::new_opaque())),
}
}
@ -40,18 +40,15 @@ impl Origin {
/// Does this origin represent a host/scheme/port tuple?
pub fn is_scheme_host_port_tuple(&self) -> bool {
match *self.inner.borrow() {
UrlOrigin::Tuple(..) => true,
UrlOrigin::UID(..) => false,
}
self.inner.borrow().is_tuple()
}
/// Return the host associated with this origin.
pub fn host(&self) -> Option<Host> {
match *self.inner.borrow() {
UrlOrigin::Tuple(_, ref host, _) => Some(host.clone()),
UrlOrigin::UID(..) => None,
}
pub fn host(&self) -> Option<Ref<Host<String>>> {
ref_filter_map(self.inner.borrow(), |origin| match *origin {
UrlOrigin::Tuple(_, ref host, _) => Some(host),
UrlOrigin::Opaque(..) => None,
})
}
/// https://html.spec.whatwg.org/multipage/#same-origin

View file

@ -100,7 +100,7 @@ use task_source::history_traversal::HistoryTraversalTaskSource;
use task_source::networking::NetworkingTaskSource;
use task_source::user_interaction::UserInteractionTaskSource;
use time::Tm;
use url::Url;
use url::{Url, Position};
use util::opts;
use util::str::DOMString;
use util::thread;
@ -1132,8 +1132,7 @@ impl ScriptThread {
if let Some(root_page) = self.page.borrow().as_ref() {
for it_page in root_page.iter() {
let current_url = it_page.document().url().serialize();
urls.push(current_url.clone());
let current_url = it_page.document().url().to_string();
for child in it_page.document().upcast::<Node>().traverse_preorder() {
dom_tree_size += heap_size_of_self_and_children(&*child);
@ -1145,7 +1144,8 @@ impl ScriptThread {
path: path![format!("url({})", current_url), "dom-tree"],
kind: ReportKind::ExplicitJemallocHeapSize,
size: dom_tree_size,
})
});
urls.push(current_url);
}
}
let path_seg = format!("url({})", urls.join(", "));
@ -1387,7 +1387,7 @@ impl ScriptThread {
let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(ConstellationMsg::SetFinalUrl(incomplete.pipeline_id, final_url.clone())).unwrap();
}
debug!("ScriptThread: loading {} on page {:?}", incomplete.url.serialize(), incomplete.pipeline_id);
debug!("ScriptThread: loading {} on page {:?}", incomplete.url, incomplete.pipeline_id);
let frame_element = incomplete.parent_info.and_then(|(parent_id, subpage_id)| {
// The root page may not exist yet, if the parent of this frame
@ -1554,30 +1554,22 @@ impl ScriptThread {
// Notify devtools that a new script global exists.
self.notify_devtools(document.Title(), final_url.clone(), (page.pipeline(), None));
let is_javascript = incomplete.url.scheme == "javascript";
let is_javascript = incomplete.url.scheme() == "javascript";
let parse_input = if is_javascript {
use url::percent_encoding::percent_decode_to;
use url::percent_encoding::percent_decode;
// Turn javascript: URL into JS code to eval, according to the steps in
// https://html.spec.whatwg.org/multipage/#javascript-protocol
let _ar = JSAutoRequest::new(self.get_cx());
let mut script_source_bytes = Vec::new();
// Start with the scheme data of the parsed URL (5.), while percent-decoding (8.)
percent_decode_to(incomplete.url.non_relative_scheme_data().unwrap().as_bytes(),
&mut script_source_bytes);
// Append question mark and query component, if any (6.), while percent-decoding (8.)
if let Some(ref query) = incomplete.url.query {
script_source_bytes.push(b'?');
percent_decode_to(query.as_bytes(), &mut script_source_bytes);
}
// Append number sign and fragment component if any (7.), while percent-decoding (8.)
if let Some(ref fragment) = incomplete.url.fragment {
script_source_bytes.push(b'#');
percent_decode_to(fragment.as_bytes(), &mut script_source_bytes);
}
// UTF-8 decode (9.)
let script_source = String::from_utf8_lossy(&script_source_bytes);
// This slice of the URLs serialization is equivalent to (5.) to (7.):
// Start with the scheme data of the parsed URL;
// append question mark and query component, if any;
// append number sign and fragment component if any.
let encoded = &incomplete.url[Position::BeforePath..];
// Percent-decode (8.) and UTF-8 decode (9.)
let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
// Script source is ready to be evaluated (11.)
unsafe {
@ -1706,7 +1698,7 @@ impl ScriptThread {
.and_then(|href| {
let value = href.value();
let url = document.url();
url.join(&value).map(|url| url.serialize()).ok()
url.join(&value).map(|url| url.to_string()).ok()
});
let event = ConstellationMsg::NodeStatus(status);
@ -1795,14 +1787,14 @@ impl ScriptThread {
// Step 8.
{
let nurl = &load_data.url;
if let Some(ref fragment) = nurl.fragment {
if let Some(fragment) = nurl.fragment() {
let page = get_page(&self.root_page(), pipeline_id);
let document = page.document();
let document = document.r();
let url = document.url();
if url.scheme == nurl.scheme && url.scheme_data == nurl.scheme_data &&
url.query == nurl.query && load_data.method == Method::Get {
match document.find_fragment_node(&*fragment) {
if &url[..Position::AfterQuery] == &nurl[..Position::AfterQuery] &&
load_data.method == Method::Get {
match document.find_fragment_node(fragment) {
Some(ref node) => {
self.scroll_fragment_point(pipeline_id, node.r());
}
@ -1881,7 +1873,7 @@ impl ScriptThread {
sender: action_sender,
};
if load_data.url.scheme == "javascript" {
if load_data.url.scheme() == "javascript" {
load_data.url = Url::parse("about:blank").unwrap();
}
@ -1928,7 +1920,7 @@ impl ScriptThread {
// https://html.spec.whatwg.org/multipage/#the-end steps 3-4.
document.process_deferred_scripts();
window.set_fragment_name(final_url.fragment.clone());
window.set_fragment_name(final_url.fragment().map(str::to_owned));
}
fn handle_css_error_reporting(&self, pipeline_id: PipelineId, filename: String,