Move to to_owned rather than into_string.

into_string has been removed from Rust.
This commit is contained in:
Ms2ger 2015-01-20 14:45:36 +01:00
parent 2d5b0e0855
commit 01ed338746
67 changed files with 473 additions and 383 deletions

View file

@ -3,6 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geom::{Point2D, Rect, Size2D}; use geom::{Point2D, Rect, Size2D};
use std::borrow::ToOwned;
use std::mem; use std::mem;
use std::slice; use std::slice;
use std::rc::Rc; use std::rc::Rc;
@ -162,7 +163,7 @@ impl Font {
let glyphs = Arc::new(glyphs); let glyphs = Arc::new(glyphs);
self.shape_cache.insert(ShapeCacheEntry { self.shape_cache.insert(ShapeCacheEntry {
text: text.into_string(), text: text.to_owned(),
options: *options, options: *options,
}, glyphs.clone()); }, glyphs.clone());
glyphs glyphs

View file

@ -17,6 +17,7 @@ use servo_util::smallvec::{SmallVec, SmallVec8};
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::arc_ptr_eq; use servo_util::arc_ptr_eq;
use std::borrow::ToOwned;
use std::rc::Rc; use std::rc::Rc;
use std::cell::RefCell; use std::cell::RefCell;
use std::sync::Arc; use std::sync::Arc;
@ -168,7 +169,7 @@ impl FontContext {
if !cache_hit { if !cache_hit {
let font_template = self.font_cache_task.get_font_template(family.name() let font_template = self.font_cache_task.get_font_template(family.name()
.into_string(), .to_owned(),
desc.clone()); desc.clone());
match font_template { match font_template {
Some(font_template) => { Some(font_template) => {
@ -178,14 +179,14 @@ impl FontContext {
style.font_variant); style.font_variant);
let layout_font = Rc::new(RefCell::new(layout_font)); let layout_font = Rc::new(RefCell::new(layout_font));
self.layout_font_cache.push(LayoutFontCacheEntry { self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().into_string(), family: family.name().to_owned(),
font: Some(layout_font.clone()), font: Some(layout_font.clone()),
}); });
fonts.push(layout_font); fonts.push(layout_font);
} }
None => { None => {
self.layout_font_cache.push(LayoutFontCacheEntry { self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().into_string(), family: family.name().to_owned(),
font: None, font: None,
}); });
} }

View file

@ -7,6 +7,7 @@ use platform::font_context::FontContextHandle;
use platform::font::FontHandle; use platform::font::FontHandle;
use platform::font_template::FontTemplateData; use platform::font_template::FontTemplateData;
use std::borrow::ToOwned;
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use font::FontHandleMethods; use font::FontHandleMethods;
@ -68,7 +69,7 @@ impl FontTemplate {
}; };
FontTemplate { FontTemplate {
identifier: identifier.into_string(), identifier: identifier.to_owned(),
descriptor: None, descriptor: None,
weak_ref: maybe_weak_ref, weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref, strong_ref: maybe_strong_ref,

View file

@ -22,6 +22,7 @@ use fontconfig::fontconfig::{
use libc; use libc;
use libc::c_int; use libc::c_int;
use std::borrow::ToOwned;
use std::ptr; use std::ptr;
use std::string::String; use std::string::String;
@ -127,13 +128,13 @@ pub fn get_system_default_family(generic_name: &str) -> Option<String> {
#[cfg(target_os="linux")] #[cfg(target_os="linux")]
pub fn get_last_resort_font_families() -> Vec<String> { pub fn get_last_resort_font_families() -> Vec<String> {
vec!( vec!(
"Fira Sans".into_string(), "Fira Sans".to_owned(),
"DejaVu Sans".into_string(), "DejaVu Sans".to_owned(),
"Arial".into_string() "Arial".to_owned()
) )
} }
#[cfg(target_os="android")] #[cfg(target_os="android")]
pub fn get_last_resort_font_families() -> Vec<String> { pub fn get_last_resort_font_families() -> Vec<String> {
vec!("Roboto".into_string()) vec!("Roboto".to_owned())
} }

View file

@ -2,6 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::borrow::ToOwned;
use std::io; use std::io;
use std::io::File; use std::io::File;
@ -29,7 +30,7 @@ impl FontTemplateData {
FontTemplateData { FontTemplateData {
bytes: bytes, bytes: bytes,
identifier: identifier.into_string(), identifier: identifier.to_owned(),
} }
} }
} }

View file

@ -6,6 +6,8 @@ use core_foundation::base::TCFType;
use core_foundation::string::{CFString, CFStringRef}; use core_foundation::string::{CFString, CFStringRef};
use core_text::font_descriptor::{CTFontDescriptor, CTFontDescriptorRef}; use core_text::font_descriptor::{CTFontDescriptor, CTFontDescriptorRef};
use core_text; use core_text;
use std::borrow::ToOwned;
use std::mem; use std::mem;
pub fn get_available_families(callback: |String|) { pub fn get_available_families(callback: |String|) {
@ -42,5 +44,5 @@ pub fn get_system_default_family(_generic_name: &str) -> Option<String> {
} }
pub fn get_last_resort_font_families() -> Vec<String> { pub fn get_last_resort_font_families() -> Vec<String> {
vec!("Arial Unicode MS".into_string(), "Arial".into_string()) vec!("Arial Unicode MS".to_owned(), "Arial".to_owned())
} }

View file

@ -7,6 +7,8 @@ use core_graphics::font::CGFont;
use core_text::font::CTFont; use core_text::font::CTFont;
use core_text; use core_text;
use std::borrow::ToOwned;
/// Platform specific font representation for mac. /// Platform specific font representation for mac.
/// The identifier is a PostScript font name. The /// The identifier is a PostScript font name. The
/// CTFont object is cached here for use by the /// CTFont object is cached here for use by the
@ -34,7 +36,7 @@ impl FontTemplateData {
FontTemplateData { FontTemplateData {
ctfont: ctfont, ctfont: ctfont,
identifier: identifier.into_string(), identifier: identifier.to_owned(),
} }
} }
} }

View file

@ -50,6 +50,7 @@ use script::dom::htmlelement::HTMLElementTypeId;
use script::dom::htmlobjectelement::is_image_data; use script::dom::htmlobjectelement::is_image_data;
use script::dom::node::NodeTypeId; use script::dom::node::NodeTypeId;
use servo_util::opts; use servo_util::opts;
use std::borrow::ToOwned;
use std::collections::DList; use std::collections::DList;
use std::mem; use std::mem;
use std::sync::atomic::Relaxed; use std::sync::atomic::Relaxed;
@ -455,7 +456,7 @@ impl<'a> FlowConstructor<'a> {
// Add whitespace results. They will be stripped out later on when // Add whitespace results. They will be stripped out later on when
// between block elements, and retained when between inline elements. // between block elements, and retained when between inline elements.
let fragment_info = let fragment_info =
SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text(" ".into_string())); SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text(" ".to_owned()));
let fragment = Fragment::from_opaque_node_and_style(whitespace_node, let fragment = Fragment::from_opaque_node_and_style(whitespace_node,
whitespace_style, whitespace_style,
whitespace_damage, whitespace_damage,
@ -652,7 +653,7 @@ impl<'a> FlowConstructor<'a> {
whitespace_damage)) => { whitespace_damage)) => {
// Instantiate the whitespace fragment. // Instantiate the whitespace fragment.
let fragment_info = SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text( let fragment_info = SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text(
" ".into_string())); " ".to_owned()));
let fragment = Fragment::from_opaque_node_and_style(whitespace_node, let fragment = Fragment::from_opaque_node_and_style(whitespace_node,
whitespace_style, whitespace_style,
whitespace_damage, whitespace_damage,
@ -986,7 +987,7 @@ impl<'a> FlowConstructor<'a> {
.list_style_type) { .list_style_type) {
None => None, None => None,
Some(text) => { Some(text) => {
let text = text.into_string(); let text = text.to_owned();
let mut unscanned_marker_fragments = DList::new(); let mut unscanned_marker_fragments = DList::new();
unscanned_marker_fragments.push_back(Fragment::new_from_specific_info( unscanned_marker_fragments.push_back(Fragment::new_from_specific_info(
node, node,

View file

@ -14,6 +14,7 @@ use servo_util::bloom::BloomFilter;
use servo_util::cache::{Cache, LRUCache, SimpleHashCache}; use servo_util::cache::{Cache, LRUCache, SimpleHashCache};
use servo_util::smallvec::{SmallVec, SmallVec16}; use servo_util::smallvec::{SmallVec, SmallVec16};
use servo_util::arc_ptr_eq; use servo_util::arc_ptr_eq;
use std::borrow::ToOwned;
use std::mem; use std::mem;
use std::hash::{Hash, sip}; use std::hash::{Hash, sip};
use std::slice::Items; use std::slice::Items;
@ -237,7 +238,7 @@ impl StyleSharingCandidate {
parent_style: parent_style, parent_style: parent_style,
local_name: element.get_local_name().clone(), local_name: element.get_local_name().clone(),
class: element.get_attr(&ns!(""), &atom!("class")) class: element.get_attr(&ns!(""), &atom!("class"))
.map(|string| string.into_string()), .map(|string| string.to_owned()),
link: element.get_link().is_some(), link: element.get_link().is_some(),
namespace: (*element.get_namespace()).clone(), namespace: (*element.get_namespace()).clone(),
common_style_affecting_attributes: common_style_affecting_attributes:

View file

@ -10,6 +10,8 @@
use flow_ref::FlowRef; use flow_ref::FlowRef;
use flow; use flow;
use serialize::json; use serialize::json;
use std::borrow::ToOwned;
use std::cell::RefCell; use std::cell::RefCell;
use std::io::File; use std::io::File;
use std::sync::atomic::{AtomicUint, SeqCst, INIT_ATOMIC_UINT}; use std::sync::atomic::{AtomicUint, SeqCst, INIT_ATOMIC_UINT};
@ -105,7 +107,7 @@ pub fn begin_trace(flow_root: FlowRef) {
STATE_KEY.with(|ref r| { STATE_KEY.with(|ref r| {
let flow_trace = json::encode(&flow::base(flow_root.deref())); let flow_trace = json::encode(&flow::base(flow_root.deref()));
let state = State { let state = State {
scope_stack: vec![box ScopeData::new("root".into_string(), flow_trace)], scope_stack: vec![box ScopeData::new("root".to_owned(), flow_trace)],
flow_root: flow_root.clone(), flow_root: flow_root.clone(),
}; };
*r.borrow_mut() = Some(state); *r.borrow_mut() = Some(state);

View file

@ -59,6 +59,7 @@ use servo_util::task_state;
use servo_util::time::{TimeProfilerCategory, ProfilerMetadata, TimeProfilerChan}; use servo_util::time::{TimeProfilerCategory, ProfilerMetadata, TimeProfilerChan};
use servo_util::time::{TimerMetadataFrameType, TimerMetadataReflowType, profile}; use servo_util::time::{TimerMetadataFrameType, TimerMetadataReflowType, profile};
use servo_util::workqueue::WorkQueue; use servo_util::workqueue::WorkQueue;
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
use std::comm::{channel, Sender, Receiver, Select}; use std::comm::{channel, Sender, Receiver, Select};
use std::mem; use std::mem;
@ -499,7 +500,7 @@ impl LayoutTask {
// GWTODO: Need to handle unloading web fonts (when we handle unloading stylesheets!) // GWTODO: Need to handle unloading web fonts (when we handle unloading stylesheets!)
let mut rw_data = self.lock_rw_data(possibly_locked_rw_data); let mut rw_data = self.lock_rw_data(possibly_locked_rw_data);
iter_font_face_rules(&sheet, &rw_data.stylist.device, |family, src| { iter_font_face_rules(&sheet, &rw_data.stylist.device, |family, src| {
self.font_cache_task.add_web_font(family.into_string(), (*src).clone()); self.font_cache_task.add_web_font(family.to_owned(), (*src).clone());
}); });
rw_data.stylist.add_stylesheet(sheet); rw_data.stylist.add_stylesheet(sheet);
LayoutTask::return_rw_data(possibly_locked_rw_data, rw_data); LayoutTask::return_rw_data(possibly_locked_rw_data, rw_data);

View file

@ -67,6 +67,7 @@ use style::{LengthAttribute, PropertyDeclarationBlock, SimpleColorAttribute};
use style::{TElement, TElementAttributes, TNode, UnsignedIntegerAttribute}; use style::{TElement, TElementAttributes, TNode, UnsignedIntegerAttribute};
use url::Url; use url::Url;
use std::borrow::ToOwned;
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
/// Allows some convenience methods on generic layout nodes. /// Allows some convenience methods on generic layout nodes.
@ -212,7 +213,7 @@ impl<'ln> TLayoutNode for LayoutNode<'ln> {
fn text(&self) -> String { fn text(&self) -> String {
unsafe { unsafe {
if let Some(text) = TextCast::to_js(self.get_jsmanaged()) { if let Some(text) = TextCast::to_js(self.get_jsmanaged()) {
(*text.unsafe_get()).characterdata().data_for_layout().into_string() (*text.unsafe_get()).characterdata().data_for_layout().to_owned()
} else if let Some(input) = HTMLInputElementCast::to_js(self.get_jsmanaged()) { } else if let Some(input) = HTMLInputElementCast::to_js(self.get_jsmanaged()) {
input.get_value_for_layout() input.get_value_for_layout()
} else if let Some(area) = HTMLTextAreaElementCast::to_js(self.get_jsmanaged()) { } else if let Some(area) = HTMLTextAreaElementCast::to_js(self.get_jsmanaged()) {
@ -652,10 +653,10 @@ fn get_content(content_list: &content::T) -> String {
let iter = &mut value.clone().into_iter().peekable(); let iter = &mut value.clone().into_iter().peekable();
match iter.next() { match iter.next() {
Some(content::ContentItem::StringContent(content)) => content, Some(content::ContentItem::StringContent(content)) => content,
_ => "".into_string(), _ => "".to_owned(),
} }
} }
_ => "".into_string(), _ => "".to_owned(),
} }
} }

View file

@ -10,6 +10,7 @@ use url::Url;
use hyper::http::RawStatus; use hyper::http::RawStatus;
use servo_util::resource_files::resources_dir_path; use servo_util::resource_files::resources_dir_path;
use std::borrow::ToOwned;
use std::io::fs::PathExtensions; use std::io::fs::PathExtensions;
pub fn factory(mut load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { pub fn factory(mut load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) {
@ -24,7 +25,7 @@ pub fn factory(mut load_data: LoadData, start_chan: Sender<TargetedLoadResponse>
content_type: Some(("text".to_string(), "html".to_string())), content_type: Some(("text".to_string(), "html".to_string())),
charset: Some("utf-8".to_string()), charset: Some("utf-8".to_string()),
headers: None, headers: None,
status: Some(RawStatus(200, "OK".into_string())) status: Some(RawStatus(200, "OK".to_owned()))
}); });
chan.send(Done(Ok(()))); chan.send(Done(Ok(())));
return return

View file

@ -15,6 +15,8 @@ use std::io::Reader;
use servo_util::task::spawn_named; use servo_util::task::spawn_named;
use url::{Url, UrlParser}; use url::{Url, UrlParser};
use std::borrow::ToOwned;
pub fn factory(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) { pub fn factory(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) {
spawn_named("http_loader", proc() load(load_data, start_chan)) spawn_named("http_loader", proc() load(load_data, start_chan))
} }
@ -85,7 +87,7 @@ fn load(load_data: LoadData, start_chan: Sender<TargetedLoadResponse>) {
// FIXME(seanmonstar): use AcceptEncoding from Hyper once available // FIXME(seanmonstar): use AcceptEncoding from Hyper once available
//if !req.headers.has::<AcceptEncoding>() { //if !req.headers.has::<AcceptEncoding>() {
// We currently don't support HTTP Compression (FIXME #2587) // We currently don't support HTTP Compression (FIXME #2587)
req.headers_mut().set_raw("Accept-Encoding".into_string(), vec![b"identity".to_vec()]); req.headers_mut().set_raw("Accept-Encoding".to_owned(), vec![b"identity".to_vec()]);
//} //}
let writer = match load_data.data { let writer = match load_data.data {
Some(ref data) => { Some(ref data) => {

View file

@ -20,6 +20,7 @@ use hyper::method::Method;
use hyper::mime::{Mime, Attr}; use hyper::mime::{Mime, Attr};
use url::Url; use url::Url;
use std::borrow::ToOwned;
use std::comm::{channel, Receiver, Sender}; use std::comm::{channel, Receiver, Sender};
pub enum ControlMsg { pub enum ControlMsg {
@ -86,7 +87,7 @@ impl Metadata {
charset: None, charset: None,
headers: None, headers: None,
// http://fetch.spec.whatwg.org/#concept-response-status-message // http://fetch.spec.whatwg.org/#concept-response-status-message
status: Some(RawStatus(200, "OK".into_string())) status: Some(RawStatus(200, "OK".to_owned()))
} }
} }

View file

@ -8,9 +8,9 @@ use rustc::middle::ty::expr_ty;
use rustc::middle::ty; use rustc::middle::ty;
declare_lint!(STR_TO_STRING, Deny, declare_lint!(STR_TO_STRING, Deny,
"Warn when a String could use into_string() instead of to_string()") "Warn when a String could use to_owned() instead of to_string()")
/// Prefer str.into_string() over str.to_string() /// Prefer str.to_owned() over str.to_string()
/// ///
/// The latter creates a `Formatter` and is 5x slower than the former /// The latter creates a `Formatter` and is 5x slower than the former
pub struct StrToStringPass; pub struct StrToStringPass;
@ -26,7 +26,7 @@ impl LintPass for StrToStringPass {
if method.node.as_str() == "to_string" if method.node.as_str() == "to_string"
&& is_str(cx, &*args[0]) => { && is_str(cx, &*args[0]) => {
cx.span_lint(STR_TO_STRING, expr.span, cx.span_lint(STR_TO_STRING, expr.span,
"str.into_string() is more efficient than str.to_string(), please use it instead"); "str.to_owned() is more efficient than str.to_string(), please use it instead");
}, },
_ => () _ => ()
} }

View file

@ -11,6 +11,7 @@ use dom::eventtarget::{EventTarget, EventTargetHelpers};
use dom::mouseevent::MouseEvent; use dom::mouseevent::MouseEvent;
use dom::node::window_from_node; use dom::node::window_from_node;
use std::borrow::ToOwned;
/// Trait for elements with defined activation behavior /// Trait for elements with defined activation behavior
pub trait Activatable : Copy { pub trait Activatable : Copy {
@ -44,7 +45,7 @@ pub trait Activatable : Copy {
// https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-mouse-event // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-mouse-event
let win = window_from_node(element.r()).root(); let win = window_from_node(element.r()).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(element.r()); let target: JSRef<EventTarget> = EventTargetCast::from_ref(element.r());
let mouse = MouseEvent::new(win.r(), "click".into_string(), let mouse = MouseEvent::new(win.r(), "click".to_owned(),
false, false, Some(win.r()), 1, false, false, Some(win.r()), 1,
0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey, 0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey,
0, None).root(); 0, None).root();

View file

@ -20,6 +20,7 @@ use servo_util::str::{DOMString, split_html_space_chars};
use string_cache::{Atom, Namespace}; use string_cache::{Atom, Namespace};
use std::borrow::ToOwned;
use std::cell::Ref; use std::cell::Ref;
use std::mem; use std::mem;
@ -138,11 +139,11 @@ impl Attr {
impl<'a> AttrMethods for JSRef<'a, Attr> { impl<'a> AttrMethods for JSRef<'a, Attr> {
fn LocalName(self) -> DOMString { fn LocalName(self) -> DOMString {
self.local_name().as_slice().into_string() self.local_name().as_slice().to_owned()
} }
fn Value(self) -> DOMString { fn Value(self) -> DOMString {
self.value().as_slice().into_string() self.value().as_slice().to_owned()
} }
fn SetValue(self, value: DOMString) { fn SetValue(self, value: DOMString) {
@ -175,14 +176,14 @@ impl<'a> AttrMethods for JSRef<'a, Attr> {
} }
fn Name(self) -> DOMString { fn Name(self) -> DOMString {
self.name.as_slice().into_string() self.name.as_slice().to_owned()
} }
fn GetNamespaceURI(self) -> Option<DOMString> { fn GetNamespaceURI(self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace; let Namespace(ref atom) = self.namespace;
match atom.as_slice() { match atom.as_slice() {
"" => None, "" => None,
url => Some(url.into_string()), url => Some(url.to_owned()),
} }
} }
@ -237,7 +238,7 @@ impl<'a> AttrHelpers<'a> for JSRef<'a, Attr> {
fn summarize(self) -> AttrInfo { fn summarize(self) -> AttrInfo {
let Namespace(ref ns) = self.namespace; let Namespace(ref ns) = self.namespace;
AttrInfo { AttrInfo {
namespace: ns.as_slice().into_string(), namespace: ns.as_slice().to_owned(),
name: self.Name(), name: self.Name(),
value: self.Value(), value: self.Value(),
} }

View file

@ -674,7 +674,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
default = "None" default = "None"
else: else:
assert defaultValue.type.tag() == IDLType.Tags.domstring assert defaultValue.type.tag() == IDLType.Tags.domstring
value = "str::from_utf8(&data).unwrap().into_string()" value = "str::from_utf8(&data).unwrap().to_owned()"
if type.nullable(): if type.nullable():
value = "Some(%s)" % value value = "Some(%s)" % value
@ -4584,6 +4584,7 @@ class CGBindingRoot(CGThing):
'page::JSPageInfo', 'page::JSPageInfo',
'libc', 'libc',
'servo_util::str::DOMString', 'servo_util::str::DOMString',
'std::borrow::ToOwned',
'std::cmp', 'std::cmp',
'std::iter::repeat', 'std::iter::repeat',
'std::mem', 'std::mem',

View file

@ -28,6 +28,7 @@ use js::jsval::{UndefinedValue, NullValue, BooleanValue, Int32Value, UInt32Value
use js::jsval::{StringValue, ObjectValue, ObjectOrNullValue}; use js::jsval::{StringValue, ObjectValue, ObjectOrNullValue};
use libc; use libc;
use std::borrow::ToOwned;
use std::default; use std::default;
use std::slice; use std::slice;
@ -289,7 +290,7 @@ pub fn jsid_to_str(cx: *mut JSContext, id: jsid) -> DOMString {
impl FromJSValConvertible<StringificationBehavior> for DOMString { impl FromJSValConvertible<StringificationBehavior> for DOMString {
fn from_jsval(cx: *mut JSContext, value: JSVal, nullBehavior: StringificationBehavior) -> Result<DOMString, ()> { fn from_jsval(cx: *mut JSContext, value: JSVal, nullBehavior: StringificationBehavior) -> Result<DOMString, ()> {
if nullBehavior == StringificationBehavior::Empty && value.is_null() { if nullBehavior == StringificationBehavior::Empty && value.is_null() {
Ok("".into_string()) Ok("".to_owned())
} else { } else {
let jsstr = unsafe { JS_ValueToString(cx, value) }; let jsstr = unsafe { JS_ValueToString(cx, value) };
if jsstr.is_null() { if jsstr.is_null() {

View file

@ -6,6 +6,7 @@
//! The `ByteString` struct. //! The `ByteString` struct.
use std::borrow::ToOwned;
use std::hash::{Hash, sip}; use std::hash::{Hash, sip};
use std::str; use std::str;
use std::str::FromStr; use std::str::FromStr;
@ -154,6 +155,6 @@ impl Hash for ByteString {
impl FromStr for ByteString { impl FromStr for ByteString {
fn from_str(s: &str) -> Option<ByteString> { fn from_str(s: &str) -> Option<ByteString> {
Some(ByteString::new(s.into_string().into_bytes())) Some(ByteString::new(s.to_owned().into_bytes()))
} }
} }

View file

@ -11,6 +11,7 @@ use dom::bindings::codegen::Bindings::BlobBinding;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
use std::cmp::{min, max}; use std::cmp::{min, max};
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
@ -43,7 +44,7 @@ impl Blob {
reflector_: Reflector::new(), reflector_: Reflector::new(),
type_: type_, type_: type_,
bytes: bytes, bytes: bytes,
typeString: typeString.into_string(), typeString: typeString.to_owned(),
global: GlobalField::from_rooted(&global) global: GlobalField::from_rooted(&global)
//isClosed_: false //isClosed_: false
} }
@ -109,12 +110,12 @@ impl<'a> BlobMethods for JSRef<'a, Blob> {
} }
}; };
let relativeContentType = match contentType { let relativeContentType = match contentType {
None => "".into_string(), None => "".to_owned(),
Some(str) => { Some(str) => {
if is_ascii_printable(&str) { if is_ascii_printable(&str) {
str.as_slice().to_ascii_lower().into_string() str.as_slice().to_ascii_lower().to_owned()
} else { } else {
"".into_string() "".to_owned()
} }
} }
}; };

View file

@ -16,6 +16,7 @@ use dom::node::{Node, NodeHelpers, NodeTypeId};
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
use std::cell::Ref; use std::cell::Ref;
#[dom_struct] #[dom_struct]
@ -80,7 +81,7 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> {
} }
fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> { fn SubstringData(self, offset: u32, count: u32) -> Fallible<DOMString> {
Ok(self.data.borrow().as_slice().slice(offset as uint, count as uint).into_string()) Ok(self.data.borrow().as_slice().slice(offset as uint, count as uint).to_owned())
} }
fn AppendData(self, arg: DOMString) -> ErrorResult { fn AppendData(self, arg: DOMString) -> ErrorResult {
@ -93,7 +94,7 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> {
} }
fn DeleteData(self, offset: u32, count: u32) -> ErrorResult { fn DeleteData(self, offset: u32, count: u32) -> ErrorResult {
self.ReplaceData(offset, count, "".into_string()) self.ReplaceData(offset, count, "".to_owned())
} }
fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { fn ReplaceData(self, offset: u32, count: u32, arg: DOMString) -> ErrorResult {
@ -106,7 +107,7 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> {
} else { } else {
count count
}; };
let mut data = self.data.borrow().as_slice().slice(0, offset as uint).into_string(); let mut data = self.data.borrow().as_slice().slice(0, offset as uint).to_owned();
data.push_str(arg.as_slice()); data.push_str(arg.as_slice());
data.push_str(self.data.borrow().as_slice().slice((offset + count) as uint, length as uint)); data.push_str(self.data.borrow().as_slice().slice((offset + count) as uint, length as uint));
*self.data.borrow_mut() = data; *self.data.borrow_mut() = data;

View file

@ -79,16 +79,18 @@ use servo_util::str::DOMString;
use string_cache::QualName; use string_cache::QualName;
use std::borrow::ToOwned;
pub fn create_element(name: QualName, prefix: Option<DOMString>, pub fn create_element(name: QualName, prefix: Option<DOMString>,
document: JSRef<Document>, creator: ElementCreator) document: JSRef<Document>, creator: ElementCreator)
-> Temporary<Element> { -> Temporary<Element> {
if name.ns != ns!(HTML) { if name.ns != ns!(HTML) {
return Element::new(name.local.as_slice().into_string(), name.ns, prefix, document); return Element::new(name.local.as_slice().to_owned(), name.ns, prefix, document);
} }
macro_rules! make( macro_rules! make(
($ctor:ident $(, $arg:expr)*) => ({ ($ctor:ident $(, $arg:expr)*) => ({
let obj = $ctor::new(name.local.as_slice().into_string(), prefix, document $(, $arg)*); let obj = $ctor::new(name.local.as_slice().to_owned(), prefix, document $(, $arg)*);
ElementCast::from_temporary(obj) ElementCast::from_temporary(obj)
}) })
) )

View file

@ -21,6 +21,7 @@ use style::{is_supported_property, longhands_from_shorthand, parse_style_attribu
use style::PropertyDeclaration; use style::PropertyDeclaration;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct CSSStyleDeclaration { pub struct CSSStyleDeclaration {
@ -39,10 +40,10 @@ macro_rules! css_properties(
( $([$getter:ident, $setter:ident, $cssprop:expr]),* ) => ( ( $([$getter:ident, $setter:ident, $cssprop:expr]),* ) => (
$( $(
fn $getter(self) -> DOMString { fn $getter(self) -> DOMString {
self.GetPropertyValue($cssprop.into_string()) self.GetPropertyValue($cssprop.to_owned())
} }
fn $setter(self, value: DOMString) { fn $setter(self, value: DOMString) {
self.SetPropertyValue($cssprop.into_string(), value).unwrap(); self.SetPropertyValue($cssprop.to_owned(), value).unwrap();
} }
)* )*
); );
@ -123,7 +124,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
} }
}); });
result.unwrap_or("".into_string()) result.unwrap_or("".to_owned())
} }
// http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue
@ -145,7 +146,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
// Step 2.2.2 & 2.2.3 // Step 2.2.2 & 2.2.3
match declaration { match declaration {
Some(declaration) => list.push(declaration), Some(declaration) => list.push(declaration),
None => return "".into_string(), None => return "".to_owned(),
} }
} }
@ -157,7 +158,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
if let Some(ref declaration) = self.get_declaration(&property) { if let Some(ref declaration) = self.get_declaration(&property) {
serialize_value(declaration) serialize_value(declaration)
} else { } else {
"".into_string() "".to_owned()
} }
} }
@ -174,15 +175,15 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
.map(|longhand| self.GetPropertyPriority(longhand.clone())) .map(|longhand| self.GetPropertyPriority(longhand.clone()))
.all(|priority| priority.as_slice() == "important") { .all(|priority| priority.as_slice() == "important") {
return "important".into_string(); return "important".to_owned();
} }
// Step 3 // Step 3
} else if self.get_important_declaration(&property).is_some() { } else if self.get_important_declaration(&property).is_some() {
return "important".into_string(); return "important".to_owned();
} }
// Step 4 // Step 4
"".into_string() "".to_owned()
} }
// http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty
@ -289,7 +290,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
// http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyvalue // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyvalue
fn SetPropertyValue(self, property: DOMString, value: DOMString) -> ErrorResult { fn SetPropertyValue(self, property: DOMString, value: DOMString) -> ErrorResult {
self.SetProperty(property, value, "".into_string()) self.SetProperty(property, value, "".to_owned())
} }
// http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty
@ -328,12 +329,12 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
// http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
fn CssFloat(self) -> DOMString { fn CssFloat(self) -> DOMString {
self.GetPropertyValue("float".into_string()) self.GetPropertyValue("float".to_owned())
} }
// http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
fn SetCssFloat(self, value: DOMString) -> ErrorResult { fn SetCssFloat(self, value: DOMString) -> ErrorResult {
self.SetPropertyValue("float".into_string(), value) self.SetPropertyValue("float".to_owned(), value)
} }
fn IndexedGetter(self, index: u32, found: &mut bool) -> DOMString { fn IndexedGetter(self, index: u32, found: &mut bool) -> DOMString {

View file

@ -63,6 +63,7 @@ use layout_interface::{LayoutChan, Msg};
use string_cache::{Atom, QualName}; use string_cache::{Atom, QualName};
use url::Url; use url::Url;
use std::borrow::ToOwned;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::{Vacant, Occupied}; use std::collections::hash_map::{Vacant, Occupied};
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
@ -339,7 +340,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
self.ready_state.set(state); self.ready_state.set(state);
let window = self.window.root(); let window = self.window.root();
let event = Event::new(GlobalRef::Window(window.r()), "readystatechange".into_string(), let event = Event::new(GlobalRef::Window(window.r()), "readystatechange".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
@ -425,9 +426,9 @@ impl Document {
Some(string) => string.clone(), Some(string) => string.clone(),
None => match is_html_document { None => match is_html_document {
// http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument // http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
IsHTMLDocument::HTMLDocument => "text/html".into_string(), IsHTMLDocument::HTMLDocument => "text/html".to_owned(),
// http://dom.spec.whatwg.org/#concept-document-content-type // http://dom.spec.whatwg.org/#concept-document-content-type
IsHTMLDocument::NonHTMLDocument => "application/xml".into_string() IsHTMLDocument::NonHTMLDocument => "application/xml".to_owned()
} }
}, },
last_modified: DOMRefCell::new(None), last_modified: DOMRefCell::new(None),
@ -435,7 +436,7 @@ impl Document {
// http://dom.spec.whatwg.org/#concept-document-quirks // http://dom.spec.whatwg.org/#concept-document-quirks
quirks_mode: Cell::new(NoQuirks), quirks_mode: Cell::new(NoQuirks),
// http://dom.spec.whatwg.org/#concept-document-encoding // http://dom.spec.whatwg.org/#concept-document-encoding
encoding_name: DOMRefCell::new("UTF-8".into_string()), encoding_name: DOMRefCell::new("UTF-8".to_owned()),
is_html_document: is_html_document == IsHTMLDocument::HTMLDocument, is_html_document: is_html_document == IsHTMLDocument::HTMLDocument,
images: Default::default(), images: Default::default(),
embeds: Default::default(), embeds: Default::default(),
@ -520,8 +521,8 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
// http://dom.spec.whatwg.org/#dom-document-compatmode // http://dom.spec.whatwg.org/#dom-document-compatmode
fn CompatMode(self) -> DOMString { fn CompatMode(self) -> DOMString {
match self.quirks_mode.get() { match self.quirks_mode.get() {
LimitedQuirks | NoQuirks => "CSS1Compat".into_string(), LimitedQuirks | NoQuirks => "CSS1Compat".to_owned(),
Quirks => "BackCompat".into_string() Quirks => "BackCompat".to_owned()
} }
} }
@ -639,7 +640,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
} }
let name = QualName::new(ns, Atom::from_slice(local_name_from_qname)); let name = QualName::new(ns, Atom::from_slice(local_name_from_qname));
Ok(Element::create(name, prefix_from_qname.map(|s| s.into_string()), self, Ok(Element::create(name, prefix_from_qname.map(|s| s.to_owned()), self,
ElementCreator::ScriptCreated)) ElementCreator::ScriptCreated))
} }
@ -654,7 +655,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let name = Atom::from_slice(local_name.as_slice()); let name = Atom::from_slice(local_name.as_slice());
// repetition used because string_cache::atom::Atom is non-copyable // repetition used because string_cache::atom::Atom is non-copyable
let l_name = Atom::from_slice(local_name.as_slice()); let l_name = Atom::from_slice(local_name.as_slice());
let value = AttrValue::String("".into_string()); let value = AttrValue::String("".to_owned());
Ok(Attr::new(window.r(), name, value, l_name, ns!(""), None, None)) Ok(Attr::new(window.r(), name, value, l_name, ns!(""), None, None))
} }
@ -802,7 +803,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
} }
}, },
None => { None => {
let new_title = HTMLTitleElement::new("title".into_string(), None, self).root(); let new_title = HTMLTitleElement::new("title".to_owned(), None, self).root();
let new_title: JSRef<Node> = NodeCast::from_ref(new_title.r()); let new_title: JSRef<Node> = NodeCast::from_ref(new_title.r());
if !title.is_empty() { if !title.is_empty() {

View file

@ -11,6 +11,8 @@ use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId}; use dom::node::{Node, NodeHelpers, NodeTypeId};
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
/// The `DOCTYPE` tag. /// The `DOCTYPE` tag.
#[dom_struct] #[dom_struct]
pub struct DocumentType { pub struct DocumentType {
@ -35,8 +37,8 @@ impl DocumentType {
DocumentType { DocumentType {
node: Node::new_inherited(NodeTypeId::DocumentType, document), node: Node::new_inherited(NodeTypeId::DocumentType, document),
name: name, name: name,
public_id: public_id.unwrap_or("".into_string()), public_id: public_id.unwrap_or("".to_owned()),
system_id: system_id.unwrap_or("".into_string()) system_id: system_id.unwrap_or("".to_owned())
} }
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]

View file

@ -11,6 +11,8 @@ use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
#[repr(uint)] #[repr(uint)]
#[deriving(Copy, Show)] #[deriving(Copy, Show)]
#[jstraceable] #[jstraceable]
@ -125,6 +127,6 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> {
DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed." DOMErrorName::EncodingError => "The encoding operation (either encoded or decoding) failed."
}; };
message.into_string() message.to_owned()
} }
} }

View file

@ -25,6 +25,8 @@ use dom::node::Node;
use dom::text::Text; use dom::text::Text;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct DOMImplementation { pub struct DOMImplementation {
reflector_: Reflector, reflector_: Reflector,
@ -123,18 +125,18 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
{ {
// Step 3. // Step 3.
let doc_type = DocumentType::new("html".into_string(), None, None, doc.r()).root(); let doc_type = DocumentType::new("html".to_owned(), None, None, doc.r()).root();
assert!(doc_node.AppendChild(NodeCast::from_ref(doc_type.r())).is_ok()); assert!(doc_node.AppendChild(NodeCast::from_ref(doc_type.r())).is_ok());
} }
{ {
// Step 4. // Step 4.
let doc_html: Root<Node> = NodeCast::from_temporary(HTMLHtmlElement::new("html".into_string(), None, doc.r())).root(); let doc_html: Root<Node> = NodeCast::from_temporary(HTMLHtmlElement::new("html".to_owned(), None, doc.r())).root();
assert!(doc_node.AppendChild(doc_html.r()).is_ok()); assert!(doc_node.AppendChild(doc_html.r()).is_ok());
{ {
// Step 5. // Step 5.
let doc_head: Root<Node> = NodeCast::from_temporary(HTMLHeadElement::new("head".into_string(), None, doc.r())).root(); let doc_head: Root<Node> = NodeCast::from_temporary(HTMLHeadElement::new("head".to_owned(), None, doc.r())).root();
assert!(doc_html.r().AppendChild(doc_head.r()).is_ok()); assert!(doc_html.r().AppendChild(doc_head.r()).is_ok());
// Step 6. // Step 6.
@ -142,7 +144,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
None => (), None => (),
Some(title_str) => { Some(title_str) => {
// Step 6.1. // Step 6.1.
let doc_title: Root<Node> = NodeCast::from_temporary(HTMLTitleElement::new("title".into_string(), None, doc.r())).root(); let doc_title: Root<Node> = NodeCast::from_temporary(HTMLTitleElement::new("title".to_owned(), None, doc.r())).root();
assert!(doc_head.r().AppendChild(doc_title.r()).is_ok()); assert!(doc_head.r().AppendChild(doc_title.r()).is_ok());
// Step 6.2. // Step 6.2.
@ -153,7 +155,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
} }
// Step 7. // Step 7.
let doc_body: Root<HTMLBodyElement> = HTMLBodyElement::new("body".into_string(), None, doc.r()).root(); let doc_body: Root<HTMLBodyElement> = HTMLBodyElement::new("body".to_owned(), None, doc.r()).root();
assert!(doc_html.r().AppendChild(NodeCast::from_ref(doc_body.r())).is_ok()); assert!(doc_html.r().AppendChild(NodeCast::from_ref(doc_body.r())).is_ok());
} }

View file

@ -17,6 +17,8 @@ use dom::window::Window;
use parse::html::{HTMLInput, parse_html}; use parse::html::{HTMLInput, parse_html};
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct DOMParser { pub struct DOMParser {
reflector_: Reflector, reflector_: Reflector,
@ -49,7 +51,7 @@ impl<'a> DOMParserMethods for JSRef<'a, DOMParser> {
-> Fallible<Temporary<Document>> { -> Fallible<Temporary<Document>> {
let window = self.window.root(); let window = self.window.root();
let url = window.r().get_url(); let url = window.r().get_url();
let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].into_string(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].to_owned();
match ty { match ty {
Text_html => { Text_html => {
let document = Document::new(window.r(), Some(url.clone()), let document = Document::new(window.r(), Some(url.clone()),

View file

@ -16,6 +16,8 @@ use dom::node::window_from_node;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS}; use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use string_cache::Atom; use string_cache::Atom;
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct DOMTokenList { pub struct DOMTokenList {
reflector_: Reflector, reflector_: Reflector,
@ -72,7 +74,7 @@ impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-item // http://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> { fn Item(self, index: u32) -> Option<DOMString> {
self.attribute().root().and_then(|attr| attr.r().value().tokens().and_then(|tokens| { self.attribute().root().and_then(|attr| attr.r().value().tokens().and_then(|tokens| {
tokens.get(index as uint).map(|token| token.as_slice().into_string()) tokens.get(index as uint).map(|token| token.as_slice().to_owned())
})) }))
} }

View file

@ -59,6 +59,7 @@ use html5ever::tree_builder::{NoQuirks, LimitedQuirks, Quirks};
use cssparser::RGBA; use cssparser::RGBA;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use std::default::Default; use std::default::Default;
use std::mem; use std::mem;
@ -761,7 +762,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn get_url_attribute(self, name: &Atom) -> DOMString { fn get_url_attribute(self, name: &Atom) -> DOMString {
assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice()); assert!(name.as_slice() == name.as_slice().to_ascii_lower().as_slice());
if !self.has_attribute(name) { if !self.has_attribute(name) {
return "".into_string(); return "".to_owned();
} }
let url = self.get_string_attribute(name); let url = self.get_string_attribute(name);
let doc = document_from_node(self).root(); let doc = document_from_node(self).root();
@ -770,7 +771,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
// XXXManishearth this doesn't handle `javascript:` urls properly // XXXManishearth this doesn't handle `javascript:` urls properly
match UrlParser::new().base_url(base).parse(url.as_slice()) { match UrlParser::new().base_url(base).parse(url.as_slice()) {
Ok(parsed) => parsed.serialize(), Ok(parsed) => parsed.serialize(),
Err(_) => "".into_string() Err(_) => "".to_owned()
} }
} }
fn set_url_attribute(self, name: &Atom, value: DOMString) { fn set_url_attribute(self, name: &Atom, value: DOMString) {
@ -780,7 +781,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn get_string_attribute(self, name: &Atom) -> DOMString { fn get_string_attribute(self, name: &Atom) -> DOMString {
match self.get_attribute(ns!(""), name) { match self.get_attribute(ns!(""), name) {
Some(x) => x.root().r().Value(), Some(x) => x.root().r().Value(),
None => "".into_string() None => "".to_owned()
} }
} }
fn set_string_attribute(self, name: &Atom, value: DOMString) { fn set_string_attribute(self, name: &Atom, value: DOMString) {
@ -835,12 +836,12 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn GetNamespaceURI(self) -> Option<DOMString> { fn GetNamespaceURI(self) -> Option<DOMString> {
match self.namespace { match self.namespace {
ns!("") => None, ns!("") => None,
Namespace(ref ns) => Some(ns.as_slice().into_string()) Namespace(ref ns) => Some(ns.as_slice().to_owned())
} }
} }
fn LocalName(self) -> DOMString { fn LocalName(self) -> DOMString {
self.local_name.as_slice().into_string() self.local_name.as_slice().to_owned()
} }
// http://dom.spec.whatwg.org/#dom-element-prefix // http://dom.spec.whatwg.org/#dom-element-prefix
@ -996,7 +997,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
// Step 9. // Step 9.
let value = self.parse_attribute(&namespace, &local_name, value); let value = self.parse_attribute(&namespace, &local_name, value);
self.do_set_attribute(local_name.clone(), value, name, self.do_set_attribute(local_name.clone(), value, name,
namespace.clone(), prefix.map(|s| s.into_string()), namespace.clone(), prefix.map(|s| s.to_owned()),
|attr| { |attr| {
*attr.local_name() == local_name && *attr.local_name() == local_name &&
*attr.namespace() == namespace *attr.namespace() == namespace

View file

@ -17,6 +17,7 @@ use dom::event::{Event, EventTypeId, EventBubbles, EventCancelable};
use servo_util::str::DOMString; use servo_util::str::DOMString;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DOMRefCell;
use std::borrow::ToOwned;
use std::cell::{Cell}; use std::cell::{Cell};
use js::jsval::{JSVal, NullValue}; use js::jsval::{JSVal, NullValue};
@ -40,8 +41,8 @@ impl ErrorEvent {
fn new_inherited(type_id: EventTypeId) -> ErrorEvent { fn new_inherited(type_id: EventTypeId) -> ErrorEvent {
ErrorEvent { ErrorEvent {
event: Event::new_inherited(type_id), event: Event::new_inherited(type_id),
message: DOMRefCell::new("".into_string()), message: DOMRefCell::new("".to_owned()),
filename: DOMRefCell::new("".into_string()), filename: DOMRefCell::new("".to_owned()),
lineno: Cell::new(0), lineno: Cell::new(0),
colno: Cell::new(0), colno: Cell::new(0),
error: MutHeap::new(NullValue()) error: MutHeap::new(NullValue())
@ -80,11 +81,11 @@ impl ErrorEvent {
init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Temporary<ErrorEvent>>{ init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Temporary<ErrorEvent>>{
let msg = match init.message.as_ref() { let msg = match init.message.as_ref() {
Some(message) => message.clone(), Some(message) => message.clone(),
None => "".into_string(), None => "".to_owned(),
}; };
let file_name = match init.filename.as_ref() { let file_name = match init.filename.as_ref() {
None => "".into_string(), None => "".to_owned(),
Some(filename) => filename.clone(), Some(filename) => filename.clone(),
}; };

View file

@ -11,6 +11,8 @@ use dom::bindings::js::{MutNullableJS, JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
use std::default::Default; use std::default::Default;
@ -77,7 +79,7 @@ impl Event {
current_target: Default::default(), current_target: Default::default(),
target: Default::default(), target: Default::default(),
phase: Cell::new(EventPhase::None), phase: Cell::new(EventPhase::None),
type_: DOMRefCell::new("".into_string()), type_: DOMRefCell::new("".to_owned()),
canceled: Cell::new(false), canceled: Cell::new(false),
cancelable: Cell::new(false), cancelable: Cell::new(false),
bubbles: Cell::new(false), bubbles: Cell::new(false),

View file

@ -22,6 +22,7 @@ use js::jsapi::{JSContext, JSObject};
use servo_util::fnv::FnvHasher; use servo_util::fnv::FnvHasher;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use libc::{c_char, size_t}; use libc::{c_char, size_t};
use std::borrow::ToOwned;
use std::collections::hash_map::{Occupied, Vacant}; use std::collections::hash_map::{Occupied, Vacant};
use std::ptr; use std::ptr;
use url::Url; use url::Url;
@ -231,11 +232,11 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> {
{ {
let event_listener = listener.map(|listener| let event_listener = listener.map(|listener|
EventListener::new(listener.callback())); EventListener::new(listener.callback()));
self.set_inline_event_listener(ty.into_string(), event_listener); self.set_inline_event_listener(ty.to_owned(), event_listener);
} }
fn get_event_handler_common<T: CallbackContainer>(self, ty: &str) -> Option<T> { fn get_event_handler_common<T: CallbackContainer>(self, ty: &str) -> Option<T> {
let listener = self.get_inline_event_listener(ty.into_string()); let listener = self.get_inline_event_listener(ty.to_owned());
listener.map(|listener| CallbackContainer::new(listener.parent.callback())) listener.map(|listener| CallbackContainer::new(listener.parent.callback()))
} }

View file

@ -16,6 +16,8 @@ use dom::blob::Blob;
use dom::file::File; use dom::file::File;
use dom::htmlformelement::HTMLFormElement; use dom::htmlformelement::HTMLFormElement;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::{Occupied, Vacant}; use std::collections::hash_map::{Occupied, Vacant};
@ -115,7 +117,7 @@ impl PrivateFormDataHelpers for FormData {
fn get_file_from_blob(&self, value: JSRef<Blob>, filename: Option<DOMString>) -> Temporary<File> { fn get_file_from_blob(&self, value: JSRef<Blob>, filename: Option<DOMString>) -> Temporary<File> {
let global = self.global.root(); let global = self.global.root();
let f: Option<JSRef<File>> = FileCast::to_ref(value); let f: Option<JSRef<File>> = FileCast::to_ref(value);
let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".into_string())); let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".to_owned()));
File::new(global.r(), value, name) File::new(global.r(), value, name)
} }
} }

View file

@ -19,6 +19,8 @@ use dom::virtualmethods::VirtualMethods;
use cssparser::RGBA; use cssparser::RGBA;
use servo_util::str::{mod, DOMString}; use servo_util::str::{mod, DOMString};
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
#[dom_struct] #[dom_struct]
@ -106,7 +108,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> {
}; };
evtarget.set_event_handler_uncompiled(cx, url, reflector, evtarget.set_event_handler_uncompiled(cx, url, reflector,
name.slice_from(2), name.slice_from(2),
attr.value().as_slice().into_string()); attr.value().as_slice().to_owned());
} }
match attr.local_name() { match attr.local_name() {

View file

@ -19,6 +19,7 @@ use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods; use dom::virtualmethods::VirtualMethods;
use std::ascii::OwnedAsciiExt; use std::ascii::OwnedAsciiExt;
use std::borrow::ToOwned;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use string_cache::Atom; use string_cache::Atom;
@ -66,7 +67,7 @@ impl<'a> HTMLButtonElementMethods for JSRef<'a, HTMLButtonElement> {
// https://html.spec.whatwg.org/multipage/forms.html#attr-button-type // https://html.spec.whatwg.org/multipage/forms.html#attr-button-type
match ty.as_slice() { match ty.as_slice() {
"reset" | "button" | "menu" => ty, "reset" | "button" | "menu" => ty,
_ => "submit".into_string() _ => "submit".to_owned()
} }
} }

View file

@ -30,6 +30,7 @@ use servo_util::str::DOMString;
use string_cache::Atom; use string_cache::Atom;
use std::borrow::ToOwned;
use std::default::Default; use std::default::Default;
#[dom_struct] #[dom_struct]
@ -141,7 +142,7 @@ pub trait HTMLElementCustomAttributeHelpers {
} }
fn to_snake_case(name: DOMString) -> DOMString { fn to_snake_case(name: DOMString) -> DOMString {
let mut attr_name = "data-".into_string(); let mut attr_name = "data-".to_owned();
for ch in name.as_slice().chars() { for ch in name.as_slice().chars() {
if ch.is_uppercase() { if ch.is_uppercase() {
attr_name.push('\x2d'); attr_name.push('\x2d');
@ -168,7 +169,7 @@ impl<'a> HTMLElementCustomAttributeHelpers for JSRef<'a, HTMLElement> {
let element: JSRef<Element> = ElementCast::from_ref(self); let element: JSRef<Element> = ElementCast::from_ref(self);
element.get_attribute(ns!(""), &Atom::from_slice(to_snake_case(name).as_slice())).map(|attr| { element.get_attribute(ns!(""), &Atom::from_slice(to_snake_case(name).as_slice())).map(|attr| {
let attr = attr.root(); let attr = attr.root();
attr.r().value().as_slice().into_string() attr.r().value().as_slice().to_owned()
}) })
} }
@ -199,7 +200,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLElement> {
let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self); let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self);
evtarget.set_event_handler_uncompiled(cx, url, reflector, evtarget.set_event_handler_uncompiled(cx, url, reflector,
name.slice_from(2), name.slice_from(2),
attr.value().as_slice().into_string()); attr.value().as_slice().to_owned());
} }
} }
} }

View file

@ -30,6 +30,7 @@ use url::UrlParser;
use url::form_urlencoded::serialize; use url::form_urlencoded::serialize;
use string_cache::Atom; use string_cache::Atom;
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
#[dom_struct] #[dom_struct]
@ -159,7 +160,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
// TODO: Handle browsing contexts // TODO: Handle browsing contexts
// TODO: Handle validation // TODO: Handle validation
let event = Event::new(GlobalRef::Window(win.r()), let event = Event::new(GlobalRef::Window(win.r()),
"submit".into_string(), "submit".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
event.r().set_trusted(true); event.r().set_trusted(true);
@ -187,7 +188,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
let parsed_data = match enctype { let parsed_data = match enctype {
FormEncType::UrlEncoded => serialize(form_data.iter().map(|d| (d.name.as_slice(), d.value.as_slice()))), FormEncType::UrlEncoded => serialize(form_data.iter().map(|d| (d.name.as_slice(), d.value.as_slice()))),
_ => "".into_string() // TODO: Add serializers for the other encoding types _ => "".to_owned() // TODO: Add serializers for the other encoding types
}; };
let mut load_data = LoadData::new(action_components); let mut load_data = LoadData::new(action_components);
@ -214,7 +215,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
fn clean_crlf(s: &str) -> DOMString { fn clean_crlf(s: &str) -> DOMString {
// https://html.spec.whatwg.org/multipage/forms.html#constructing-the-form-data-set // https://html.spec.whatwg.org/multipage/forms.html#constructing-the-form-data-set
// Step 4 // Step 4
let mut buf = "".into_string(); let mut buf = "".to_owned();
let mut prev = ' '; let mut prev = ' ';
for ch in s.chars() { for ch in s.chars() {
match ch { match ch {
@ -284,7 +285,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
"image" => None, // Unimplemented "image" => None, // Unimplemented
"radio" | "checkbox" => { "radio" | "checkbox" => {
if value.is_empty() { if value.is_empty() {
value = "on".into_string(); value = "on".to_owned();
} }
Some(FormDatum { Some(FormDatum {
ty: ty, ty: ty,
@ -346,7 +347,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
let win = window_from_node(self).root(); let win = window_from_node(self).root();
let event = Event::new(GlobalRef::Window(win.r()), let event = Event::new(GlobalRef::Window(win.r()),
"reset".into_string(), "reset".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
@ -513,7 +514,7 @@ pub trait FormControl<'a> : Copy {
if self.to_element().has_attribute(attr) { if self.to_element().has_attribute(attr) {
input(self) input(self)
} else { } else {
self.form_owner().map_or("".into_string(), |t| owner(t.root().r())) self.form_owner().map_or("".to_owned(), |t| owner(t.root().r()))
} }
} }
fn to_element(self) -> JSRef<'a, Element>; fn to_element(self) -> JSRef<'a, Element>;

View file

@ -24,6 +24,8 @@ use string_cache::Atom;
use url::{Url, UrlParser}; use url::{Url, UrlParser};
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct HTMLImageElement { pub struct HTMLImageElement {
htmlelement: HTMLElement, htmlelement: HTMLElement,
@ -189,7 +191,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
&atom!("src") => { &atom!("src") => {
let window = window_from_node(*self).root(); let window = window_from_node(*self).root();
let url = window.r().get_url(); let url = window.r().get_url();
self.update_image(Some((attr.value().as_slice().into_string(), &url))); self.update_image(Some((attr.value().as_slice().to_owned(), &url)));
}, },
_ => () _ => ()
} }

View file

@ -38,6 +38,7 @@ use servo_util::str::DOMString;
use string_cache::Atom; use string_cache::Atom;
use std::ascii::OwnedAsciiExt; use std::ascii::OwnedAsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
use std::default::Default; use std::default::Default;
@ -116,7 +117,7 @@ impl HTMLInputElement {
checked_changed: Cell::new(false), checked_changed: Cell::new(false),
value_changed: Cell::new(false), value_changed: Cell::new(false),
size: Cell::new(DEFAULT_INPUT_SIZE), size: Cell::new(DEFAULT_INPUT_SIZE),
textinput: DOMRefCell::new(TextInput::new(Single, "".into_string())), textinput: DOMRefCell::new(TextInput::new(Single, "".to_owned())),
activation_state: DOMRefCell::new(InputActivationState::new()) activation_state: DOMRefCell::new(InputActivationState::new())
} }
} }
@ -149,15 +150,15 @@ impl LayoutHTMLInputElementHelpers for JS<HTMLInputElement> {
unsafe fn get_raw_attr_value(input: JS<HTMLInputElement>) -> Option<String> { unsafe fn get_raw_attr_value(input: JS<HTMLInputElement>) -> Option<String> {
let elem: JS<Element> = input.transmute_copy(); let elem: JS<Element> = input.transmute_copy();
(*elem.unsafe_get()).get_attr_val_for_layout(&ns!(""), &atom!("value")) (*elem.unsafe_get()).get_attr_val_for_layout(&ns!(""), &atom!("value"))
.map(|s| s.into_string()) .map(|s| s.to_owned())
} }
match (*self.unsafe_get()).input_type.get() { match (*self.unsafe_get()).input_type.get() {
InputType::InputCheckbox | InputType::InputRadio => "".into_string(), InputType::InputCheckbox | InputType::InputRadio => "".to_owned(),
InputType::InputFile | InputType::InputImage => "".into_string(), InputType::InputFile | InputType::InputImage => "".to_owned(),
InputType::InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".into_string()), InputType::InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".to_owned()),
InputType::InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.into_string()), InputType::InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.to_owned()),
InputType::InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.into_string()), InputType::InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.to_owned()),
InputType::InputPassword => { InputType::InputPassword => {
let raw = get_raw_textinput_value(self); let raw = get_raw_textinput_value(self);
String::from_char(raw.char_len(), '●') String::from_char(raw.char_len(), '●')
@ -313,7 +314,7 @@ fn broadcast_radio_checked(broadcaster: JSRef<HTMLInputElement>, group: Option<&
// There is no DOM tree manipulation here, so this is safe // There is no DOM tree manipulation here, so this is safe
let mut iter = unsafe { let mut iter = unsafe {
doc_node.query_selector_iter("input[type=radio]".into_string()).unwrap() doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap()
.filter_map(|t| HTMLInputElementCast::to_ref(t)) .filter_map(|t| HTMLInputElementCast::to_ref(t))
.filter(|&r| in_same_group(r, owner.r(), group) && broadcaster != r) .filter(|&r| in_same_group(r, owner.r(), group) && broadcaster != r)
}; };
@ -439,7 +440,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> {
} }
&atom!("value") => { &atom!("value") => {
if !self.value_changed.get() { if !self.value_changed.get() {
self.textinput.borrow_mut().set_content(attr.value().as_slice().into_string()); self.textinput.borrow_mut().set_content(attr.value().as_slice().to_owned());
self.force_relayout(); self.force_relayout();
} }
} }
@ -488,7 +489,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> {
} }
&atom!("value") => { &atom!("value") => {
if !self.value_changed.get() { if !self.value_changed.get() {
self.textinput.borrow_mut().set_content("".into_string()); self.textinput.borrow_mut().set_content("".to_owned());
self.force_relayout(); self.force_relayout();
} }
} }
@ -639,7 +640,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
// Safe since we only manipulate the DOM tree after finding an element // Safe since we only manipulate the DOM tree after finding an element
let checked_member = unsafe { let checked_member = unsafe {
doc_node.query_selector_iter("input[type=radio]".into_string()).unwrap() doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap()
.filter_map(|t| HTMLInputElementCast::to_ref(t)) .filter_map(|t| HTMLInputElementCast::to_ref(t))
.filter(|&r| in_same_group(r, owner.r(), .filter(|&r| in_same_group(r, owner.r(),
group.as_ref().map(|gr| gr.as_slice()))) group.as_ref().map(|gr| gr.as_slice())))
@ -739,7 +740,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
if self.mutable() { if self.mutable() {
let win = window_from_node(*self).root(); let win = window_from_node(*self).root();
let event = Event::new(GlobalRef::Window(win.r()), let event = Event::new(GlobalRef::Window(win.r()),
"input".into_string(), "input".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
event.r().set_trusted(true); event.r().set_trusted(true);
@ -747,7 +748,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
target.DispatchEvent(event.r()).ok(); target.DispatchEvent(event.r()).ok();
let event = Event::new(GlobalRef::Window(win.r()), let event = Event::new(GlobalRef::Window(win.r()),
"change".into_string(), "change".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
event.r().set_trusted(true); event.r().set_trusted(true);
@ -771,7 +772,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
// This is safe because we are stopping after finding the first element // This is safe because we are stopping after finding the first element
// and only then performing actions which may modify the DOM tree // and only then performing actions which may modify the DOM tree
unsafe { unsafe {
node.query_selector_iter("input[type=submit]".into_string()).unwrap() node.query_selector_iter("input[type=submit]".to_owned()).unwrap()
.filter_map(|t| HTMLInputElementCast::to_ref(t)) .filter_map(|t| HTMLInputElementCast::to_ref(t))
.find(|r| r.form_owner() == owner) .find(|r| r.form_owner() == owner)
.map(|s| s.synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey)); .map(|s| s.synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey));

View file

@ -21,6 +21,7 @@ use layout_interface::{LayoutChan, Msg};
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS}; use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::default::Default; use std::default::Default;
use url::UrlParser; use url::UrlParser;
use string_cache::Atom; use string_cache::Atom;
@ -54,7 +55,7 @@ impl HTMLLinkElement {
fn get_attr(element: JSRef<Element>, name: &Atom) -> Option<String> { fn get_attr(element: JSRef<Element>, name: &Atom) -> Option<String> {
let elem = element.get_attribute(ns!(""), name).root(); let elem = element.get_attribute(ns!(""), name).root();
elem.map(|e| e.r().value().as_slice().into_string()) elem.map(|e| e.r().value().as_slice().to_owned())
} }
fn is_stylesheet(value: &Option<String>) -> bool { fn is_stylesheet(value: &Option<String>) -> bool {

View file

@ -31,6 +31,7 @@ use encoding::all::UTF_8;
use encoding::types::{Encoding, DecoderTrap}; use encoding::types::{Encoding, DecoderTrap};
use servo_net::resource_task::load_whole_resource; use servo_net::resource_task::load_whole_resource;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec}; use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec};
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
use string_cache::Atom; use string_cache::Atom;
use url::UrlParser; use url::UrlParser;
@ -239,7 +240,7 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let window = window.r(); let window = window.r();
let event = Event::new(GlobalRef::Window(window), let event = Event::new(GlobalRef::Window(window),
"load".into_string(), "load".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
event.r().set_trusted(true); event.r().set_trusted(true);

View file

@ -23,6 +23,8 @@ use dom::virtualmethods::VirtualMethods;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use string_cache::Atom; use string_cache::Atom;
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct HTMLSelectElement { pub struct HTMLSelectElement {
htmlelement: HTMLElement htmlelement: HTMLElement
@ -68,9 +70,9 @@ impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> {
fn Type(self) -> DOMString { fn Type(self) -> DOMString {
let elem: JSRef<Element> = ElementCast::from_ref(self); let elem: JSRef<Element> = ElementCast::from_ref(self);
if elem.has_attribute(&atom!("multiple")) { if elem.has_attribute(&atom!("multiple")) {
"select-multiple".into_string() "select-multiple".to_owned()
} else { } else {
"select-one".into_string() "select-one".to_owned()
} }
} }
} }

View file

@ -15,6 +15,8 @@ use dom::node::{Node, NodeHelpers, NodeTypeId, NodeIterator};
use dom::processinginstruction::ProcessingInstruction; use dom::processinginstruction::ProcessingInstruction;
use dom::text::Text; use dom::text::Text;
use std::borrow::ToOwned;
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn serialize(iterator: &mut NodeIterator) -> String { pub fn serialize(iterator: &mut NodeIterator) -> String {
let mut html = String::new(); let mut html = String::new();
@ -126,7 +128,7 @@ fn serialize_elem(elem: JSRef<Element>, open_elements: &mut Vec<String>, html: &
} }
if !(elem.is_void()) { if !(elem.is_void()) {
open_elements.push(elem.local_name().as_slice().into_string()); open_elements.push(elem.local_name().as_slice().to_owned());
} }
} }

View file

@ -29,6 +29,7 @@ use dom::virtualmethods::VirtualMethods;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use string_cache::Atom; use string_cache::Atom;
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
#[dom_struct] #[dom_struct]
@ -83,7 +84,7 @@ impl HTMLTextAreaElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTextAreaElement {
HTMLTextAreaElement { HTMLTextAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTextAreaElement, localName, prefix, document), htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTextAreaElement, localName, prefix, document),
textinput: DOMRefCell::new(TextInput::new(Lines::Multiple, "".into_string())), textinput: DOMRefCell::new(TextInput::new(Lines::Multiple, "".to_owned())),
cols: Cell::new(DEFAULT_COLS), cols: Cell::new(DEFAULT_COLS),
rows: Cell::new(DEFAULT_ROWS), rows: Cell::new(DEFAULT_ROWS),
value_changed: Cell::new(false), value_changed: Cell::new(false),
@ -151,7 +152,7 @@ impl<'a> HTMLTextAreaElementMethods for JSRef<'a, HTMLTextAreaElement> {
// https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-type
fn Type(self) -> DOMString { fn Type(self) -> DOMString {
"textarea".into_string() "textarea".to_owned()
} }
// https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-defaultvalue // https://html.spec.whatwg.org/multipage/forms.html#dom-textarea-defaultvalue

View file

@ -15,6 +15,8 @@ use dom::uievent::UIEvent;
use dom::window::Window; use dom::window::Window;
use servo_msg::constellation_msg; use servo_msg::constellation_msg;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
use std::cell::{RefCell, Cell}; use std::cell::{RefCell, Cell};
#[jstraceable] #[jstraceable]
@ -44,8 +46,8 @@ impl KeyboardEvent {
fn new_inherited() -> KeyboardEvent { fn new_inherited() -> KeyboardEvent {
KeyboardEvent { KeyboardEvent {
uievent: UIEvent::new_inherited(EventTypeId::KeyboardEvent), uievent: UIEvent::new_inherited(EventTypeId::KeyboardEvent),
key: RefCell::new("".into_string()), key: RefCell::new("".to_owned()),
code: RefCell::new("".into_string()), code: RefCell::new("".to_owned()),
location: Cell::new(0), location: Cell::new(0),
ctrl: Cell::new(false), ctrl: Cell::new(false),
alt: Cell::new(false), alt: Cell::new(false),
@ -83,7 +85,7 @@ impl KeyboardEvent {
key_code: u32) -> Temporary<KeyboardEvent> { key_code: u32) -> Temporary<KeyboardEvent> {
let ev = KeyboardEvent::new_uninitialized(window).root(); let ev = KeyboardEvent::new_uninitialized(window).root();
ev.r().InitKeyboardEvent(type_, canBubble, cancelable, view, key, location, ev.r().InitKeyboardEvent(type_, canBubble, cancelable, view, key, location,
"".into_string(), repeat, "".into_string()); "".to_owned(), repeat, "".to_owned());
*ev.r().code.borrow_mut() = code; *ev.r().code.borrow_mut() = code;
ev.r().ctrl.set(ctrlKey); ev.r().ctrl.set(ctrlKey);
ev.r().alt.set(altKey); ev.r().alt.set(altKey);

View file

@ -106,13 +106,14 @@ macro_rules! make_enumerated_getter(
use dom::bindings::codegen::InheritTypes::ElementCast; use dom::bindings::codegen::InheritTypes::ElementCast;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned;
let element: JSRef<Element> = ElementCast::from_ref(self); let element: JSRef<Element> = ElementCast::from_ref(self);
let val = element.get_string_attribute(&Atom::from_slice($htmlname)) let val = element.get_string_attribute(&Atom::from_slice($htmlname))
.into_ascii_lower(); .into_ascii_lower();
// https://html.spec.whatwg.org/multipage/forms.html#attr-fs-method // https://html.spec.whatwg.org/multipage/forms.html#attr-fs-method
match val.as_slice() { match val.as_slice() {
$($choices)|+ => val, $($choices)|+ => val,
_ => $default.into_string() _ => $default.to_owned()
} }
} }
); );

View file

@ -18,6 +18,8 @@ use servo_util::str::DOMString;
use js::jsapi::JSContext; use js::jsapi::JSContext;
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct MessageEvent { pub struct MessageEvent {
event: Event, event: Event,
@ -44,7 +46,7 @@ impl MessageEvent {
} }
pub fn new_uninitialized(global: GlobalRef) -> Temporary<MessageEvent> { pub fn new_uninitialized(global: GlobalRef) -> Temporary<MessageEvent> {
MessageEvent::new_initialized(global, UndefinedValue(), "".into_string(), "".into_string()) MessageEvent::new_initialized(global, UndefinedValue(), "".to_owned(), "".to_owned())
} }
pub fn new_initialized(global: GlobalRef, data: JSVal, origin: DOMString, lastEventId: DOMString) -> Temporary<MessageEvent> { pub fn new_initialized(global: GlobalRef, data: JSVal, origin: DOMString, lastEventId: DOMString) -> Temporary<MessageEvent> {
@ -78,8 +80,8 @@ impl MessageEvent {
scope: GlobalRef, scope: GlobalRef,
message: JSVal) { message: JSVal) {
let messageevent = MessageEvent::new( let messageevent = MessageEvent::new(
scope, "message".into_string(), false, false, message, scope, "message".to_owned(), false, false, message,
"".into_string(), "".into_string()).root(); "".to_owned(), "".to_owned()).root();
let event: JSRef<Event> = EventCast::from_ref(messageevent.r()); let event: JSRef<Event> = EventCast::from_ref(messageevent.r());
target.dispatch_event(event); target.dispatch_event(event);
} }

View file

@ -5,8 +5,10 @@
use servo_util::str::DOMString; use servo_util::str::DOMString;
use servo_util::opts; use servo_util::opts;
use std::borrow::ToOwned;
pub fn Product() -> DOMString { pub fn Product() -> DOMString {
"Gecko".into_string() "Gecko".to_owned()
} }
pub fn TaintEnabled() -> bool { pub fn TaintEnabled() -> bool {
@ -14,20 +16,20 @@ pub fn TaintEnabled() -> bool {
} }
pub fn AppName() -> DOMString { pub fn AppName() -> DOMString {
"Netscape".into_string() // Like Gecko/Webkit "Netscape".to_owned() // Like Gecko/Webkit
} }
pub fn AppCodeName() -> DOMString { pub fn AppCodeName() -> DOMString {
"Mozilla".into_string() "Mozilla".to_owned()
} }
pub fn Platform() -> DOMString { pub fn Platform() -> DOMString {
"".into_string() "".to_owned()
} }
pub fn UserAgent() -> DOMString { pub fn UserAgent() -> DOMString {
match opts::get().user_agent { match opts::get().user_agent {
Some(ref user_agent) => user_agent.clone(), Some(ref user_agent) => user_agent.clone(),
None => "".into_string(), None => "".to_owned(),
} }
} }

View file

@ -54,6 +54,7 @@ use js::jsapi::{JSContext, JSObject, JSTracer, JSRuntime};
use js::jsfriendapi; use js::jsfriendapi;
use libc; use libc;
use libc::{uintptr_t, c_void}; use libc::{uintptr_t, c_void};
use std::borrow::ToOwned;
use std::cell::{Cell, RefCell, Ref, RefMut}; use std::cell::{Cell, RefCell, Ref, RefMut};
use std::default::Default; use std::default::Default;
use std::iter::{FilterMap, Peekable}; use std::iter::{FilterMap, Peekable};
@ -854,17 +855,17 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
NodeInfo { NodeInfo {
uniqueId: self.unique_id.borrow().clone(), uniqueId: self.unique_id.borrow().clone(),
baseURI: self.GetBaseURI().unwrap_or("".into_string()), baseURI: self.GetBaseURI().unwrap_or("".to_owned()),
parent: self.GetParentNode().root().map(|node| node.r().get_unique_id()).unwrap_or("".into_string()), parent: self.GetParentNode().root().map(|node| node.r().get_unique_id()).unwrap_or("".to_owned()),
nodeType: self.NodeType() as uint, nodeType: self.NodeType() as uint,
namespaceURI: "".into_string(), //FIXME namespaceURI: "".to_owned(), //FIXME
nodeName: self.NodeName(), nodeName: self.NodeName(),
numChildren: self.ChildNodes().root().r().Length() as uint, numChildren: self.ChildNodes().root().r().Length() as uint,
//FIXME doctype nodes only //FIXME doctype nodes only
name: "".into_string(), name: "".to_owned(),
publicId: "".into_string(), publicId: "".to_owned(),
systemId: "".into_string(), systemId: "".to_owned(),
attrs: match ElementCast::to_ref(self) { attrs: match ElementCast::to_ref(self) {
Some(element) => element.summarize(), Some(element) => element.summarize(),
@ -878,7 +879,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
.map(|elem| NodeCast::from_ref(elem.root().r()) == self) .map(|elem| NodeCast::from_ref(elem.root().r()) == self)
.unwrap_or(false), .unwrap_or(false),
shortValue: self.GetNodeValue().unwrap_or("".into_string()), //FIXME: truncate shortValue: self.GetNodeValue().unwrap_or("".to_owned()), //FIXME: truncate
incompleteValue: false, //FIXME: reflect truncation incompleteValue: false, //FIXME: reflect truncation
} }
} }
@ -1567,7 +1568,7 @@ impl Node {
local: element.local_name().clone() local: element.local_name().clone()
}; };
let element = Element::create(name, let element = Element::create(name,
element.prefix().as_ref().map(|p| p.as_slice().into_string()), element.prefix().as_ref().map(|p| p.as_slice().to_owned()),
document.r(), ElementCreator::ScriptCreated); document.r(), ElementCreator::ScriptCreated);
NodeCast::from_temporary(element) NodeCast::from_temporary(element)
}, },
@ -1680,19 +1681,19 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
let elem: JSRef<Element> = ElementCast::to_ref(self).unwrap(); let elem: JSRef<Element> = ElementCast::to_ref(self).unwrap();
elem.TagName() elem.TagName()
} }
NodeTypeId::Text => "#text".into_string(), NodeTypeId::Text => "#text".to_owned(),
NodeTypeId::ProcessingInstruction => { NodeTypeId::ProcessingInstruction => {
let processing_instruction: JSRef<ProcessingInstruction> = let processing_instruction: JSRef<ProcessingInstruction> =
ProcessingInstructionCast::to_ref(self).unwrap(); ProcessingInstructionCast::to_ref(self).unwrap();
processing_instruction.Target() processing_instruction.Target()
} }
NodeTypeId::Comment => "#comment".into_string(), NodeTypeId::Comment => "#comment".to_owned(),
NodeTypeId::DocumentType => { NodeTypeId::DocumentType => {
let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap(); let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap();
doctype.name().clone() doctype.name().clone()
}, },
NodeTypeId::DocumentFragment => "#document-fragment".into_string(), NodeTypeId::DocumentFragment => "#document-fragment".to_owned(),
NodeTypeId::Document => "#document".into_string() NodeTypeId::Document => "#document".to_owned()
} }
} }

View file

@ -22,6 +22,8 @@ use servo_util::str::DOMString;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JSContext, JSObject};
use js::jsval::{JSVal, NullValue}; use js::jsval::{JSVal, NullValue};
use std::borrow::ToOwned;
#[dom_struct] #[dom_struct]
pub struct TestBinding { pub struct TestBinding {
reflector: Reflector, reflector: Reflector,
@ -51,7 +53,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn SetFloatAttribute(self, _: f32) {} fn SetFloatAttribute(self, _: f32) {}
fn DoubleAttribute(self) -> f64 { 0. } fn DoubleAttribute(self) -> f64 { 0. }
fn SetDoubleAttribute(self, _: f64) {} fn SetDoubleAttribute(self, _: f64) {}
fn StringAttribute(self) -> DOMString { "".into_string() } fn StringAttribute(self) -> DOMString { "".to_owned() }
fn SetStringAttribute(self, _: DOMString) {} fn SetStringAttribute(self, _: DOMString) {}
fn ByteStringAttribute(self) -> ByteString { ByteString::new(vec!()) } fn ByteStringAttribute(self) -> ByteString { ByteString::new(vec!()) }
fn SetByteStringAttribute(self, _: ByteString) {} fn SetByteStringAttribute(self, _: ByteString) {}
@ -64,7 +66,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn SetInterfaceAttribute(self, _: JSRef<Blob>) {} fn SetInterfaceAttribute(self, _: JSRef<Blob>) {}
fn UnionAttribute(self) -> HTMLElementOrLong { eLong(0) } fn UnionAttribute(self) -> HTMLElementOrLong { eLong(0) }
fn SetUnionAttribute(self, _: HTMLElementOrLong) {} fn SetUnionAttribute(self, _: HTMLElementOrLong) {}
fn Union2Attribute(self) -> EventOrString { eString("".into_string()) } fn Union2Attribute(self) -> EventOrString { eString("".to_owned()) }
fn SetUnion2Attribute(self, _: EventOrString) {} fn SetUnion2Attribute(self, _: EventOrString) {}
fn ArrayAttribute(self, _: *mut JSContext) -> *mut JSObject { NullValue().to_object_or_null() } fn ArrayAttribute(self, _: *mut JSContext) -> *mut JSObject { NullValue().to_object_or_null() }
fn AnyAttribute(self, _: *mut JSContext) -> JSVal { NullValue() } fn AnyAttribute(self, _: *mut JSContext) -> JSVal { NullValue() }
@ -94,7 +96,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn SetDoubleAttributeNullable(self, _: Option<f64>) {} fn SetDoubleAttributeNullable(self, _: Option<f64>) {}
fn GetByteStringAttributeNullable(self) -> Option<ByteString> { Some(ByteString::new(vec!())) } fn GetByteStringAttributeNullable(self) -> Option<ByteString> { Some(ByteString::new(vec!())) }
fn SetByteStringAttributeNullable(self, _: Option<ByteString>) {} fn SetByteStringAttributeNullable(self, _: Option<ByteString>) {}
fn GetStringAttributeNullable(self) -> Option<DOMString> { Some("".into_string()) } fn GetStringAttributeNullable(self) -> Option<DOMString> { Some("".to_owned()) }
fn SetStringAttributeNullable(self, _: Option<DOMString>) {} fn SetStringAttributeNullable(self, _: Option<DOMString>) {}
fn GetEnumAttributeNullable(self) -> Option<TestEnum> { Some(_empty) } fn GetEnumAttributeNullable(self) -> Option<TestEnum> { Some(_empty) }
fn GetInterfaceAttributeNullable(self) -> Option<Temporary<Blob>> { fn GetInterfaceAttributeNullable(self) -> Option<Temporary<Blob>> {
@ -104,7 +106,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn SetInterfaceAttributeNullable(self, _: Option<JSRef<Blob>>) {} fn SetInterfaceAttributeNullable(self, _: Option<JSRef<Blob>>) {}
fn GetUnionAttributeNullable(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) } fn GetUnionAttributeNullable(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) }
fn SetUnionAttributeNullable(self, _: Option<HTMLElementOrLong>) {} fn SetUnionAttributeNullable(self, _: Option<HTMLElementOrLong>) {}
fn GetUnion2AttributeNullable(self) -> Option<EventOrString> { Some(eString("".into_string())) } fn GetUnion2AttributeNullable(self) -> Option<EventOrString> { Some(eString("".to_owned())) }
fn SetUnion2AttributeNullable(self, _: Option<EventOrString>) {} fn SetUnion2AttributeNullable(self, _: Option<EventOrString>) {}
fn ReceiveVoid(self) -> () {} fn ReceiveVoid(self) -> () {}
fn ReceiveBoolean(self) -> bool { false } fn ReceiveBoolean(self) -> bool { false }
@ -118,7 +120,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn ReceiveUnsignedLongLong(self) -> u64 { 0 } fn ReceiveUnsignedLongLong(self) -> u64 { 0 }
fn ReceiveFloat(self) -> f32 { 0. } fn ReceiveFloat(self) -> f32 { 0. }
fn ReceiveDouble(self) -> f64 { 0. } fn ReceiveDouble(self) -> f64 { 0. }
fn ReceiveString(self) -> DOMString { "".into_string() } fn ReceiveString(self) -> DOMString { "".to_owned() }
fn ReceiveByteString(self) -> ByteString { ByteString::new(vec!()) } fn ReceiveByteString(self) -> ByteString { ByteString::new(vec!()) }
fn ReceiveEnum(self) -> TestEnum { _empty } fn ReceiveEnum(self) -> TestEnum { _empty }
fn ReceiveInterface(self) -> Temporary<Blob> { fn ReceiveInterface(self) -> Temporary<Blob> {
@ -127,7 +129,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
} }
fn ReceiveAny(self, _: *mut JSContext) -> JSVal { NullValue() } fn ReceiveAny(self, _: *mut JSContext) -> JSVal { NullValue() }
fn ReceiveUnion(self) -> HTMLElementOrLong { eLong(0) } fn ReceiveUnion(self) -> HTMLElementOrLong { eLong(0) }
fn ReceiveUnion2(self) -> EventOrString { eString("".into_string()) } fn ReceiveUnion2(self) -> EventOrString { eString("".to_owned()) }
fn ReceiveNullableBoolean(self) -> Option<bool> { Some(false) } fn ReceiveNullableBoolean(self) -> Option<bool> { Some(false) }
fn ReceiveNullableByte(self) -> Option<i8> { Some(0) } fn ReceiveNullableByte(self) -> Option<i8> { Some(0) }
@ -140,7 +142,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn ReceiveNullableUnsignedLongLong(self) -> Option<u64> { Some(0) } fn ReceiveNullableUnsignedLongLong(self) -> Option<u64> { Some(0) }
fn ReceiveNullableFloat(self) -> Option<f32> { Some(0.) } fn ReceiveNullableFloat(self) -> Option<f32> { Some(0.) }
fn ReceiveNullableDouble(self) -> Option<f64> { Some(0.) } fn ReceiveNullableDouble(self) -> Option<f64> { Some(0.) }
fn ReceiveNullableString(self) -> Option<DOMString> { Some("".into_string()) } fn ReceiveNullableString(self) -> Option<DOMString> { Some("".to_owned()) }
fn ReceiveNullableByteString(self) -> Option<ByteString> { Some(ByteString::new(vec!())) } fn ReceiveNullableByteString(self) -> Option<ByteString> { Some(ByteString::new(vec!())) }
fn ReceiveNullableEnum(self) -> Option<TestEnum> { Some(_empty) } fn ReceiveNullableEnum(self) -> Option<TestEnum> { Some(_empty) }
fn ReceiveNullableInterface(self) -> Option<Temporary<Blob>> { fn ReceiveNullableInterface(self) -> Option<Temporary<Blob>> {
@ -148,7 +150,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
Some(Blob::new(global.r(), None, "")) Some(Blob::new(global.r(), None, ""))
} }
fn ReceiveNullableUnion(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) } fn ReceiveNullableUnion(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) }
fn ReceiveNullableUnion2(self) -> Option<EventOrString> { Some(eString("".into_string())) } fn ReceiveNullableUnion2(self) -> Option<EventOrString> { Some(eString("".to_owned())) }
fn PassBoolean(self, _: bool) {} fn PassBoolean(self, _: bool) {}
fn PassByte(self, _: i8) {} fn PassByte(self, _: i8) {}

View file

@ -5,6 +5,8 @@
use servo_util::str::DOMString; use servo_util::str::DOMString;
use url::Url; use url::Url;
use std::borrow::ToOwned;
pub struct UrlHelper; pub struct UrlHelper;
impl UrlHelper { impl UrlHelper {
@ -14,16 +16,16 @@ impl UrlHelper {
pub fn Search(url: &Url) -> DOMString { pub fn Search(url: &Url) -> DOMString {
match url.query { match url.query {
None => "".into_string(), None => "".to_owned(),
Some(ref query) if query.as_slice() == "" => "".into_string(), Some(ref query) if query.as_slice() == "" => "".to_owned(),
Some(ref query) => format!("?{}", query) Some(ref query) => format!("?{}", query)
} }
} }
pub fn Hash(url: &Url) -> DOMString { pub fn Hash(url: &Url) -> DOMString {
match url.fragment { match url.fragment {
None => "".into_string(), None => "".to_owned(),
Some(ref hash) if hash.as_slice() == "" => "".into_string(), Some(ref hash) if hash.as_slice() == "" => "".to_owned(),
Some(ref hash) => format!("#{}", hash) Some(ref hash) => format!("#{}", hash)
} }
} }

View file

@ -50,6 +50,7 @@ use servo_util::str::DOMString;
use servo_util::task::spawn_named; use servo_util::task::spawn_named;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
use std::comm::{Sender, Receiver, channel}; use std::comm::{Sender, Receiver, channel};
use std::default::Default; use std::default::Default;
@ -168,7 +169,7 @@ impl XMLHttpRequest {
timeout: Cell::new(0u32), timeout: Cell::new(0u32),
with_credentials: Cell::new(false), with_credentials: Cell::new(false),
upload: JS::from_rooted(XMLHttpRequestUpload::new(global)), upload: JS::from_rooted(XMLHttpRequestUpload::new(global)),
response_url: "".into_string(), response_url: "".to_owned(),
status: Cell::new(0), status: Cell::new(0),
status_text: DOMRefCell::new(ByteString::new(vec!())), status_text: DOMRefCell::new(ByteString::new(vec!())),
response: DOMRefCell::new(ByteString::new(vec!())), response: DOMRefCell::new(ByteString::new(vec!())),
@ -454,7 +455,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
None => {} None => {}
} }
headers.set_raw(name_str.into_string(), vec![value.as_slice().to_vec()]); headers.set_raw(name_str.to_owned(), vec![value.as_slice().to_vec()]);
Ok(()) Ok(())
} }
fn Timeout(self) -> u32 { fn Timeout(self) -> u32 {
@ -525,12 +526,12 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
// If one of the event handlers below aborts the fetch by calling // If one of the event handlers below aborts the fetch by calling
// abort or open we will need the current generation id to detect it. // abort or open we will need the current generation id to detect it.
let gen_id = self.generation_id.get(); let gen_id = self.generation_id.get();
self.dispatch_response_progress_event("loadstart".into_string()); self.dispatch_response_progress_event("loadstart".to_owned());
if self.generation_id.get() != gen_id { if self.generation_id.get() != gen_id {
return Ok(()); return Ok(());
} }
if !self.upload_complete.get() { if !self.upload_complete.get() {
self.dispatch_upload_progress_event("loadstart".into_string(), Some(0)); self.dispatch_upload_progress_event("loadstart".to_owned(), Some(0));
if self.generation_id.get() != gen_id { if self.generation_id.get() != gen_id {
return Ok(()); return Ok(());
} }
@ -562,10 +563,10 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
let n = "content-type"; let n = "content-type";
match data { match data {
Some(eString(_)) => Some(eString(_)) =>
request_headers.set_raw(n.into_string(), vec![join_raw("text/plain", params)]), request_headers.set_raw(n.to_owned(), vec![join_raw("text/plain", params)]),
Some(eURLSearchParams(_)) => Some(eURLSearchParams(_)) =>
request_headers.set_raw( request_headers.set_raw(
n.into_string(), vec![join_raw("application/x-www-form-urlencoded", params)]), n.to_owned(), vec![join_raw("application/x-www-form-urlencoded", params)]),
None => () None => ()
} }
} }
@ -602,9 +603,9 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
buf.push_str(format!("{}", p).as_slice()); buf.push_str(format!("{}", p).as_slice());
}); });
referer_url.serialize_path().map(|ref h| buf.push_str(h.as_slice())); referer_url.serialize_path().map(|ref h| buf.push_str(h.as_slice()));
self.request_headers.borrow_mut().set_raw("Referer".into_string(), vec![buf.into_bytes()]); self.request_headers.borrow_mut().set_raw("Referer".to_owned(), vec![buf.into_bytes()]);
}, },
Ok(Some(ref req)) => self.insert_trusted_header("origin".into_string(), Ok(Some(ref req)) => self.insert_trusted_header("origin".to_owned(),
format!("{}", req.origin)), format!("{}", req.origin)),
_ => {} _ => {}
} }
@ -705,7 +706,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
}, },
_ if self.ready_state.get() != XMLHttpRequestState::XHRDone => NullValue(), _ if self.ready_state.get() != XMLHttpRequestState::XHRDone => NullValue(),
Json => { Json => {
let decoded = UTF_8.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().into_string(); let decoded = UTF_8.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().to_owned();
let decoded: Vec<u16> = decoded.as_slice().utf16_units().collect(); let decoded: Vec<u16> = decoded.as_slice().utf16_units().collect();
let mut vp = UndefinedValue(); let mut vp = UndefinedValue();
unsafe { unsafe {
@ -727,7 +728,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
_empty | Text => { _empty | Text => {
match self.ready_state.get() { match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::XHRDone => Ok(self.text_response()), XMLHttpRequestState::Loading | XMLHttpRequestState::XHRDone => Ok(self.text_response()),
_ => Ok("".into_string()) _ => Ok("".to_owned())
} }
}, },
_ => Err(InvalidState) _ => Err(InvalidState)
@ -770,7 +771,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
self.ready_state.set(rs); self.ready_state.set(rs);
let global = self.global.root(); let global = self.global.root();
let event = Event::new(global.r(), let event = Event::new(global.r(),
"readystatechange".into_string(), "readystatechange".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
@ -804,11 +805,11 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
self.upload_complete.set(true); self.upload_complete.set(true);
// Substeps 2-4 // Substeps 2-4
if !self.sync.get() { if !self.sync.get() {
self.dispatch_upload_progress_event("progress".into_string(), None); self.dispatch_upload_progress_event("progress".to_owned(), None);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event("load".into_string(), None); self.dispatch_upload_progress_event("load".to_owned(), None);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event("loadend".into_string(), None); self.dispatch_upload_progress_event("loadend".to_owned(), None);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
} }
// Part of step 13, send() (processing response) // Part of step 13, send() (processing response)
@ -836,7 +837,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
self.change_ready_state(XMLHttpRequestState::Loading); self.change_ready_state(XMLHttpRequestState::Loading);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
} }
self.dispatch_response_progress_event("progress".into_string()); self.dispatch_response_progress_event("progress".to_owned());
} }
}, },
XHRProgress::Done(_) => { XHRProgress::Done(_) => {
@ -852,11 +853,11 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
self.change_ready_state(XMLHttpRequestState::XHRDone); self.change_ready_state(XMLHttpRequestState::XHRDone);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
// Subsubsteps 10-12 // Subsubsteps 10-12
self.dispatch_response_progress_event("progress".into_string()); self.dispatch_response_progress_event("progress".to_owned());
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_response_progress_event("load".into_string()); self.dispatch_response_progress_event("load".to_owned());
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_response_progress_event("loadend".into_string()); self.dispatch_response_progress_event("loadend".to_owned());
}, },
XHRProgress::Errored(_, e) => { XHRProgress::Errored(_, e) => {
self.send_flag.set(false); self.send_flag.set(false);
@ -873,18 +874,18 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
let upload_complete: &Cell<bool> = &self.upload_complete; let upload_complete: &Cell<bool> = &self.upload_complete;
if !upload_complete.get() { if !upload_complete.get() {
upload_complete.set(true); upload_complete.set(true);
self.dispatch_upload_progress_event("progress".into_string(), None); self.dispatch_upload_progress_event("progress".to_owned(), None);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(errormsg.into_string(), None); self.dispatch_upload_progress_event(errormsg.to_owned(), None);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event("loadend".into_string(), None); self.dispatch_upload_progress_event("loadend".to_owned(), None);
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
} }
self.dispatch_response_progress_event("progress".into_string()); self.dispatch_response_progress_event("progress".to_owned());
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(errormsg.into_string()); self.dispatch_response_progress_event(errormsg.to_owned());
return_if_fetch_was_terminated!(); return_if_fetch_was_terminated!();
self.dispatch_response_progress_event("loadend".into_string()); self.dispatch_response_progress_event("loadend".to_owned());
} }
} }
} }
@ -970,7 +971,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
// According to Simon, decode() should never return an error, so unwrap()ing // According to Simon, decode() should never return an error, so unwrap()ing
// the result should be fine. XXXManishearth have a closer look at this later // the result should be fine. XXXManishearth have a closer look at this later
encoding.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().into_string() encoding.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().to_owned()
} }
fn filter_response_headers(self) -> Headers { fn filter_response_headers(self) -> Headers {
// http://fetch.spec.whatwg.org/#concept-response-header-list // http://fetch.spec.whatwg.org/#concept-response-header-list

View file

@ -79,6 +79,7 @@ use url::Url;
use libc; use libc;
use std::any::{Any, AnyRefExt}; use std::any::{Any, AnyRefExt};
use std::borrow::ToOwned;
use std::cell::Cell; use std::cell::Cell;
use std::comm::{channel, Sender, Receiver, Select}; use std::comm::{channel, Sender, Receiver, Select};
use std::fmt::{mod, Show}; use std::fmt::{mod, Show};
@ -846,7 +847,7 @@ impl ScriptTask {
let jsval = window.r().evaluate_js_on_global_with_result(evalstr); let jsval = window.r().evaluate_js_on_global_with_result(evalstr);
let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval, let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval,
StringificationBehavior::Empty); StringificationBehavior::Empty);
(HTMLInput::InputString(strval.unwrap_or("".into_string())), doc_url) (HTMLInput::InputString(strval.unwrap_or("".to_owned())), doc_url)
}; };
parse_html(document.r(), parser_input, &final_url); parse_html(document.r(), parser_input, &final_url);
@ -1002,13 +1003,13 @@ impl ScriptTask {
let ev_type = match state { let ev_type = match state {
KeyState::Pressed | KeyState::Repeated => "keydown", KeyState::Pressed | KeyState::Repeated => "keydown",
KeyState::Released => "keyup", KeyState::Released => "keyup",
}.into_string(); }.to_owned();
let props = KeyboardEvent::key_properties(key, modifiers); let props = KeyboardEvent::key_properties(key, modifiers);
let keyevent = KeyboardEvent::new(window.r(), ev_type, true, true, let keyevent = KeyboardEvent::new(window.r(), ev_type, true, true,
Some(window.r()), 0, Some(window.r()), 0,
props.key.into_string(), props.code.into_string(), props.key.to_owned(), props.code.to_owned(),
props.location, is_repeating, is_composing, props.location, is_repeating, is_composing,
ctrl, alt, shift, meta, ctrl, alt, shift, meta,
None, props.key_code).root(); None, props.key_code).root();
@ -1019,9 +1020,9 @@ impl ScriptTask {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys
if state != KeyState::Released && props.is_printable() && !prevented { if state != KeyState::Released && props.is_printable() && !prevented {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order
let event = KeyboardEvent::new(window.r(), "keypress".into_string(), let event = KeyboardEvent::new(window.r(), "keypress".to_owned(),
true, true, Some(window.r()), true, true, Some(window.r()),
0, props.key.into_string(), props.code.into_string(), 0, props.key.to_owned(), props.code.to_owned(),
props.location, is_repeating, is_composing, props.location, is_repeating, is_composing,
ctrl, alt, shift, meta, ctrl, alt, shift, meta,
props.char_code, 0).root(); props.char_code, 0).root();
@ -1105,7 +1106,7 @@ impl ScriptTask {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports // http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(window.r(), let uievent = UIEvent::new(window.r(),
"resize".into_string(), false, "resize".to_owned(), false,
false, Some(window.r()), false, Some(window.r()),
0i32).root(); 0i32).root();
let event: JSRef<Event> = EventCast::from_ref(uievent.r()); let event: JSRef<Event> = EventCast::from_ref(uievent.r());
@ -1156,7 +1157,7 @@ impl ScriptTask {
let event = let event =
Event::new(GlobalRef::Window(window.r()), Event::new(GlobalRef::Window(window.r()),
"click".into_string(), "click".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events
@ -1208,7 +1209,7 @@ impl ScriptTask {
let y = point.y.to_i32().unwrap_or(0); let y = point.y.to_i32().unwrap_or(0);
let mouse_event = MouseEvent::new(window.r(), let mouse_event = MouseEvent::new(window.r(),
"mousemove".into_string(), "mousemove".to_owned(),
true, true,
true, true,
Some(window.r()), Some(window.r()),
@ -1360,7 +1361,7 @@ impl DocumentProgressHandler {
fn dispatch_dom_content_loaded(&self) { fn dispatch_dom_content_loaded(&self) {
let document = self.addr.to_temporary().root(); let document = self.addr.to_temporary().root();
let window = document.r().window().root(); let window = document.r().window().root();
let event = Event::new(GlobalRef::Window(window.r()), "DOMContentLoaded".into_string(), let event = Event::new(GlobalRef::Window(window.r()), "DOMContentLoaded".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(document.r()); let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(document.r());
@ -1375,7 +1376,7 @@ impl DocumentProgressHandler {
fn dispatch_load(&self) { fn dispatch_load(&self) {
let document = self.addr.to_temporary().root(); let document = self.addr.to_temporary().root();
let window = document.r().window().root(); let window = document.r().window().root();
let event = Event::new(GlobalRef::Window(window.r()), "load".into_string(), let event = Event::new(GlobalRef::Window(window.r()), "load".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(window.r()); let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(window.r());

View file

@ -9,6 +9,7 @@ use dom::bindings::js::JSRef;
use dom::keyboardevent::KeyboardEvent; use dom::keyboardevent::KeyboardEvent;
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::borrow::ToOwned;
use std::cmp::{min, max}; use std::cmp::{min, max};
use std::default::Default; use std::default::Default;
use std::num::SignedInt; use std::num::SignedInt;
@ -106,7 +107,7 @@ impl TextInput {
-1 -1
}, Selection::Selected); }, Selection::Selected);
} }
self.replace_selection("".into_string()); self.replace_selection("".to_owned());
} }
/// Insert a character at the current editing point /// Insert a character at the current editing point
@ -139,12 +140,12 @@ impl TextInput {
let lines_suffix = self.lines.slice(end.line + 1, self.lines.len()); let lines_suffix = self.lines.slice(end.line + 1, self.lines.len());
let mut insert_lines = if self.multiline { let mut insert_lines = if self.multiline {
insert.as_slice().split('\n').map(|s| s.into_string()).collect() insert.as_slice().split('\n').map(|s| s.to_owned()).collect()
} else { } else {
vec!(insert) vec!(insert)
}; };
let mut new_line = prefix.into_string(); let mut new_line = prefix.to_owned();
new_line.push_str(insert_lines[0].as_slice()); new_line.push_str(insert_lines[0].as_slice());
insert_lines[0] = new_line; insert_lines[0] = new_line;
@ -338,7 +339,7 @@ impl TextInput {
/// Get the current contents of the text input. Multiple lines are joined by \n. /// Get the current contents of the text input. Multiple lines are joined by \n.
pub fn get_content(&self) -> DOMString { pub fn get_content(&self) -> DOMString {
let mut content = "".into_string(); let mut content = "".to_owned();
for (i, line) in self.lines.iter().enumerate() { for (i, line) in self.lines.iter().enumerate() {
content.push_str(line.as_slice()); content.push_str(line.as_slice());
if i < self.lines.len() - 1 { if i < self.lines.len() - 1 {
@ -352,7 +353,7 @@ impl TextInput {
/// any \n encountered will be stripped and force a new logical line. /// any \n encountered will be stripped and force a new logical line.
pub fn set_content(&mut self, content: DOMString) { pub fn set_content(&mut self, content: DOMString) {
self.lines = if self.multiline { self.lines = if self.multiline {
content.as_slice().split('\n').map(|s| s.into_string()).collect() content.as_slice().split('\n').map(|s| s.to_owned()).collect()
} else { } else {
vec!(content) vec!(content)
}; };
@ -363,7 +364,7 @@ impl TextInput {
#[test] #[test]
fn test_textinput_delete_char() { fn test_textinput_delete_char() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".into_string()); let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned());
textinput.adjust_horizontal(2, Selection::NotSelected); textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.delete_char(DeleteDir::Backward); textinput.delete_char(DeleteDir::Backward);
assert_eq!(textinput.get_content().as_slice(), "acdefg"); assert_eq!(textinput.get_content().as_slice(), "acdefg");
@ -378,7 +379,7 @@ fn test_textinput_delete_char() {
#[test] #[test]
fn test_textinput_insert_char() { fn test_textinput_insert_char() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".into_string()); let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned());
textinput.adjust_horizontal(2, Selection::NotSelected); textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.insert_char('a'); textinput.insert_char('a');
assert_eq!(textinput.get_content().as_slice(), "abacdefg"); assert_eq!(textinput.get_content().as_slice(), "abacdefg");
@ -390,7 +391,7 @@ fn test_textinput_insert_char() {
#[test] #[test]
fn test_textinput_get_sorted_selection() { fn test_textinput_get_sorted_selection() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".into_string()); let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned());
textinput.adjust_horizontal(2, Selection::NotSelected); textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.adjust_horizontal(2, Selection::Selected); textinput.adjust_horizontal(2, Selection::Selected);
let (begin, end) = textinput.get_sorted_selection(); let (begin, end) = textinput.get_sorted_selection();
@ -407,17 +408,17 @@ fn test_textinput_get_sorted_selection() {
#[test] #[test]
fn test_textinput_replace_selection() { fn test_textinput_replace_selection() {
let mut textinput = TextInput::new(Lines::Single, "abcdefg".into_string()); let mut textinput = TextInput::new(Lines::Single, "abcdefg".to_owned());
textinput.adjust_horizontal(2, Selection::NotSelected); textinput.adjust_horizontal(2, Selection::NotSelected);
textinput.adjust_horizontal(2, Selection::Selected); textinput.adjust_horizontal(2, Selection::Selected);
textinput.replace_selection("xyz".into_string()); textinput.replace_selection("xyz".to_owned());
assert_eq!(textinput.get_content().as_slice(), "abxyzefg"); assert_eq!(textinput.get_content().as_slice(), "abxyzefg");
} }
#[test] #[test]
fn test_textinput_current_line_length() { fn test_textinput_current_line_length() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".into_string()); let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned());
assert_eq!(textinput.current_line_length(), 3); assert_eq!(textinput.current_line_length(), 3);
textinput.adjust_vertical(1, Selection::NotSelected); textinput.adjust_vertical(1, Selection::NotSelected);
@ -429,7 +430,7 @@ fn test_textinput_current_line_length() {
#[test] #[test]
fn test_textinput_adjust_vertical() { fn test_textinput_adjust_vertical() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".into_string()); let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned());
textinput.adjust_horizontal(3, Selection::NotSelected); textinput.adjust_horizontal(3, Selection::NotSelected);
textinput.adjust_vertical(1, Selection::NotSelected); textinput.adjust_vertical(1, Selection::NotSelected);
assert_eq!(textinput.edit_point.line, 1); assert_eq!(textinput.edit_point.line, 1);
@ -446,7 +447,7 @@ fn test_textinput_adjust_vertical() {
#[test] #[test]
fn test_textinput_adjust_horizontal() { fn test_textinput_adjust_horizontal() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".into_string()); let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned());
textinput.adjust_horizontal(4, Selection::NotSelected); textinput.adjust_horizontal(4, Selection::NotSelected);
assert_eq!(textinput.edit_point.line, 1); assert_eq!(textinput.edit_point.line, 1);
assert_eq!(textinput.edit_point.index, 0); assert_eq!(textinput.edit_point.index, 0);
@ -466,12 +467,12 @@ fn test_textinput_adjust_horizontal() {
#[test] #[test]
fn test_textinput_handle_return() { fn test_textinput_handle_return() {
let mut single_line_textinput = TextInput::new(Lines::Single, "abcdef".into_string()); let mut single_line_textinput = TextInput::new(Lines::Single, "abcdef".to_owned());
single_line_textinput.adjust_horizontal(3, Selection::NotSelected); single_line_textinput.adjust_horizontal(3, Selection::NotSelected);
single_line_textinput.handle_return(); single_line_textinput.handle_return();
assert_eq!(single_line_textinput.get_content().as_slice(), "abcdef"); assert_eq!(single_line_textinput.get_content().as_slice(), "abcdef");
let mut multi_line_textinput = TextInput::new(Lines::Multiple, "abcdef".into_string()); let mut multi_line_textinput = TextInput::new(Lines::Multiple, "abcdef".to_owned());
multi_line_textinput.adjust_horizontal(3, Selection::NotSelected); multi_line_textinput.adjust_horizontal(3, Selection::NotSelected);
multi_line_textinput.handle_return(); multi_line_textinput.handle_return();
assert_eq!(multi_line_textinput.get_content().as_slice(), "abc\ndef"); assert_eq!(multi_line_textinput.get_content().as_slice(), "abc\ndef");
@ -479,7 +480,7 @@ fn test_textinput_handle_return() {
#[test] #[test]
fn test_textinput_select_all() { fn test_textinput_select_all() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".into_string()); let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned());
assert_eq!(textinput.edit_point.line, 0); assert_eq!(textinput.edit_point.line, 0);
assert_eq!(textinput.edit_point.index, 0); assert_eq!(textinput.edit_point.index, 0);
@ -490,19 +491,19 @@ fn test_textinput_select_all() {
#[test] #[test]
fn test_textinput_get_content() { fn test_textinput_get_content() {
let single_line_textinput = TextInput::new(Lines::Single, "abcdefg".into_string()); let single_line_textinput = TextInput::new(Lines::Single, "abcdefg".to_owned());
assert_eq!(single_line_textinput.get_content().as_slice(), "abcdefg"); assert_eq!(single_line_textinput.get_content().as_slice(), "abcdefg");
let multi_line_textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".into_string()); let multi_line_textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned());
assert_eq!(multi_line_textinput.get_content().as_slice(), "abc\nde\nf"); assert_eq!(multi_line_textinput.get_content().as_slice(), "abc\nde\nf");
} }
#[test] #[test]
fn test_textinput_set_content() { fn test_textinput_set_content() {
let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".into_string()); let mut textinput = TextInput::new(Lines::Multiple, "abc\nde\nf".to_owned());
assert_eq!(textinput.get_content().as_slice(), "abc\nde\nf"); assert_eq!(textinput.get_content().as_slice(), "abc\nde\nf");
textinput.set_content("abc\nf".into_string()); textinput.set_content("abc\nf".to_owned());
assert_eq!(textinput.get_content().as_slice(), "abc\nf"); assert_eq!(textinput.get_content().as_slice(), "abc\nf");
assert_eq!(textinput.edit_point.line, 0); assert_eq!(textinput.edit_point.line, 0);
@ -510,7 +511,7 @@ fn test_textinput_set_content() {
textinput.adjust_horizontal(3, Selection::Selected); textinput.adjust_horizontal(3, Selection::Selected);
assert_eq!(textinput.edit_point.line, 0); assert_eq!(textinput.edit_point.line, 0);
assert_eq!(textinput.edit_point.index, 3); assert_eq!(textinput.edit_point.index, 3);
textinput.set_content("de".into_string()); textinput.set_content("de".to_owned());
assert_eq!(textinput.get_content().as_slice(), "de"); assert_eq!(textinput.get_content().as_slice(), "de");
assert_eq!(textinput.edit_point.line, 0); assert_eq!(textinput.edit_point.line, 0);
assert_eq!(textinput.edit_point.index, 2); assert_eq!(textinput.edit_point.index, 2);

View file

@ -41,6 +41,9 @@ use servo::Browser;
#[cfg(not(test))] #[cfg(not(test))]
use compositing::windowing::WindowEvent; use compositing::windowing::WindowEvent;
#[cfg(target_os="android")]
use std::borrow::ToOwned;
#[cfg(not(any(test,target_os="android")))] #[cfg(not(any(test,target_os="android")))]
use std::os; use std::os;
@ -55,8 +58,8 @@ android_start!(main)
#[cfg(target_os="android")] #[cfg(target_os="android")]
fn get_args() -> Vec<String> { fn get_args() -> Vec<String> {
vec![ vec![
"servo".into_string(), "servo".to_owned(),
"http://en.wikipedia.org/wiki/Rust".into_string() "http://en.wikipedia.org/wiki/Rust".to_owned()
] ]
} }

View file

@ -328,6 +328,7 @@ mod tests {
use selector_matching::StylesheetOrigin; use selector_matching::StylesheetOrigin;
use super::*; use super::*;
use url::Url; use url::Url;
use std::borrow::ToOwned;
fn test_media_rule(css: &str, callback: |&MediaQueryList, &str|) { fn test_media_rule(css: &str, callback: |&MediaQueryList, &str|) {
let url = Url::parse("http://localhost").unwrap(); let url = Url::parse("http://localhost").unwrap();
@ -346,152 +347,152 @@ mod tests {
let ss = Stylesheet::from_str(css, url, StylesheetOrigin::Author); let ss = Stylesheet::from_str(css, url, StylesheetOrigin::Author);
let mut rule_count: int = 0; let mut rule_count: int = 0;
iter_stylesheet_style_rules(&ss, device, |_| rule_count += 1); iter_stylesheet_style_rules(&ss, device, |_| rule_count += 1);
assert!(rule_count == expected_rule_count, css.into_string()); assert!(rule_count == expected_rule_count, css.to_owned());
} }
#[test] #[test]
fn test_mq_empty() { fn test_mq_empty() {
test_media_rule("@media { }", |list, css| { test_media_rule("@media { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
} }
#[test] #[test]
fn test_mq_screen() { fn test_mq_screen() {
test_media_rule("@media screen { }", |list, css| { test_media_rule("@media screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media only screen { }", |list, css| { test_media_rule("@media only screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.into_string()); assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media not screen { }", |list, css| { test_media_rule("@media not screen { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
} }
#[test] #[test]
fn test_mq_print() { fn test_mq_print() {
test_media_rule("@media print { }", |list, css| { test_media_rule("@media print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media only print { }", |list, css| { test_media_rule("@media only print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.into_string()); assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media not print { }", |list, css| { test_media_rule("@media not print { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
} }
#[test] #[test]
fn test_mq_unknown() { fn test_mq_unknown() {
test_media_rule("@media fridge { }", |list, css| { test_media_rule("@media fridge { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media only glass { }", |list, css| { test_media_rule("@media only glass { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.into_string()); assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media not wood { }", |list, css| { test_media_rule("@media not wood { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
} }
#[test] #[test]
fn test_mq_all() { fn test_mq_all() {
test_media_rule("@media all { }", |list, css| { test_media_rule("@media all { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media only all { }", |list, css| { test_media_rule("@media only all { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Only), css.into_string()); assert!(q.qualifier == Some(Qualifier::Only), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media not all { }", |list, css| { test_media_rule("@media not all { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
} }
#[test] #[test]
fn test_mq_or() { fn test_mq_or() {
test_media_rule("@media screen, print { }", |list, css| { test_media_rule("@media screen, print { }", |list, css| {
assert!(list.media_queries.len() == 2, css.into_string()); assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0]; let q0 = &list.media_queries[0];
assert!(q0.qualifier == None, css.into_string()); assert!(q0.qualifier == None, css.to_owned());
assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q0.expressions.len() == 0, css.into_string()); assert!(q0.expressions.len() == 0, css.to_owned());
let q1 = &list.media_queries[1]; let q1 = &list.media_queries[1];
assert!(q1.qualifier == None, css.into_string()); assert!(q1.qualifier == None, css.to_owned());
assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.into_string()); assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q1.expressions.len() == 0, css.into_string()); assert!(q1.expressions.len() == 0, css.to_owned());
}); });
} }
#[test] #[test]
fn test_mq_default_expressions() { fn test_mq_default_expressions() {
test_media_rule("@media (min-width: 100px) { }", |list, css| { test_media_rule("@media (min-width: 100px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 1, css.into_string()); assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -499,11 +500,11 @@ mod tests {
}); });
test_media_rule("@media (max-width: 43px) { }", |list, css| { test_media_rule("@media (max-width: 43px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 1, css.into_string()); assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)), Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -514,11 +515,11 @@ mod tests {
#[test] #[test]
fn test_mq_expressions() { fn test_mq_expressions() {
test_media_rule("@media screen and (min-width: 100px) { }", |list, css| { test_media_rule("@media screen and (min-width: 100px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 1, css.into_string()); assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -526,11 +527,11 @@ mod tests {
}); });
test_media_rule("@media print and (max-width: 43px) { }", |list, css| { test_media_rule("@media print and (max-width: 43px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q.expressions.len() == 1, css.into_string()); assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)), Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(43)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -538,11 +539,11 @@ mod tests {
}); });
test_media_rule("@media fridge and (max-width: 52px) { }", |list, css| { test_media_rule("@media fridge and (max-width: 52px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Unknown), css.to_owned());
assert!(q.expressions.len() == 1, css.into_string()); assert!(q.expressions.len() == 1, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(52)), Expression::Width(Range::Max(w)) => assert!(w == Au::from_px(52)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -553,11 +554,11 @@ mod tests {
#[test] #[test]
fn test_mq_multiple_expressions() { fn test_mq_multiple_expressions() {
test_media_rule("@media (min-width: 100px) and (max-width: 200px) { }", |list, css| { test_media_rule("@media (min-width: 100px) and (max-width: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == None, css.into_string()); assert!(q.qualifier == None, css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 2, css.into_string()); assert!(q.expressions.len() == 2, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -569,11 +570,11 @@ mod tests {
}); });
test_media_rule("@media not screen and (min-width: 100px) and (max-width: 200px) { }", |list, css| { test_media_rule("@media not screen and (min-width: 100px) and (max-width: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q.expressions.len() == 2, css.into_string()); assert!(q.expressions.len() == 2, css.to_owned());
match q.expressions[0] { match q.expressions[0] {
Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)), Expression::Width(Range::Min(w)) => assert!(w == Au::from_px(100)),
_ => panic!("wrong expression type"), _ => panic!("wrong expression type"),
@ -588,75 +589,75 @@ mod tests {
#[test] #[test]
fn test_mq_malformed_expressions() { fn test_mq_malformed_expressions() {
test_media_rule("@media (min-width: 100blah) and (max-width: 200px) { }", |list, css| { test_media_rule("@media (min-width: 100blah) and (max-width: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media screen and (height: 200px) { }", |list, css| { test_media_rule("@media screen and (height: 200px) { }", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media (min-width: 30em foo bar) {}", |list, css| { test_media_rule("@media (min-width: 30em foo bar) {}", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media not {}", |list, css| { test_media_rule("@media not {}", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media not (min-width: 300px) {}", |list, css| { test_media_rule("@media not (min-width: 300px) {}", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media , {}", |list, css| { test_media_rule("@media , {}", |list, css| {
assert!(list.media_queries.len() == 1, css.into_string()); assert!(list.media_queries.len() == 1, css.to_owned());
let q = &list.media_queries[0]; let q = &list.media_queries[0];
assert!(q.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q.media_type == MediaQueryType::All, css.into_string()); assert!(q.media_type == MediaQueryType::All, css.to_owned());
assert!(q.expressions.len() == 0, css.into_string()); assert!(q.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media screen 4px, print {}", |list, css| { test_media_rule("@media screen 4px, print {}", |list, css| {
assert!(list.media_queries.len() == 2, css.into_string()); assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0]; let q0 = &list.media_queries[0];
assert!(q0.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q0.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q0.media_type == MediaQueryType::All, css.into_string()); assert!(q0.media_type == MediaQueryType::All, css.to_owned());
assert!(q0.expressions.len() == 0, css.into_string()); assert!(q0.expressions.len() == 0, css.to_owned());
let q1 = &list.media_queries[1]; let q1 = &list.media_queries[1];
assert!(q1.qualifier == None, css.into_string()); assert!(q1.qualifier == None, css.to_owned());
assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.into_string()); assert!(q1.media_type == MediaQueryType::MediaType(MediaType::Print), css.to_owned());
assert!(q1.expressions.len() == 0, css.into_string()); assert!(q1.expressions.len() == 0, css.to_owned());
}); });
test_media_rule("@media screen, {}", |list, css| { test_media_rule("@media screen, {}", |list, css| {
assert!(list.media_queries.len() == 2, css.into_string()); assert!(list.media_queries.len() == 2, css.to_owned());
let q0 = &list.media_queries[0]; let q0 = &list.media_queries[0];
assert!(q0.qualifier == None, css.into_string()); assert!(q0.qualifier == None, css.to_owned());
assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.into_string()); assert!(q0.media_type == MediaQueryType::MediaType(MediaType::Screen), css.to_owned());
assert!(q0.expressions.len() == 0, css.into_string()); assert!(q0.expressions.len() == 0, css.to_owned());
let q1 = &list.media_queries[1]; let q1 = &list.media_queries[1];
assert!(q1.qualifier == Some(Qualifier::Not), css.into_string()); assert!(q1.qualifier == Some(Qualifier::Not), css.to_owned());
assert!(q1.media_type == MediaQueryType::All, css.into_string()); assert!(q1.media_type == MediaQueryType::All, css.to_owned());
assert!(q1.expressions.len() == 0, css.into_string()); assert!(q1.expressions.len() == 0, css.to_owned());
}); });
} }

View file

@ -5,6 +5,7 @@
// This file is a Mako template: http://www.makotemplates.org/ // This file is a Mako template: http://www.makotemplates.org/
pub use std::ascii::AsciiExt; pub use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::fmt; use std::fmt;
use std::fmt::Show; use std::fmt::Show;
use std::sync::Arc; use std::sync::Arc;
@ -1025,6 +1026,7 @@ pub mod longhands {
<%self:longhand name="font-family"> <%self:longhand name="font-family">
pub use super::computed_as_specified as to_computed_value; pub use super::computed_as_specified as to_computed_value;
use std::borrow::ToOwned;
pub mod computed_value { pub mod computed_value {
use std::fmt; use std::fmt;
#[deriving(PartialEq, Eq, Clone)] #[deriving(PartialEq, Eq, Clone)]
@ -1065,7 +1067,7 @@ pub mod longhands {
#[inline] #[inline]
pub fn get_initial_value() -> computed_value::T { pub fn get_initial_value() -> computed_value::T {
vec![FontFamily::FamilyName("serif".into_string())] vec![FontFamily::FamilyName("serif".to_owned())]
} }
/// <familiy-name># /// <familiy-name>#
/// <familiy-name> = <string> | [ <ident>+ ] /// <familiy-name> = <string> | [ <ident>+ ]
@ -2647,7 +2649,7 @@ impl<T: Show> DeclaredValue<T> {
match self { match self {
&DeclaredValue::SpecifiedValue(ref inner) => Some(format!("{}", inner)), &DeclaredValue::SpecifiedValue(ref inner) => Some(format!("{}", inner)),
&DeclaredValue::Initial => None, &DeclaredValue::Initial => None,
&DeclaredValue::Inherit => Some("inherit".into_string()), &DeclaredValue::Inherit => Some("inherit".to_owned()),
} }
} }
} }
@ -2673,10 +2675,10 @@ impl PropertyDeclaration {
match self { match self {
% for property in LONGHANDS: % for property in LONGHANDS:
% if property.derived_from is None: % if property.derived_from is None:
&PropertyDeclaration::${property.camel_case}Declaration(..) => "${property.name}".into_string(), &PropertyDeclaration::${property.camel_case}Declaration(..) => "${property.name}".to_owned(),
% endif % endif
% endfor % endfor
_ => "".into_string(), _ => "".to_owned(),
} }
} }
@ -3391,7 +3393,7 @@ pub fn longhands_from_shorthand(shorthand: &str) -> Option<Vec<String>> {
% for property in SHORTHANDS: % for property in SHORTHANDS:
"${property.name}" => Some(vec!( "${property.name}" => Some(vec!(
% for sub in property.sub_properties: % for sub in property.sub_properties:
"${sub.name}".into_string(), "${sub.name}".to_owned(),
% endfor % endfor
)), )),
% endfor % endfor

View file

@ -11,6 +11,7 @@ use geom::scale_factor::ScaleFactor;
use geom::size::TypedSize2D; use geom::size::TypedSize2D;
use layers::geometry::DevicePixel; use layers::geometry::DevicePixel;
use getopts; use getopts;
use std::borrow::ToOwned;
use std::collections::HashSet; use std::collections::HashSet;
use std::cmp; use std::cmp;
use std::io; use std::io;
@ -302,7 +303,7 @@ pub fn from_cmdline_args(args: &[String]) -> bool {
} }
}; };
let render_api = match opt_match.opt_str("r").unwrap_or("gl".into_string()).as_slice() { let render_api = match opt_match.opt_str("r").unwrap_or("gl".to_owned()).as_slice() {
"mesa" => RenderApi::Mesa, "mesa" => RenderApi::Mesa,
"gl" => RenderApi::OpenGL, "gl" => RenderApi::OpenGL,
_ => { _ => {

View file

@ -4,6 +4,7 @@
use opts; use opts;
use std::any::Any; use std::any::Any;
use std::borrow::ToOwned;
#[cfg(not(test))] #[cfg(not(test))]
use std::io::File; use std::io::File;
//use std::mem; //use std::mem;
@ -83,7 +84,7 @@ pub fn instrument(f: proc()) {
let task = Local::borrow(None::<Task>); let task = Local::borrow(None::<Task>);
match task.name { match task.name {
Some(ref name) => name.to_string(), Some(ref name) => name.to_string(),
None => "unknown".into_string(), None => "unknown".to_owned(),
} }
}; };
let stats = TaskStats { let stats = TaskStats {

View file

@ -523,55 +523,56 @@ def_small_vector_clone_impl!(SmallVec32)
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use smallvec::{SmallVec, SmallVec2, SmallVec16}; use smallvec::{SmallVec, SmallVec2, SmallVec16};
use std::borrow::ToOwned;
// We heap allocate all these strings so that double frees will show up under valgrind. // We heap allocate all these strings so that double frees will show up under valgrind.
#[test] #[test]
pub fn test_inline() { pub fn test_inline() {
let mut v = SmallVec16::new(); let mut v = SmallVec16::new();
v.push("hello".into_string()); v.push("hello".to_owned());
v.push("there".into_string()); v.push("there".to_owned());
assert_eq!(v.as_slice(), vec![ assert_eq!(v.as_slice(), vec![
"hello".into_string(), "hello".to_owned(),
"there".into_string(), "there".to_owned(),
].as_slice()); ].as_slice());
} }
#[test] #[test]
pub fn test_spill() { pub fn test_spill() {
let mut v = SmallVec2::new(); let mut v = SmallVec2::new();
v.push("hello".into_string()); v.push("hello".to_owned());
v.push("there".into_string()); v.push("there".to_owned());
v.push("burma".into_string()); v.push("burma".to_owned());
v.push("shave".into_string()); v.push("shave".to_owned());
assert_eq!(v.as_slice(), vec![ assert_eq!(v.as_slice(), vec![
"hello".into_string(), "hello".to_owned(),
"there".into_string(), "there".to_owned(),
"burma".into_string(), "burma".to_owned(),
"shave".into_string(), "shave".to_owned(),
].as_slice()); ].as_slice());
} }
#[test] #[test]
pub fn test_double_spill() { pub fn test_double_spill() {
let mut v = SmallVec2::new(); let mut v = SmallVec2::new();
v.push("hello".into_string()); v.push("hello".to_owned());
v.push("there".into_string()); v.push("there".to_owned());
v.push("burma".into_string()); v.push("burma".to_owned());
v.push("shave".into_string()); v.push("shave".to_owned());
v.push("hello".into_string()); v.push("hello".to_owned());
v.push("there".into_string()); v.push("there".to_owned());
v.push("burma".into_string()); v.push("burma".to_owned());
v.push("shave".into_string()); v.push("shave".to_owned());
assert_eq!(v.as_slice(), vec![ assert_eq!(v.as_slice(), vec![
"hello".into_string(), "hello".to_owned(),
"there".into_string(), "there".to_owned(),
"burma".into_string(), "burma".to_owned(),
"shave".into_string(), "shave".to_owned(),
"hello".into_string(), "hello".to_owned(),
"there".into_string(), "there".to_owned(),
"burma".into_string(), "burma".to_owned(),
"shave".into_string(), "shave".to_owned(),
].as_slice()); ].as_slice());
} }
} }

View file

@ -6,6 +6,7 @@ use geometry::Au;
use cssparser::{mod, RGBA, Color}; use cssparser::{mod, RGBA, Color};
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::iter::Filter; use std::iter::Filter;
use std::num::Int; use std::num::Int;
use std::str::{CharEq, CharSplits, FromStr}; use std::str::{CharEq, CharSplits, FromStr};
@ -16,11 +17,11 @@ pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str]; pub type StaticStringVec = &'static [&'static str];
pub fn null_str_as_empty(s: &Option<DOMString>) -> DOMString { pub fn null_str_as_empty(s: &Option<DOMString>) -> DOMString {
// We don't use map_default because it would allocate "".into_string() even // We don't use map_default because it would allocate "".to_owned() even
// for Some. // for Some.
match *s { match *s {
Some(ref s) => s.clone(), Some(ref s) => s.clone(),
None => "".into_string() None => "".to_owned()
} }
} }

View file

@ -2,6 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::borrow::ToOwned;
use std::task; use std::task;
use std::comm::Sender; use std::comm::Sender;
use std::task::TaskBuilder; use std::task::TaskBuilder;
@ -29,7 +30,7 @@ pub fn spawn_named_with_send_on_failure<T: Send>(name: &'static str,
f(); f();
}); });
let watched_name = name.into_string(); let watched_name = name.to_owned();
let watcher_name = format!("{}Watcher", watched_name); let watcher_name = format!("{}Watcher", watched_name);
TaskBuilder::new().named(watcher_name).spawn(proc() { TaskBuilder::new().named(watcher_name).spawn(proc() {
//rtinstrument::instrument(proc() { //rtinstrument::instrument(proc() {

View file

@ -16,6 +16,7 @@ use compositing::windowing::{WindowNavigateMsg, WindowEvent};
use glutin_app; use glutin_app;
use libc::c_int; use libc::c_int;
use servo_util::opts; use servo_util::opts;
use std::borrow::ToOwned;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicInt, SeqCst}; use std::sync::atomic::{AtomicInt, SeqCst};
@ -204,7 +205,7 @@ fn browser_host_create(window_info: &cef_window_info_t,
callback_executed: bool) callback_executed: bool)
-> CefBrowser { -> CefBrowser {
let mut urls = Vec::new(); let mut urls = Vec::new();
urls.push("http://s27.postimg.org/vqbtrolyr/servo.jpg".into_string()); urls.push("http://s27.postimg.org/vqbtrolyr/servo.jpg".to_owned());
let mut opts = opts::default_opts(); let mut opts = opts::default_opts();
opts.urls = urls; opts.urls = urls;
let browser = ServoCefBrowser::new(window_info, client).as_cef_interface(); let browser = ServoCefBrowser::new(window_info, client).as_cef_interface();

View file

@ -12,6 +12,7 @@ use rustrt::local::Local;
use rustrt::task; use rustrt::task;
use servo_util::opts; use servo_util::opts;
use servo_util::opts::RenderApi; use servo_util::opts::RenderApi;
use std::borrow::ToOwned;
use std::c_str::CString; use std::c_str::CString;
use std::rt; use std::rt;
use browser; use browser;
@ -31,7 +32,7 @@ static CEF_API_HASH_PLATFORM: &'static [u8] = b"2bc564c3871965ef3a2531b528bda3e1
#[cfg(target_os="linux")] #[cfg(target_os="linux")]
fn resources_path() -> Option<String> { fn resources_path() -> Option<String> {
Some("../../servo/resources".into_string()) Some("../../servo/resources".to_owned())
} }
#[cfg(not(target_os="linux"))] #[cfg(not(target_os="linux"))]
@ -70,7 +71,7 @@ pub extern "C" fn cef_initialize(args: *const cef_main_args_t,
create_rust_task(); create_rust_task();
let urls = vec![HOME_URL.into_string()]; let urls = vec![HOME_URL.to_owned()];
opts::set_opts(opts::Opts { opts::set_opts(opts::Opts {
urls: urls, urls: urls,
n_paint_threads: 1, n_paint_threads: 1,