Upgrade Rust.

This commit is contained in:
Jack Moffitt 2014-06-01 00:21:53 -06:00
parent 2ae671b5aa
commit 629c4c6afe
148 changed files with 992 additions and 967 deletions

1
.gitignore vendored
View file

@ -19,6 +19,7 @@ objdir
parser.out parser.out
src/components/script/dom/bindings/codegen/*.rs src/components/script/dom/bindings/codegen/*.rs
src/components/script/dom/bindings/codegen/_cache/ src/components/script/dom/bindings/codegen/_cache/
src/components/script/dom/bindings/codegen/Bindings/
src/components/script/dom/bindings/codegen/test/*.rs src/components/script/dom/bindings/codegen/test/*.rs
src/components/script/dom/bindings/codegen/RegisterBindings.cpp src/components/script/dom/bindings/codegen/RegisterBindings.cpp
src/components/script/dom/bindings/codegen/PrototypeList.h src/components/script/dom/bindings/codegen/PrototypeList.h

View file

@ -51,6 +51,7 @@ export CFG_LOCAL_RUSTC
export CFG_ENABLE_DEBUG export CFG_ENABLE_DEBUG
export CFG_ENABLE_DEBUG_SKIA export CFG_ENABLE_DEBUG_SKIA
export RUSTC=$(CFG_RUSTC) export RUSTC=$(CFG_RUSTC)
export RUSTDOC=$(CFG_RUST_HOME)/bin/rustdoc
export RUSTFLAGS=$(CFG_RUSTC_FLAGS) export RUSTFLAGS=$(CFG_RUSTC_FLAGS)
export RANLIB=$(CFG_RANLIB) export RANLIB=$(CFG_RANLIB)
export PYTHON=$(CFG_PYTHON2) export PYTHON=$(CFG_PYTHON2)
@ -255,7 +256,7 @@ WEBIDLS_SRC = $(S)src/components/script/dom/webidls
WEBIDLS_script = $(call rwildcard, $(WEBIDLS_SRC), *.webidl) WEBIDLS_script = $(call rwildcard, $(WEBIDLS_SRC), *.webidl)
BINDINGS_script = $(patsubst %.webidl, %Binding.rs, $(WEBIDLS_script)) BINDINGS_script = $(patsubst %.webidl, %Binding.rs, $(WEBIDLS_script))
AUTOGEN_SRC_script = $(foreach var, $(BINDINGS_script), $(subst $(WEBIDLS_SRC), $(BINDINGS_SRC), $(var))) AUTOGEN_SRC_script = $(foreach var, $(BINDINGS_script), $(subst $(WEBIDLS_SRC), $(BINDINGS_SRC)/Bindings, $(var)))
SRC_script = $(call rwildcard,$(S)src/components/script/,*.rs) $(AUTOGEN_SRC_script) SRC_script = $(call rwildcard,$(S)src/components/script/,*.rs) $(AUTOGEN_SRC_script)
CRATE_script = $(S)src/components/script/script.rs CRATE_script = $(S)src/components/script/script.rs
@ -265,9 +266,9 @@ DEPS_script = $(CRATE_script) $(SRC_script) $(DONE_SUBMODULES) $(DONE_util) $(DO
RFLAGS_style = $(strip $(CFG_RUSTC_FLAGS)) $(addprefix -L $(B)src/,$(DEPS_SUBMODULES)) -L $(B)src/components/util -L$(B)src/components/macros RFLAGS_style = $(strip $(CFG_RUSTC_FLAGS)) $(addprefix -L $(B)src/,$(DEPS_SUBMODULES)) -L $(B)src/components/util -L$(B)src/components/macros
MAKO_ZIP = $(S)src/components/style/Mako-0.9.1.zip MAKO_ZIP = $(S)src/components/style/Mako-0.9.1.zip
MAKO_style = $(S)src/components/style/properties.rs MAKO_style = $(S)src/components/style/properties/mod.rs
MAKO_SRC_style = $(MAKO_style).mako MAKO_SRC_style = $(MAKO_style).mako
SRC_style = $(call rwildcard,$(S)src/components/style/,*.rs) $(MAKO_style) SRC_style = $(call rwildcard,$(S)src/components/style/,*.rs) $(call rwildcard,$(S)src/compontents/style/properties/*.rs) $(MAKO_style)
CRATE_style = $(S)src/components/style/style.rs CRATE_style = $(S)src/components/style/style.rs
DONE_style = $(B)src/components/style/libstyle.dummy DONE_style = $(B)src/components/style/libstyle.dummy
@ -303,25 +304,28 @@ $(eval $(call DEF_LIB_CRATE_RULES,$(lib_crate))))
CACHE_DIR = $(BINDINGS_SRC)/_cache CACHE_DIR = $(BINDINGS_SRC)/_cache
bindinggen_dependencies := $(addprefix $(BINDINGS_SRC)/, BindingGen.py Bindings.conf Configuration.py CodegenRust.py parser/WebIDL.py ParserResults.pkl) bindinggen_dependencies := $(addprefix $(BINDINGS_SRC)/, BindingGen.py Bindings.conf Configuration.py CodegenRust.py parser/WebIDL.py ParserResults.pkl Bindings/.done)
$(AUTOGEN_SRC_script): $(BINDINGS_SRC)/%Binding.rs: $(bindinggen_dependencies) \ $(AUTOGEN_SRC_script): $(BINDINGS_SRC)/Bindings/%Binding.rs: $(bindinggen_dependencies) \
$(addprefix $(WEBIDLS_SRC)/, %.webidl) $(addprefix $(WEBIDLS_SRC)/, %.webidl)
@$(call E, "Maybe generating $(shell basename $@)...") @$(call E, "Maybe generating $(shell basename $@)...")
$(Q) $(CFG_PYTHON2) $(BINDINGS_SRC)/pythonpath.py \ $(Q) $(CFG_PYTHON2) $(BINDINGS_SRC)/pythonpath.py \
-I$(BINDINGS_SRC)/parser -I$(BINDINGS_SRC)/ply \ -I$(BINDINGS_SRC)/parser -I$(BINDINGS_SRC)/ply \
-D$(BINDINGS_SRC) \ -D$(BINDINGS_SRC) \
$(BINDINGS_SRC)/BindingGen.py \ $(BINDINGS_SRC)/BindingGen.py \
$(BINDINGS_SRC)/Bindings.conf $*Binding $(addprefix $(WEBIDLS_SRC)/, $*.webidl) $(BINDINGS_SRC)/Bindings.conf Bindings/$*Binding $(addprefix $(WEBIDLS_SRC)/, $*.webidl)
$(Q)touch $@ $(Q)touch $@
globalgen_dependencies := $(addprefix $(BINDINGS_SRC)/, GlobalGen.py Bindings.conf Configuration.py CodegenRust.py parser/WebIDL.py) $(CACHE_DIR)/.done globalgen_dependencies := $(addprefix $(BINDINGS_SRC)/, GlobalGen.py Bindings.conf Configuration.py CodegenRust.py parser/WebIDL.py) $(CACHE_DIR)/.done $(BINDINGS_SRC)/Bindings/.done
$(MAKO_style): $(MAKO_SRC_style) $(MAKO_style): $(MAKO_SRC_style)
# Use a temporary file to avoid writing an empty (but more recent) file on failure. # Use a temporary file to avoid writing an empty (but more recent) file on failure.
PYTHONPATH=$(MAKO_ZIP) $(CFG_PYTHON2) -c "from mako.template import Template; print(Template(filename='$<').render())" > $@.tmp PYTHONPATH=$(MAKO_ZIP) $(CFG_PYTHON2) -c "from mako.template import Template; print(Template(filename='$<').render())" > $@.tmp
mv $@.tmp $@ mv $@.tmp $@
$(BINDINGS_SRC)/Bindings/.done:
mkdir -p $(BINDINGS_SRC)/Bindings
@touch $@
$(CACHE_DIR)/.done: $(CACHE_DIR)/.done:
mkdir -p $(CACHE_DIR) mkdir -p $(CACHE_DIR)

@ -1 +1 @@
Subproject commit aa6725407ae0a2cb88458e147e76adf8bcae0961 Subproject commit d35a38087088301aa58f244ae99d48b282df6fb2

View file

@ -1,4 +1,4 @@
# If this file is modified, then rust will be forcibly cleaned and then rebuilt. # If this file is modified, then rust will be forcibly cleaned and then rebuilt.
# The actual contents of this file do not matter, but to trigger a change on the # The actual contents of this file do not matter, but to trigger a change on the
# build bots then the contents should be changed so git updates the mtime. # build bots then the contents should be changed so git updates the mtime.
2014-05-08 2014-05-29

View file

@ -6,7 +6,6 @@ use libc::{calloc, c_int, size_t};
use std::mem; use std::mem;
use std::str; use std::str;
use std::c_vec::CVec; use std::c_vec::CVec;
use std::cast::transmute;
use string::{cef_string_userfree_utf16_alloc, cef_string_utf16_set}; use string::{cef_string_userfree_utf16_alloc, cef_string_utf16_set};
use types::{cef_command_line_t, cef_string_t, cef_string_userfree_t, cef_string_utf16_t}; use types::{cef_command_line_t, cef_string_t, cef_string_userfree_t, cef_string_utf16_t};
@ -14,7 +13,7 @@ type command_line_t = command_line;
struct command_line { struct command_line {
pub cl: cef_command_line_t, pub cl: cef_command_line_t,
pub argc: c_int, pub argc: c_int,
pub argv: Vec<~str>, pub argv: Vec<String>,
} }
static mut GLOBAL_CMDLINE: Option<*mut command_line_t> = None; static mut GLOBAL_CMDLINE: Option<*mut command_line_t> = None;
@ -29,7 +28,7 @@ fn command_line_new() -> *mut command_line_t {
pub fn command_line_init(argc: c_int, argv: **u8) { pub fn command_line_init(argc: c_int, argv: **u8) {
unsafe { unsafe {
let mut a: Vec<~str> = vec!(); let mut a: Vec<String> = vec!();
for i in range(0u, argc as uint) { for i in range(0u, argc as uint) {
a.push(str::raw::from_c_str(*argv.offset(i as int) as *i8)); a.push(str::raw::from_c_str(*argv.offset(i as int) as *i8));
} }
@ -49,18 +48,18 @@ pub extern "C" fn command_line_get_switch_value(cmd: *mut cef_command_line_t, na
unsafe { unsafe {
//technically cef_string_t can be any type of character size //technically cef_string_t can be any type of character size
//but the default cef callback uses utf16, so I'm jumping on board the SS Copy //but the default cef callback uses utf16, so I'm jumping on board the SS Copy
let cl: *mut command_line_t = transmute(cmd); let cl: *mut command_line_t = mem::transmute(cmd);
let cs: *cef_string_utf16_t = transmute(name); let cs: *cef_string_utf16_t = mem::transmute(name);
let opt = str::from_utf16(CVec::new((*cs).str, (*cs).length as uint).as_slice()).unwrap(); let opt = str::from_utf16(CVec::new((*cs).str, (*cs).length as uint).as_slice()).unwrap();
//debug!("opt: {}", opt); //debug!("opt: {}", opt);
for s in (*cl).argv.iter() { for s in (*cl).argv.iter() {
let o = s.trim_left_chars('-'); let o = s.as_slice().trim_left_chars('-');
//debug!("arg: {}", o); //debug!("arg: {}", o);
if o.starts_with(opt) { if o.as_slice().starts_with(opt.as_slice()) {
let string = cef_string_userfree_utf16_alloc() as *mut cef_string_utf16_t; let string = cef_string_userfree_utf16_alloc() as *mut cef_string_utf16_t;
let arg = o.slice_from(opt.len() + 1).as_bytes(); let arg = o.slice_from(opt.len() + 1).as_bytes();
arg.with_c_str(|c_str| { arg.with_c_str(|c_str| {
cef_string_utf16_set(transmute(c_str), arg.len() as u64, string, 1); cef_string_utf16_set(mem::transmute(c_str), arg.len() as u64, string, 1);
}); });
return string as *mut cef_string_userfree_t return string as *mut cef_string_userfree_t
} }
@ -74,7 +73,7 @@ pub extern "C" fn cef_command_line_create() -> *mut cef_command_line_t {
unsafe { unsafe {
let cl = command_line_new(); let cl = command_line_new();
(*cl).cl.get_switch_value = command_line_get_switch_value; (*cl).cl.get_switch_value = command_line_get_switch_value;
transmute(cl) mem::transmute(cl)
} }
} }
@ -83,7 +82,7 @@ pub extern "C" fn cef_command_line_get_global() -> *mut cef_command_line_t {
unsafe { unsafe {
match GLOBAL_CMDLINE { match GLOBAL_CMDLINE {
Some(scl) => { Some(scl) => {
transmute(scl) mem::transmute(scl)
}, },
None => { None => {
0 as *mut cef_command_line_t 0 as *mut cef_command_line_t

View file

@ -10,7 +10,7 @@ use libc::{c_int, c_void};
use native; use native;
use servo; use servo;
use servo_util::opts; use servo_util::opts;
use std::cast::transmute; use std::mem;
use types::{cef_app_t, cef_main_args_t, cef_settings_t}; use types::{cef_app_t, cef_main_args_t, cef_settings_t};
@ -23,11 +23,11 @@ pub extern "C" fn cef_initialize(args: *cef_main_args_t, settings: *mut cef_sett
unsafe { unsafe {
command_line_init((*args).argc, (*args).argv); command_line_init((*args).argc, (*args).argv);
let cb = (*application).get_browser_process_handler; let cb = (*application).get_browser_process_handler;
if !fptr_is_null(transmute(cb)) { if !fptr_is_null(mem::transmute(cb)) {
let handler = cb(application); let handler = cb(application);
if handler.is_not_null() { if handler.is_not_null() {
let hcb = (*handler).on_context_initialized; let hcb = (*handler).on_context_initialized;
if !fptr_is_null(transmute(hcb)) { if !fptr_is_null(mem::transmute(hcb)) {
hcb(handler); hcb(handler);
} }
} }
@ -43,7 +43,7 @@ pub extern "C" fn cef_shutdown() {
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_run_message_loop() { pub extern "C" fn cef_run_message_loop() {
let mut urls = Vec::new(); let mut urls = Vec::new();
urls.push("http://www.w3c-test.org".to_owned()); urls.push("http://www.w3c-test.org".to_string());
let opts = opts::Opts { let opts = opts::Opts {
urls: urls, urls: urls,
render_backend: azure::azure_hl::SkiaBackend, render_backend: azure::azure_hl::SkiaBackend,

View file

@ -7,7 +7,7 @@ use eutil::fptr_is_null;
use libc::{size_t, c_int, c_ushort,c_void}; use libc::{size_t, c_int, c_ushort,c_void};
use libc::types::os::arch::c95::wchar_t; use libc::types::os::arch::c95::wchar_t;
use mem::{new0,newarray0,delete,deletearray}; use mem::{new0,newarray0,delete,deletearray};
use std::cast::transmute; use std::mem;
use std::ptr; use std::ptr;
use types::{cef_string_utf16_t, cef_string_utf8_t, cef_string_wide_t}; use types::{cef_string_utf16_t, cef_string_utf8_t, cef_string_wide_t};
use types::{cef_string_userfree_utf16_t, cef_string_userfree_utf8_t, cef_string_userfree_wide_t}; use types::{cef_string_userfree_utf16_t, cef_string_userfree_utf8_t, cef_string_userfree_wide_t};
@ -50,13 +50,13 @@ pub extern "C" fn cef_string_userfree_utf16_free(cs: *mut cef_string_userfree_ut
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_string_utf8_clear(cs: *mut cef_string_utf8_t) { pub extern "C" fn cef_string_utf8_clear(cs: *mut cef_string_utf8_t) {
unsafe { unsafe {
if !fptr_is_null(transmute((*cs).dtor)) { if !fptr_is_null(mem::transmute((*cs).dtor)) {
let dtor = (*cs).dtor; let dtor = (*cs).dtor;
dtor((*cs).str); dtor((*cs).str);
} }
(*cs).length = 0; (*cs).length = 0;
(*cs).str = 0 as *mut u8; (*cs).str = 0 as *mut u8;
(*cs).dtor = transmute(0 as *u8); (*cs).dtor = mem::transmute(0 as *u8);
} }
} }
@ -82,9 +82,9 @@ pub extern "C" fn cef_string_utf8_set(src: *u8, src_len: size_t, output: *mut ce
(*output).dtor = string_utf8_dtor; (*output).dtor = string_utf8_dtor;
} }
} else { } else {
(*output).str = transmute(src); (*output).str = mem::transmute(src);
(*output).length = src_len; (*output).length = src_len;
(*output).dtor = transmute(0 as *u8); (*output).dtor = mem::transmute(0 as *u8);
} }
} }
return 1; return 1;
@ -93,13 +93,13 @@ pub extern "C" fn cef_string_utf8_set(src: *u8, src_len: size_t, output: *mut ce
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_string_utf16_clear(cs: *mut cef_string_utf16_t) { pub extern "C" fn cef_string_utf16_clear(cs: *mut cef_string_utf16_t) {
unsafe { unsafe {
if !fptr_is_null(transmute((*cs).dtor)) { if !fptr_is_null(mem::transmute((*cs).dtor)) {
let dtor = (*cs).dtor; let dtor = (*cs).dtor;
dtor((*cs).str); dtor((*cs).str);
} }
(*cs).length = 0; (*cs).length = 0;
(*cs).str = 0 as *mut c_ushort; (*cs).str = 0 as *mut c_ushort;
(*cs).dtor = transmute(0 as *u8); (*cs).dtor = mem::transmute(0 as *u8);
} }
} }
@ -125,9 +125,9 @@ pub extern "C" fn cef_string_utf16_set(src: *c_ushort, src_len: size_t, output:
(*output).dtor = string_utf16_dtor; (*output).dtor = string_utf16_dtor;
} }
} else { } else {
(*output).str = transmute(src); (*output).str = mem::transmute(src);
(*output).length = src_len; (*output).length = src_len;
(*output).dtor = transmute(0 as *u8); (*output).dtor = mem::transmute(0 as *u8);
} }
} }
return 1; return 1;
@ -136,13 +136,13 @@ pub extern "C" fn cef_string_utf16_set(src: *c_ushort, src_len: size_t, output:
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_string_wide_clear(cs: *mut cef_string_wide_t) { pub extern "C" fn cef_string_wide_clear(cs: *mut cef_string_wide_t) {
unsafe { unsafe {
if !fptr_is_null(transmute((*cs).dtor)) { if !fptr_is_null(mem::transmute((*cs).dtor)) {
let dtor = (*cs).dtor; let dtor = (*cs).dtor;
dtor((*cs).str); dtor((*cs).str);
} }
(*cs).length = 0; (*cs).length = 0;
(*cs).str = 0 as *mut wchar_t; (*cs).str = 0 as *mut wchar_t;
(*cs).dtor = transmute(0 as *u8); (*cs).dtor = mem::transmute(0 as *u8);
} }
} }
@ -168,9 +168,9 @@ pub extern "C" fn cef_string_wide_set(src: *wchar_t, src_len: size_t, output: *m
(*output).dtor = string_wide_dtor; (*output).dtor = string_wide_dtor;
} }
} else { } else {
(*output).str = transmute(src); (*output).str = mem::transmute(src);
(*output).length = src_len; (*output).length = src_len;
(*output).dtor = transmute(0 as *u8); (*output).dtor = mem::transmute(0 as *u8);
} }
} }
return 1; return 1;

View file

@ -631,7 +631,7 @@ impl DisplayItem {
} }
pub fn debug_with_level(&self, level: uint) { pub fn debug_with_level(&self, level: uint) {
let mut indent = StrBuf::new(); let mut indent = String::new();
for _ in range(0, level) { for _ in range(0, level) {
indent.push_str("| ") indent.push_str("| ")
} }
@ -644,7 +644,7 @@ impl DisplayItem {
impl fmt::Show for DisplayItem { impl fmt::Show for DisplayItem {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{} @ {} ({:x})", write!(f, "{} @ {} ({:x})",
match *self { match *self {
SolidColorDisplayItemClass(_) => "SolidColor", SolidColorDisplayItemClass(_) => "SolidColor",
TextDisplayItemClass(_) => "Text", TextDisplayItemClass(_) => "Text",

View file

@ -6,7 +6,7 @@ use azure::{AzFloat, AzScaledFontRef};
use azure::azure_hl::{BackendType, ColorPattern}; use azure::azure_hl::{BackendType, ColorPattern};
use azure::scaled_font::ScaledFont; use azure::scaled_font::ScaledFont;
use geom::{Point2D, Rect, Size2D}; use geom::{Point2D, Rect, Size2D};
use std::cast; use std::mem;
use std::num::Zero; use std::num::Zero;
use std::ptr; use std::ptr;
use std::str; use std::str;
@ -37,9 +37,9 @@ pub trait FontHandleMethods {
-> Result<Self,()>; -> Result<Self,()>;
// an identifier usable by FontContextHandle to recreate this FontHandle. // an identifier usable by FontContextHandle to recreate this FontHandle.
fn face_identifier(&self) -> ~str; fn face_identifier(&self) -> String;
fn family_name(&self) -> ~str; fn family_name(&self) -> String;
fn face_name(&self) -> ~str; fn face_name(&self) -> String;
fn is_italic(&self) -> bool; fn is_italic(&self) -> bool;
fn boldness(&self) -> font_weight::T; fn boldness(&self) -> font_weight::T;
@ -57,17 +57,17 @@ pub type FractionalPixel = f64;
pub type FontTableTag = u32; pub type FontTableTag = u32;
pub trait FontTableTagConversions { pub trait FontTableTagConversions {
fn tag_to_str(&self) -> ~str; fn tag_to_str(&self) -> String;
} }
impl FontTableTagConversions for FontTableTag { impl FontTableTagConversions for FontTableTag {
fn tag_to_str(&self) -> ~str { fn tag_to_str(&self) -> String {
unsafe { unsafe {
let reversed = str::raw::from_buf_len(cast::transmute(self), 4); let reversed = str::raw::from_buf_len(mem::transmute(self), 4);
return str::from_chars([reversed.char_at(3), return str::from_chars([reversed.as_slice().char_at(3),
reversed.char_at(2), reversed.as_slice().char_at(2),
reversed.char_at(1), reversed.as_slice().char_at(1),
reversed.char_at(0)]); reversed.as_slice().char_at(0)]);
} }
} }
} }
@ -101,7 +101,7 @@ pub struct FontStyle {
pub pt_size: f64, pub pt_size: f64,
pub weight: font_weight::T, pub weight: font_weight::T,
pub style: font_style::T, pub style: font_style::T,
pub families: Vec<~str>, pub families: Vec<String>,
// TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust // TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust
} }
@ -132,7 +132,7 @@ impl FontDescriptor {
// A FontSelector is a platform-specific strategy for serializing face names. // A FontSelector is a platform-specific strategy for serializing face names.
#[deriving(Clone, Eq)] #[deriving(Clone, Eq)]
pub enum FontSelector { pub enum FontSelector {
SelectorPlatformIdentifier(~str), SelectorPlatformIdentifier(String),
} }
// This struct is the result of mapping a specified FontStyle into the // This struct is the result of mapping a specified FontStyle into the
@ -143,7 +143,7 @@ pub enum FontSelector {
// The ordering of font instances is mainly decided by the CSS // The ordering of font instances is mainly decided by the CSS
// 'font-family' property. The last font is a system fallback font. // 'font-family' property. The last font is a system fallback font.
pub struct FontGroup { pub struct FontGroup {
pub families: Vec<~str>, pub families: Vec<String>,
// style of the first western font in group, which is // style of the first western font in group, which is
// used for purposes of calculating text run metrics. // used for purposes of calculating text run metrics.
pub style: UsedFontStyle, pub style: UsedFontStyle,
@ -151,7 +151,7 @@ pub struct FontGroup {
} }
impl FontGroup { impl FontGroup {
pub fn new(families: Vec<~str>, style: &UsedFontStyle, fonts: Vec<Rc<RefCell<Font>>>) -> FontGroup { pub fn new(families: Vec<String>, style: &UsedFontStyle, fonts: Vec<Rc<RefCell<Font>>>) -> FontGroup {
FontGroup { FontGroup {
families: families, families: families,
style: (*style).clone(), style: (*style).clone(),
@ -159,7 +159,7 @@ impl FontGroup {
} }
} }
pub fn create_textrun(&self, text: ~str, decoration: text_decoration::T) -> TextRun { pub fn create_textrun(&self, text: String, decoration: text_decoration::T) -> TextRun {
assert!(self.fonts.len() > 0); assert!(self.fonts.len() > 0);
// TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable.
@ -206,7 +206,7 @@ pub struct Font {
pub style: UsedFontStyle, pub style: UsedFontStyle,
pub metrics: FontMetrics, pub metrics: FontMetrics,
pub backend: BackendType, pub backend: BackendType,
pub shape_cache: HashCache<~str, Arc<GlyphStore>>, pub shape_cache: HashCache<String, Arc<GlyphStore>>,
pub glyph_advance_cache: HashCache<u32, FractionalPixel>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>,
} }
@ -285,7 +285,7 @@ impl<'a> Font {
let result = self.handle.get_table_for_tag(tag); let result = self.handle.get_table_for_tag(tag);
let status = if result.is_some() { "Found" } else { "Didn't find" }; let status = if result.is_some() { "Found" } else { "Didn't find" };
debug!("{:s} font table[{:s}] with family={:s}, face={:s}", debug!("{:s} font table[{:s}] with family={}, face={}",
status, tag.tag_to_str(), status, tag.tag_to_str(),
self.handle.family_name(), self.handle.face_name()); self.handle.family_name(), self.handle.face_name());
@ -413,14 +413,14 @@ impl Font {
RunMetrics::new(advance, self.metrics.ascent, self.metrics.descent) RunMetrics::new(advance, self.metrics.ascent, self.metrics.descent)
} }
pub fn shape_text(&mut self, text: ~str, is_whitespace: bool) -> Arc<GlyphStore> { pub fn shape_text(&mut self, text: String, is_whitespace: bool) -> Arc<GlyphStore> {
//FIXME (ksh8281) //FIXME (ksh8281)
self.make_shaper(); self.make_shaper();
let shaper = &self.shaper; let shaper = &self.shaper;
self.shape_cache.find_or_create(&text, |txt| { self.shape_cache.find_or_create(&text, |txt| {
let mut glyphs = GlyphStore::new(text.char_len() as int, is_whitespace); let mut glyphs = GlyphStore::new(text.as_slice().char_len() as int, is_whitespace);
shaper.get_ref().shape_text(*txt, &mut glyphs); shaper.get_ref().shape_text(txt.as_slice(), &mut glyphs);
Arc::new(glyphs) Arc::new(glyphs)
}) })
} }

View file

@ -30,7 +30,7 @@ pub struct FontContextInfo {
} }
pub trait FontContextHandleMethods { pub trait FontContextHandleMethods {
fn create_font_from_identifier(&self, ~str, UsedFontStyle) -> Result<FontHandle, ()>; fn create_font_from_identifier(&self, String, UsedFontStyle) -> Result<FontHandle, ()>;
} }
pub struct FontContext { pub struct FontContext {
@ -39,7 +39,7 @@ pub struct FontContext {
pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>, pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>,
pub handle: FontContextHandle, pub handle: FontContextHandle,
pub backend: BackendType, pub backend: BackendType,
pub generic_fonts: HashMap<~str,~str>, pub generic_fonts: HashMap<String,String>,
pub profiler_chan: ProfilerChan, pub profiler_chan: ProfilerChan,
} }
@ -54,11 +54,11 @@ impl FontContext {
// TODO: Allow users to specify these. // TODO: Allow users to specify these.
let mut generic_fonts = HashMap::with_capacity(5); let mut generic_fonts = HashMap::with_capacity(5);
generic_fonts.insert("serif".to_owned(), "Times New Roman".to_owned()); generic_fonts.insert("serif".to_string(), "Times New Roman".to_string());
generic_fonts.insert("sans-serif".to_owned(), "Arial".to_owned()); generic_fonts.insert("sans-serif".to_string(), "Arial".to_string());
generic_fonts.insert("cursive".to_owned(), "Apple Chancery".to_owned()); generic_fonts.insert("cursive".to_string(), "Apple Chancery".to_string());
generic_fonts.insert("fantasy".to_owned(), "Papyrus".to_owned()); generic_fonts.insert("fantasy".to_string(), "Papyrus".to_string());
generic_fonts.insert("monospace".to_owned(), "Menlo".to_owned()); generic_fonts.insert("monospace".to_string(), "Menlo".to_string());
FontContext { FontContext {
instance_cache: LRUCache::new(10), instance_cache: LRUCache::new(10),
@ -107,10 +107,10 @@ impl FontContext {
} }
} }
fn transform_family(&self, family: &~str) -> ~str { fn transform_family(&self, family: &String) -> String {
debug!("(transform family) searching for `{:s}`", family.as_slice()); debug!("(transform family) searching for `{:s}`", family.as_slice());
match self.generic_fonts.find(family) { match self.generic_fonts.find(family) {
None => family.to_owned(), None => family.to_string(),
Some(mapped_family) => (*mapped_family).clone() Some(mapped_family) => (*mapped_family).clone()
} }
} }

View file

@ -13,12 +13,12 @@ use style::computed_values::{font_weight, font_style};
use servo_util::time::{ProfilerChan, profile}; use servo_util::time::{ProfilerChan, profile};
use servo_util::time; use servo_util::time;
pub type FontFamilyMap = HashMap<~str, FontFamily>; pub type FontFamilyMap = HashMap<String, FontFamily>;
trait FontListHandleMethods { trait FontListHandleMethods {
fn get_available_families(&self, fctx: &FontContextHandle) -> FontFamilyMap; fn get_available_families(&self, fctx: &FontContextHandle) -> FontFamilyMap;
fn load_variations_for_family(&self, family: &mut FontFamily); fn load_variations_for_family(&self, family: &mut FontFamily);
fn get_last_resort_font_families() -> Vec<~str>; fn get_last_resort_font_families() -> Vec<String>;
} }
/// The platform-independent font list abstraction. /// The platform-independent font list abstraction.
@ -53,7 +53,7 @@ impl FontList {
} }
pub fn find_font_in_family<'a>(&'a mut self, pub fn find_font_in_family<'a>(&'a mut self,
family_name: &~str, family_name: &String,
style: &SpecifiedFontStyle) -> Option<&'a FontEntry> { style: &SpecifiedFontStyle) -> Option<&'a FontEntry> {
// TODO(Issue #188): look up localized font family names if canonical name not found // TODO(Issue #188): look up localized font family names if canonical name not found
// look up canonical name // look up canonical name
@ -75,14 +75,14 @@ impl FontList {
} }
} }
pub fn get_last_resort_font_families() -> Vec<~str> { pub fn get_last_resort_font_families() -> Vec<String> {
FontListHandle::get_last_resort_font_families() FontListHandle::get_last_resort_font_families()
} }
} }
// Holds a specific font family, and the various // Holds a specific font family, and the various
pub struct FontFamily { pub struct FontFamily {
pub family_name: ~str, pub family_name: String,
pub entries: Vec<FontEntry>, pub entries: Vec<FontEntry>,
} }
@ -130,7 +130,7 @@ impl FontFamily {
/// In the common case, each FontFamily will have a singleton FontEntry, or it will have the /// In the common case, each FontFamily will have a singleton FontEntry, or it will have the
/// standard four faces: Normal, Bold, Italic, BoldItalic. /// standard four faces: Normal, Bold, Italic, BoldItalic.
pub struct FontEntry { pub struct FontEntry {
pub face_name: ~str, pub face_name: String,
weight: font_weight::T, weight: font_weight::T,
italic: bool, italic: bool,
pub handle: FontHandle, pub handle: FontHandle,

View file

@ -13,6 +13,7 @@
#[phase(syntax, link)] #[phase(syntax, link)]
extern crate log; extern crate log;
extern crate debug;
extern crate azure; extern crate azure;
extern crate collections; extern crate collections;
extern crate geom; extern crate geom;
@ -48,6 +49,8 @@ pub use gfx_font_list = font_list;
pub use servo_gfx_font = font; pub use servo_gfx_font = font;
pub use servo_gfx_font_list = font_list; pub use servo_gfx_font_list = font_list;
pub use render_context::RenderContext;
// Private rendering modules // Private rendering modules
mod render_context; mod render_context;

View file

@ -24,7 +24,7 @@ use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics};
use freetype::freetype::{ft_sfnt_os2}; use freetype::freetype::{ft_sfnt_os2};
use freetype::tt_os2::TT_OS2; use freetype::tt_os2::TT_OS2;
use std::cast; use std::mem;
use std::ptr; use std::ptr;
use std::str; use std::str;
@ -48,7 +48,7 @@ impl FontTableMethods for FontTable {
pub enum FontSource { pub enum FontSource {
FontSourceMem(Vec<u8>), FontSourceMem(Vec<u8>),
FontSourceFile(~str) FontSourceFile(String)
} }
pub struct FontHandle { pub struct FontHandle {
@ -117,15 +117,15 @@ impl FontHandleMethods for FontHandle {
} }
// an identifier usable by FontContextHandle to recreate this FontHandle. // an identifier usable by FontContextHandle to recreate this FontHandle.
fn face_identifier(&self) -> ~str { fn face_identifier(&self) -> String {
/* FT_Get_Postscript_Name seems like a better choice here, but it /* FT_Get_Postscript_Name seems like a better choice here, but it
doesn't give usable results for fontconfig when deserializing. */ doesn't give usable results for fontconfig when deserializing. */
unsafe { str::raw::from_c_str((*self.face).family_name) } unsafe { str::raw::from_c_str((*self.face).family_name) }
} }
fn family_name(&self) -> ~str { fn family_name(&self) -> String {
unsafe { str::raw::from_c_str((*self.face).family_name) } unsafe { str::raw::from_c_str((*self.face).family_name) }
} }
fn face_name(&self) -> ~str { fn face_name(&self) -> String {
unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) }
} }
fn is_italic(&self) -> bool { fn is_italic(&self) -> bool {
@ -168,7 +168,7 @@ impl FontHandleMethods for FontHandle {
FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) FontHandleMethods::new_from_buffer(fctx, buf.clone(), style)
} }
FontSourceFile(ref file) => { FontSourceFile(ref file) => {
FontHandle::new_from_file(fctx, (*file).clone(), style) FontHandle::new_from_file(fctx, file.as_slice(), style)
} }
} }
} }
@ -194,7 +194,7 @@ impl FontHandleMethods for FontHandle {
let res = FT_Load_Glyph(self.face, glyph as FT_UInt, 0); let res = FT_Load_Glyph(self.face, glyph as FT_UInt, 0);
if res.succeeded() { if res.succeeded() {
let void_glyph = (*self.face).glyph; let void_glyph = (*self.face).glyph;
let slot: FT_GlyphSlot = cast::transmute(void_glyph); let slot: FT_GlyphSlot = mem::transmute(void_glyph);
assert!(slot.is_not_null()); assert!(slot.is_not_null());
debug!("metrics: {:?}", (*slot).metrics); debug!("metrics: {:?}", (*slot).metrics);
let advance = (*slot).metrics.horiAdvance; let advance = (*slot).metrics.horiAdvance;
@ -303,7 +303,7 @@ impl<'a> FontHandle {
} }
} }
pub fn new_from_file_unstyled(fctx: &FontContextHandle, file: ~str) pub fn new_from_file_unstyled(fctx: &FontContextHandle, file: String)
-> Result<FontHandle, ()> { -> Result<FontHandle, ()> {
unsafe { unsafe {
let ft_ctx: FT_Library = fctx.ctx.ctx; let ft_ctx: FT_Library = fctx.ctx.ctx;
@ -338,7 +338,7 @@ impl<'a> FontHandle {
// face.size is a *c_void in the bindings, presumably to avoid // face.size is a *c_void in the bindings, presumably to avoid
// recursive structural types // recursive structural types
let size: &FT_SizeRec = unsafe { cast::transmute(&(*face.size)) }; let size: &FT_SizeRec = unsafe { mem::transmute(&(*face.size)) };
let metrics: &FT_Size_Metrics = &(*size).metrics; let metrics: &FT_Size_Metrics = &(*size).metrics;
let em_size = face.units_per_EM as f64; let em_size = face.units_per_EM as f64;

View file

@ -44,12 +44,12 @@ impl FontContextHandle {
} }
impl FontContextHandleMethods for FontContextHandle { impl FontContextHandleMethods for FontContextHandle {
fn create_font_from_identifier(&self, name: ~str, style: UsedFontStyle) fn create_font_from_identifier(&self, name: String, style: UsedFontStyle)
-> Result<FontHandle, ()> { -> Result<FontHandle, ()> {
debug!("Creating font handle for {:s}", name); debug!("Creating font handle for {:s}", name);
path_from_identifier(name, &style).and_then(|file_name| { path_from_identifier(name, &style).and_then(|file_name| {
debug!("Opening font face {:s}", file_name); debug!("Opening font face {:s}", file_name);
FontHandle::new_from_file(self, file_name.to_owned(), &style) FontHandle::new_from_file(self, file_name.as_slice(), &style)
}) })
} }
} }

View file

@ -55,7 +55,7 @@ impl FontListHandle {
while FcPatternGetString(*font, FC_FAMILY, v, &family) == FcResultMatch { while FcPatternGetString(*font, FC_FAMILY, v, &family) == FcResultMatch {
let family_name = str::raw::from_c_str(family as *c_char); let family_name = str::raw::from_c_str(family as *c_char);
debug!("Creating new FontFamily for family: {:s}", family_name); debug!("Creating new FontFamily for family: {:s}", family_name);
let new_family = FontFamily::new(family_name); let new_family = FontFamily::new(family_name.as_slice());
family_map.insert(family_name, new_family); family_map.insert(family_name, new_family);
v += 1; v += 1;
} }
@ -131,8 +131,8 @@ impl FontListHandle {
} }
} }
pub fn get_last_resort_font_families() -> Vec<~str> { pub fn get_last_resort_font_families() -> Vec<String> {
vec!("Arial".to_owned()) vec!("Arial".to_string())
} }
} }
@ -148,7 +148,7 @@ impl Drop for AutoPattern {
} }
} }
pub fn path_from_identifier(name: ~str, style: &UsedFontStyle) -> Result<~str, ()> { pub fn path_from_identifier(name: String, style: &UsedFontStyle) -> Result<String, ()> {
unsafe { unsafe {
let config = FcConfigGetCurrent(); let config = FcConfigGetCurrent();
let wrapper = AutoPattern { pattern: FcPatternCreate() }; let wrapper = AutoPattern { pattern: FcPatternCreate() };

View file

@ -91,11 +91,11 @@ impl FontHandleMethods for FontHandle {
return result; return result;
} }
fn family_name(&self) -> ~str { fn family_name(&self) -> String {
self.ctfont.family_name() self.ctfont.family_name()
} }
fn face_name(&self) -> ~str { fn face_name(&self) -> String {
self.ctfont.face_name() self.ctfont.face_name()
} }
@ -189,7 +189,7 @@ impl FontHandleMethods for FontHandle {
}) })
} }
fn face_identifier(&self) -> ~str { fn face_identifier(&self) -> String {
self.ctfont.postscript_name() self.ctfont.postscript_name()
} }
} }

View file

@ -23,10 +23,10 @@ impl FontContextHandle {
impl FontContextHandleMethods for FontContextHandle { impl FontContextHandleMethods for FontContextHandle {
fn create_font_from_identifier(&self, fn create_font_from_identifier(&self,
name: ~str, name: String,
style: UsedFontStyle) style: UsedFontStyle)
-> Result<FontHandle, ()> { -> Result<FontHandle, ()> {
let ctfont_result = core_text::font::new_from_name(name, style.pt_size); let ctfont_result = core_text::font::new_from_name(name.as_slice(), style.pt_size);
ctfont_result.and_then(|ctfont| { ctfont_result.and_then(|ctfont| {
FontHandle::new_from_CTFont(self, ctfont) FontHandle::new_from_CTFont(self, ctfont)
}) })

View file

@ -12,7 +12,7 @@ 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::cast; use std::mem;
pub struct FontListHandle { pub struct FontListHandle {
fctx: FontContextHandle, fctx: FontContextHandle,
@ -29,12 +29,12 @@ impl FontListHandle {
let family_names = core_text::font_collection::get_family_names(); let family_names = core_text::font_collection::get_family_names();
let mut family_map: FontFamilyMap = HashMap::new(); let mut family_map: FontFamilyMap = HashMap::new();
for strref in family_names.iter() { for strref in family_names.iter() {
let family_name_ref: CFStringRef = unsafe { cast::transmute(strref) }; let family_name_ref: CFStringRef = unsafe { mem::transmute(strref) };
let family_name_cf: CFString = unsafe { TCFType::wrap_under_get_rule(family_name_ref) }; let family_name_cf: CFString = unsafe { TCFType::wrap_under_get_rule(family_name_ref) };
let family_name = family_name_cf.to_str(); let family_name = family_name_cf.to_str();
debug!("Creating new FontFamily for family: {:s}", family_name); debug!("Creating new FontFamily for family: {:s}", family_name);
let new_family = FontFamily::new(family_name); let new_family = FontFamily::new(family_name.as_slice());
family_map.insert(family_name, new_family); family_map.insert(family_name, new_family);
} }
family_map family_map
@ -44,10 +44,10 @@ impl FontListHandle {
debug!("Looking for faces of family: {:s}", family.family_name); debug!("Looking for faces of family: {:s}", family.family_name);
let family_collection = let family_collection =
core_text::font_collection::create_for_family(family.family_name); core_text::font_collection::create_for_family(family.family_name.as_slice());
let family_descriptors = family_collection.get_descriptors(); let family_descriptors = family_collection.get_descriptors();
for descref in family_descriptors.iter() { for descref in family_descriptors.iter() {
let descref: CTFontDescriptorRef = unsafe { cast::transmute(descref) }; let descref: CTFontDescriptorRef = unsafe { mem::transmute(descref) };
let desc: CTFontDescriptor = unsafe { TCFType::wrap_under_get_rule(descref) }; let desc: CTFontDescriptor = unsafe { TCFType::wrap_under_get_rule(descref) };
let font = core_text::font::new_from_descriptor(&desc, 0.0); let font = core_text::font::new_from_descriptor(&desc, 0.0);
let handle = FontHandle::new_from_CTFont(&self.fctx, font).unwrap(); let handle = FontHandle::new_from_CTFont(&self.fctx, font).unwrap();
@ -58,7 +58,7 @@ impl FontListHandle {
} }
} }
pub fn get_last_resort_font_families() -> Vec<~str> { pub fn get_last_resort_font_families() -> Vec<String> {
vec!("Arial Unicode MS".to_owned(), "Arial".to_owned()) vec!("Arial Unicode MS".to_string(), "Arial".to_string())
} }
} }

View file

@ -38,7 +38,7 @@ use harfbuzz::{hb_shape, hb_buffer_get_glyph_infos};
use libc::{c_uint, c_int, c_void, c_char}; use libc::{c_uint, c_int, c_void, c_char};
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::range::Range; use servo_util::range::Range;
use std::cast::transmute; use std::mem;
use std::char; use std::char;
use std::cmp; use std::cmp;
use std::ptr::null; use std::ptr::null;
@ -507,7 +507,7 @@ extern fn get_font_table_func(_: *hb_face_t, tag: hb_tag_t, user_data: *c_void)
blob = hb_blob_create(buf as *c_char, blob = hb_blob_create(buf as *c_char,
len as c_uint, len as c_uint,
HB_MEMORY_MODE_READONLY, HB_MEMORY_MODE_READONLY,
transmute(skinny_font_table_ptr), mem::transmute(skinny_font_table_ptr),
destroy_blob_func); destroy_blob_func);
}); });

View file

@ -13,7 +13,7 @@ use text::glyph::{CharIndex, GlyphStore};
/// A text run. /// A text run.
#[deriving(Clone)] #[deriving(Clone)]
pub struct TextRun { pub struct TextRun {
pub text: Arc<~str>, pub text: Arc<String>,
pub font_descriptor: FontDescriptor, pub font_descriptor: FontDescriptor,
pub font_metrics: FontMetrics, pub font_metrics: FontMetrics,
pub font_style: FontStyle, pub font_style: FontStyle,
@ -97,8 +97,8 @@ impl<'a> Iterator<Range<CharIndex>> for LineIterator<'a> {
} }
impl<'a> TextRun { impl<'a> TextRun {
pub fn new(font: &mut Font, text: ~str, decoration: text_decoration::T) -> TextRun { pub fn new(font: &mut Font, text: String, decoration: text_decoration::T) -> TextRun {
let glyphs = TextRun::break_and_shape(font, text); let glyphs = TextRun::break_and_shape(font, text.as_slice());
let run = TextRun { let run = TextRun {
text: Arc::new(text), text: Arc::new(text),
@ -145,7 +145,7 @@ impl<'a> TextRun {
// Create a glyph store for this slice if it's nonempty. // Create a glyph store for this slice if it's nonempty.
if can_break_before && byte_i > byte_last_boundary { if can_break_before && byte_i > byte_last_boundary {
let slice = text.slice(byte_last_boundary, byte_i).to_owned(); let slice = text.slice(byte_last_boundary, byte_i).to_string();
debug!("creating glyph store for slice {} (ws? {}), {} - {} in run {}", debug!("creating glyph store for slice {} (ws? {}), {} - {} in run {}",
slice, !cur_slice_is_whitespace, byte_last_boundary, byte_i, text); slice, !cur_slice_is_whitespace, byte_last_boundary, byte_i, text);
glyphs.push(font.shape_text(slice, !cur_slice_is_whitespace)); glyphs.push(font.shape_text(slice, !cur_slice_is_whitespace));
@ -157,7 +157,7 @@ impl<'a> TextRun {
// Create a glyph store for the final slice if it's nonempty. // Create a glyph store for the final slice if it's nonempty.
if byte_i > byte_last_boundary { if byte_i > byte_last_boundary {
let slice = text.slice_from(byte_last_boundary).to_owned(); let slice = text.slice_from(byte_last_boundary).to_string();
debug!("creating glyph store for final slice {} (ws? {}), {} - {} in run {}", debug!("creating glyph store for final slice {} (ws? {}), {} - {} in run {}",
slice, cur_slice_is_whitespace, byte_last_boundary, text.len(), text); slice, cur_slice_is_whitespace, byte_last_boundary, text.len(), text);
glyphs.push(font.shape_text(slice, cur_slice_is_whitespace)); glyphs.push(font.shape_text(slice, cur_slice_is_whitespace));

View file

@ -24,8 +24,8 @@ pub enum CompressionMode {
// * Untracked: various edge cases for bidi, CJK, etc. // * Untracked: various edge cases for bidi, CJK, etc.
pub fn transform_text(text: &str, mode: CompressionMode, pub fn transform_text(text: &str, mode: CompressionMode,
incoming_whitespace: bool, incoming_whitespace: bool,
new_line_pos: &mut Vec<CharIndex>) -> (~str, bool) { new_line_pos: &mut Vec<CharIndex>) -> (String, bool) {
let mut out_str = StrBuf::new(); let mut out_str = String::new();
let out_whitespace = match mode { let out_whitespace = match mode {
CompressNone | DiscardNewline => { CompressNone | DiscardNewline => {
let mut new_line_index = CharIndex(0); let mut new_line_index = CharIndex(0);
@ -195,7 +195,7 @@ fn test_transform_discard_newline() {
/* FIXME: Fix and re-enable /* FIXME: Fix and re-enable
#[test] #[test]
fn test_transform_compress_whitespace() { fn test_transform_compress_whitespace() {
let test_strs : ~[~str] = ~[" foo bar".to_owned(), let test_strs : ~[String] = ~[" foo bar".to_owned(),
"foo bar ".to_owned(), "foo bar ".to_owned(),
"foo\n bar".to_owned(), "foo\n bar".to_owned(),
"foo \nbar".to_owned(), "foo \nbar".to_owned(),
@ -203,7 +203,7 @@ fn test_transform_compress_whitespace() {
"foo bar baz".to_owned(), "foo bar baz".to_owned(),
"foobarbaz\n\n".to_owned()]; "foobarbaz\n\n".to_owned()];
let oracle_strs : ~[~str] = ~[" foo bar".to_owned(), let oracle_strs : ~[String] = ~[" foo bar".to_owned(),
"foo bar ".to_owned(), "foo bar ".to_owned(),
"foo\n bar".to_owned(), "foo\n bar".to_owned(),
"foo \nbar".to_owned(), "foo \nbar".to_owned(),
@ -223,7 +223,7 @@ fn test_transform_compress_whitespace() {
#[test] #[test]
fn test_transform_compress_whitespace_newline() { fn test_transform_compress_whitespace_newline() {
let test_strs : ~[~str] = ~[" foo bar".to_owned(), let test_strs : ~[String] = ~[" foo bar".to_owned(),
"foo bar ".to_owned(), "foo bar ".to_owned(),
"foo\n bar".to_owned(), "foo\n bar".to_owned(),
"foo \nbar".to_owned(), "foo \nbar".to_owned(),
@ -231,7 +231,7 @@ fn test_transform_compress_whitespace_newline() {
"foo bar baz".to_owned(), "foo bar baz".to_owned(),
"foobarbaz\n\n".to_owned()]; "foobarbaz\n\n".to_owned()];
let oracle_strs : ~[~str] = ~["foo bar".to_owned(), let oracle_strs : ~[String] = ~["foo bar".to_owned(),
"foo bar ".to_owned(), "foo bar ".to_owned(),
"foo bar".to_owned(), "foo bar".to_owned(),
"foo bar".to_owned(), "foo bar".to_owned(),

View file

@ -47,7 +47,7 @@ macro_rules! lazy_init(
static mut s: *$T = 0 as *$T; static mut s: *$T = 0 as *$T;
static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT; static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT;
ONCE.doit(|| { ONCE.doit(|| {
s = ::std::cast::transmute::<Box<$T>, *$T>(box () ($e)); s = ::std::mem::transmute::<Box<$T>, *$T>(box () ($e));
}); });
&*s &*s
} }
@ -66,7 +66,7 @@ mod tests {
lazy_init! { lazy_init! {
static ref NUMBER: uint = times_two(3); static ref NUMBER: uint = times_two(3);
static ref VEC: [Box<uint>, ..3] = [box 1, box 2, box 3]; static ref VEC: [Box<uint>, ..3] = [box 1, box 2, box 3];
static ref OWNED_STRING: ~str = "hello".to_owned(); static ref OWNED_STRING: String = "hello".to_string();
static ref HASHMAP: collections::HashMap<uint, &'static str> = { static ref HASHMAP: collections::HashMap<uint, &'static str> = {
let mut m = collections::HashMap::new(); let mut m = collections::HashMap::new();
m.insert(0u, "abc"); m.insert(0u, "abc");
@ -82,7 +82,7 @@ mod tests {
#[test] #[test]
fn test_basic() { fn test_basic() {
assert_eq!(*OWNED_STRING, "hello".to_owned()); assert_eq!(*OWNED_STRING, "hello".to_string());
assert_eq!(*NUMBER, 6); assert_eq!(*NUMBER, 6);
assert!(HASHMAP.find(&1).is_some()); assert!(HASHMAP.find(&1).is_some());
assert!(HASHMAP.find(&3).is_none()); assert!(HASHMAP.find(&3).is_none());

View file

@ -592,7 +592,7 @@ impl IOCompositor {
} }
} }
fn on_load_url_window_event(&mut self, url_string: ~str) { fn on_load_url_window_event(&mut self, url_string: String) {
debug!("osmain: loading URL `{:s}`", url_string); debug!("osmain: loading URL `{:s}`", url_string);
self.load_complete = false; self.load_complete = false;
let root_pipeline_id = match self.compositor_layer { let root_pipeline_id = match self.compositor_layer {
@ -600,7 +600,7 @@ impl IOCompositor {
None => fail!("Compositor: Received LoadUrlWindowEvent without initialized compositor layers"), None => fail!("Compositor: Received LoadUrlWindowEvent without initialized compositor layers"),
}; };
let msg = LoadUrlMsg(root_pipeline_id, url::parse_url(url_string, None)); let msg = LoadUrlMsg(root_pipeline_id, url::parse_url(url_string.as_slice(), None));
let ConstellationChan(ref chan) = self.constellation_chan; let ConstellationChan(ref chan) = self.constellation_chan;
chan.send(msg); chan.send(msg);
} }
@ -718,7 +718,7 @@ impl IOCompositor {
if self.load_complete && self.ready_state == FinishedLoading if self.load_complete && self.ready_state == FinishedLoading
&& self.opts.output_file.is_some() { && self.opts.output_file.is_some() {
let (width, height) = (self.window_size.width as uint, self.window_size.height as uint); let (width, height) = (self.window_size.width as uint, self.window_size.height as uint);
let path = from_str::<Path>(*self.opts.output_file.get_ref()).unwrap(); let path = from_str::<Path>(self.opts.output_file.get_ref().as_slice()).unwrap();
let mut pixels = gl2::read_pixels(0, 0, let mut pixels = gl2::read_pixels(0, 0,
width as gl2::GLsizei, width as gl2::GLsizei,
height as gl2::GLsizei, height as gl2::GLsizei,

View file

@ -342,12 +342,12 @@ impl CompositorLayer {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn dump_layer_tree(&self, layer: Rc<ContainerLayer>, indent: ~str) { fn dump_layer_tree(&self, layer: Rc<ContainerLayer>, indent: String) {
println!("{}scissor {:?}", indent, layer.scissor.borrow()); println!("{}scissor {:?}", indent, layer.scissor.borrow());
for kid in layer.children() { for kid in layer.children() {
match kid { match kid {
ContainerLayerKind(ref container_layer) => { ContainerLayerKind(ref container_layer) => {
self.dump_layer_tree((*container_layer).clone(), indent + " "); self.dump_layer_tree((*container_layer).clone(), format!("{} ", indent));
} }
TextureLayerKind(_) => { TextureLayerKind(_) => {
println!("{} (texture layer)", indent); println!("{} (texture layer)", indent);
@ -406,13 +406,13 @@ impl CompositorLayer {
MouseWindowMouseUpEvent(button, _) => MouseUpEvent(button, cursor), MouseWindowMouseUpEvent(button, _) => MouseUpEvent(button, cursor),
}; };
let ScriptChan(ref chan) = self.pipeline.script_chan; let ScriptChan(ref chan) = self.pipeline.script_chan;
chan.send_opt(SendEventMsg(self.pipeline.id.clone(), message)); let _ = chan.send_opt(SendEventMsg(self.pipeline.id.clone(), message));
} }
pub fn send_mouse_move_event(&self, cursor: Point2D<f32>) { pub fn send_mouse_move_event(&self, cursor: Point2D<f32>) {
let message = MouseMoveEvent(cursor); let message = MouseMoveEvent(cursor);
let ScriptChan(ref chan) = self.pipeline.script_chan; let ScriptChan(ref chan) = self.pipeline.script_chan;
chan.send_opt(SendEventMsg(self.pipeline.id.clone(), message)); let _ = chan.send_opt(SendEventMsg(self.pipeline.id.clone(), message));
} }
// Given the current window size, determine which tiles need to be (re-)rendered and sends them // Given the current window size, determine which tiles need to be (re-)rendered and sends them
@ -432,7 +432,7 @@ impl CompositorLayer {
redisplay = !unused.is_empty(); redisplay = !unused.is_empty();
if redisplay { if redisplay {
// Send back unused tiles. // Send back unused tiles.
self.pipeline.render_chan.send_opt(UnusedBufferMsg(unused)); let _ = self.pipeline.render_chan.send_opt(UnusedBufferMsg(unused));
} }
if !request.is_empty() { if !request.is_empty() {
// Ask for tiles. // Ask for tiles.
@ -440,7 +440,7 @@ impl CompositorLayer {
// FIXME(#2003, pcwalton): We may want to batch these up in the case in which // FIXME(#2003, pcwalton): We may want to batch these up in the case in which
// one page has multiple layers, to avoid the user seeing inconsistent states. // one page has multiple layers, to avoid the user seeing inconsistent states.
let msg = ReRenderMsg(request, scale, self.id, self.epoch); let msg = ReRenderMsg(request, scale, self.id, self.epoch);
self.pipeline.render_chan.send_opt(msg); let _ = self.pipeline.render_chan.send_opt(msg);
} }
} }
}; };
@ -548,7 +548,7 @@ impl CompositorLayer {
self.page_size = Some(new_size); self.page_size = Some(new_size);
match self.quadtree { match self.quadtree {
Tree(ref mut quadtree) => { Tree(ref mut quadtree) => {
self.pipeline let _ = self.pipeline
.render_chan .render_chan
.send_opt(UnusedBufferMsg(quadtree.resize(new_size.width as uint, .send_opt(UnusedBufferMsg(quadtree.resize(new_size.width as uint,
new_size.height as uint))); new_size.height as uint)));
@ -655,7 +655,7 @@ impl CompositorLayer {
child.page_size = Some(new_size); child.page_size = Some(new_size);
match child.quadtree { match child.quadtree {
Tree(ref mut quadtree) => { Tree(ref mut quadtree) => {
child.pipeline.render_chan.send_opt(UnusedBufferMsg(quadtree.resize(new_size.width as uint, let _ = child.pipeline.render_chan.send_opt(UnusedBufferMsg(quadtree.resize(new_size.width as uint,
new_size.height as uint))); new_size.height as uint)));
} }
NoTree(tile_size, max_mem) => { NoTree(tile_size, max_mem) => {
@ -829,7 +829,7 @@ impl CompositorLayer {
self.epoch, self.epoch,
epoch, epoch,
self.pipeline.id); self.pipeline.id);
self.pipeline.render_chan.send_opt(UnusedBufferMsg(new_buffers.buffers)); let _ = self.pipeline.render_chan.send_opt(UnusedBufferMsg(new_buffers.buffers));
return None return None
} }
@ -849,7 +849,7 @@ impl CompositorLayer {
buffer)); buffer));
} }
if !unused_tiles.is_empty() { // send back unused buffers if !unused_tiles.is_empty() { // send back unused buffers
self.pipeline.render_chan.send_opt(UnusedBufferMsg(unused_tiles)); let _ = self.pipeline.render_chan.send_opt(UnusedBufferMsg(unused_tiles));
} }
} }
@ -892,7 +892,7 @@ impl CompositorLayer {
tile.mark_wont_leak() tile.mark_wont_leak()
} }
self.pipeline.render_chan.send_opt(UnusedBufferMsg(tiles)); let _ = self.pipeline.render_chan.send_opt(UnusedBufferMsg(tiles));
} }
} }
} }

View file

@ -388,10 +388,10 @@ impl Constellation {
fn force_pipeline_exit(old_pipeline: &Rc<Pipeline>) { fn force_pipeline_exit(old_pipeline: &Rc<Pipeline>) {
let ScriptChan(ref old_script) = old_pipeline.script_chan; let ScriptChan(ref old_script) = old_pipeline.script_chan;
old_script.send_opt(ExitPipelineMsg(old_pipeline.id)); let _ = old_script.send_opt(ExitPipelineMsg(old_pipeline.id));
old_pipeline.render_chan.send_opt(render_task::ExitMsg(None)); let _ = old_pipeline.render_chan.send_opt(render_task::ExitMsg(None));
let LayoutChan(ref old_layout) = old_pipeline.layout_chan; let LayoutChan(ref old_layout) = old_pipeline.layout_chan;
old_layout.send_opt(layout_interface::ExitNowMsg); let _ = old_layout.send_opt(layout_interface::ExitNowMsg);
} }
force_pipeline_exit(&old_pipeline); force_pipeline_exit(&old_pipeline);
self.pipelines.remove(&pipeline_id); self.pipelines.remove(&pipeline_id);
@ -796,7 +796,7 @@ impl Constellation {
debug!("constellation sending resize message to active frame"); debug!("constellation sending resize message to active frame");
let pipeline = &frame_tree.pipeline; let pipeline = &frame_tree.pipeline;
let ScriptChan(ref chan) = pipeline.script_chan; let ScriptChan(ref chan) = pipeline.script_chan;
chan.send_opt(ResizeMsg(pipeline.id, new_size)); let _ = chan.send_opt(ResizeMsg(pipeline.id, new_size));
already_seen.insert(pipeline.id); already_seen.insert(pipeline.id);
} }
for frame_tree in self.navigation_context.previous.iter() for frame_tree in self.navigation_context.previous.iter()
@ -805,7 +805,7 @@ impl Constellation {
if !already_seen.contains(&pipeline.id) { if !already_seen.contains(&pipeline.id) {
debug!("constellation sending resize message to inactive frame"); debug!("constellation sending resize message to inactive frame");
let ScriptChan(ref chan) = pipeline.script_chan; let ScriptChan(ref chan) = pipeline.script_chan;
chan.send_opt(ResizeInactiveMsg(pipeline.id, new_size)); let _ = chan.send_opt(ResizeInactiveMsg(pipeline.id, new_size));
already_seen.insert(pipeline.id); already_seen.insert(pipeline.id);
} }
} }
@ -818,7 +818,7 @@ impl Constellation {
debug!("constellation sending resize message to pending outer frame ({:?})", debug!("constellation sending resize message to pending outer frame ({:?})",
frame_tree.pipeline.id); frame_tree.pipeline.id);
let ScriptChan(ref chan) = frame_tree.pipeline.script_chan; let ScriptChan(ref chan) = frame_tree.pipeline.script_chan;
chan.send_opt(ResizeMsg(frame_tree.pipeline.id, new_size)); let _ = chan.send_opt(ResizeMsg(frame_tree.pipeline.id, new_size));
} }
} }

View file

@ -14,9 +14,9 @@ use layout::wrapper::{LayoutElement, LayoutNode, PostorderNodeMutTraversal, Thre
use gfx::font_context::FontContext; use gfx::font_context::FontContext;
use servo_util::cache::{Cache, LRUCache, SimpleHashCache}; use servo_util::cache::{Cache, LRUCache, SimpleHashCache};
use servo_util::namespace::Null; use servo_util::namespace::Null;
use servo_util::smallvec::{SmallVec, SmallVec0, SmallVec16}; use servo_util::smallvec::{SmallVec, SmallVec16};
use servo_util::str::DOMString; use servo_util::str::DOMString;
use std::cast; use std::mem;
use std::hash::{Hash, sip}; use std::hash::{Hash, sip};
use std::slice::Items; use std::slice::Items;
use style::{After, Before, ComputedValues, MatchedProperty, Stylist, TElement, TNode, cascade}; use style::{After, Before, ComputedValues, MatchedProperty, Stylist, TElement, TNode, cascade};
@ -24,8 +24,8 @@ use sync::Arc;
pub struct ApplicableDeclarations { pub struct ApplicableDeclarations {
pub normal: SmallVec16<MatchedProperty>, pub normal: SmallVec16<MatchedProperty>,
pub before: SmallVec0<MatchedProperty>, pub before: Vec<MatchedProperty>,
pub after: SmallVec0<MatchedProperty>, pub after: Vec<MatchedProperty>,
/// Whether the `normal` declarations are shareable with other nodes. /// Whether the `normal` declarations are shareable with other nodes.
pub normal_shareable: bool, pub normal_shareable: bool,
@ -35,28 +35,28 @@ impl ApplicableDeclarations {
pub fn new() -> ApplicableDeclarations { pub fn new() -> ApplicableDeclarations {
ApplicableDeclarations { ApplicableDeclarations {
normal: SmallVec16::new(), normal: SmallVec16::new(),
before: SmallVec0::new(), before: Vec::new(),
after: SmallVec0::new(), after: Vec::new(),
normal_shareable: false, normal_shareable: false,
} }
} }
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.normal = SmallVec16::new(); self.normal = SmallVec16::new();
self.before = SmallVec0::new(); self.before = Vec::new();
self.after = SmallVec0::new(); self.after = Vec::new();
self.normal_shareable = false; self.normal_shareable = false;
} }
} }
#[deriving(Clone)] #[deriving(Clone)]
pub struct ApplicableDeclarationsCacheEntry { pub struct ApplicableDeclarationsCacheEntry {
pub declarations: SmallVec16<MatchedProperty>, pub declarations: Vec<MatchedProperty>,
} }
impl ApplicableDeclarationsCacheEntry { impl ApplicableDeclarationsCacheEntry {
fn new(slice: &[MatchedProperty]) -> ApplicableDeclarationsCacheEntry { fn new(slice: &[MatchedProperty]) -> ApplicableDeclarationsCacheEntry {
let mut entry_declarations = SmallVec16::new(); let mut entry_declarations = Vec::new();
for declarations in slice.iter() { for declarations in slice.iter() {
entry_declarations.push(declarations.clone()); entry_declarations.push(declarations.clone());
} }
@ -96,8 +96,8 @@ impl<'a> ApplicableDeclarationsCacheQuery<'a> {
#[inline] #[inline]
fn arc_ptr_eq<T>(a: &Arc<T>, b: &Arc<T>) -> bool { fn arc_ptr_eq<T>(a: &Arc<T>, b: &Arc<T>) -> bool {
unsafe { unsafe {
let a: uint = cast::transmute_copy(a); let a: uint = mem::transmute_copy(a);
let b: uint = cast::transmute_copy(b); let b: uint = mem::transmute_copy(b);
a == b a == b
} }
} }
@ -121,7 +121,7 @@ impl<'a> Hash for ApplicableDeclarationsCacheQuery<'a> {
fn hash(&self, state: &mut sip::SipState) { fn hash(&self, state: &mut sip::SipState) {
for declaration in self.declarations.iter() { for declaration in self.declarations.iter() {
let ptr: uint = unsafe { let ptr: uint = unsafe {
cast::transmute_copy(declaration) mem::transmute_copy(declaration)
}; };
ptr.hash(state); ptr.hash(state);
} }
@ -231,12 +231,12 @@ impl StyleSharingCandidate {
} }
fn can_share_style_with(&self, element: &LayoutElement) -> bool { fn can_share_style_with(&self, element: &LayoutElement) -> bool {
if element.get_local_name() != self.local_name { if element.get_local_name() != self.local_name.as_slice() {
return false return false
} }
match (&self.class, element.get_attr(&Null, "class")) { match (&self.class, element.get_attr(&Null, "class")) {
(&None, Some(_)) | (&Some(_), None) => return false, (&None, Some(_)) | (&Some(_), None) => return false,
(&Some(ref this_class), Some(element_class)) if element_class != *this_class => { (&Some(ref this_class), Some(element_class)) if element_class != this_class.as_slice() => {
return false return false
} }
(&Some(_), Some(_)) | (&None, None) => {} (&Some(_), Some(_)) | (&None, None) => {}
@ -383,7 +383,7 @@ impl<'ln> PrivateMatchMethods for LayoutNode<'ln> {
}; };
let parent_layout_data: &Option<LayoutDataWrapper> = unsafe { let parent_layout_data: &Option<LayoutDataWrapper> = unsafe {
cast::transmute(parent_node.borrow_layout_data_unchecked()) mem::transmute(parent_node.borrow_layout_data_unchecked())
}; };
match parent_layout_data { match parent_layout_data {
&Some(ref parent_layout_data_ref) => { &Some(ref parent_layout_data_ref) => {

View file

@ -6,7 +6,7 @@ use layout::incremental::RestyleDamage;
use layout::util::LayoutDataAccess; use layout::util::LayoutDataAccess;
use layout::wrapper::{TLayoutNode, ThreadSafeLayoutNode}; use layout::wrapper::{TLayoutNode, ThreadSafeLayoutNode};
use layout::wrapper::{After, AfterBlock, Before, BeforeBlock, Normal}; use layout::wrapper::{After, AfterBlock, Before, BeforeBlock, Normal};
use std::cast; use std::mem;
use style::ComputedValues; use style::ComputedValues;
use sync::Arc; use sync::Arc;
@ -27,28 +27,28 @@ impl<'ln> NodeUtil for ThreadSafeLayoutNode<'ln> {
let layout_data_ref = self.borrow_layout_data(); let layout_data_ref = self.borrow_layout_data();
match self.get_pseudo_element_type() { match self.get_pseudo_element_type() {
Before | BeforeBlock => { Before | BeforeBlock => {
cast::transmute_lifetime(layout_data_ref.as_ref() mem::transmute(layout_data_ref.as_ref()
.unwrap() .unwrap()
.data .data
.before_style .before_style
.as_ref() .as_ref()
.unwrap()) .unwrap())
} }
After | AfterBlock => { After | AfterBlock => {
cast::transmute_lifetime(layout_data_ref.as_ref() mem::transmute(layout_data_ref.as_ref()
.unwrap() .unwrap()
.data .data
.after_style .after_style
.as_ref() .as_ref()
.unwrap()) .unwrap())
} }
Normal => { Normal => {
cast::transmute_lifetime(layout_data_ref.as_ref() mem::transmute(layout_data_ref.as_ref()
.unwrap() .unwrap()
.shared_data .shared_data
.style .style
.as_ref() .as_ref()
.unwrap()) .unwrap())
} }
} }
} }

View file

@ -1681,11 +1681,11 @@ impl Flow for BlockFlow {
impl fmt::Show for BlockFlow { impl fmt::Show for BlockFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_float() { if self.is_float() {
write!(f.buf, "FloatFlow: {}", self.fragment) write!(f, "FloatFlow: {}", self.fragment)
} else if self.is_root() { } else if self.is_root() {
write!(f.buf, "RootFlow: {}", self.fragment) write!(f, "RootFlow: {}", self.fragment)
} else { } else {
write!(f.buf, "BlockFlow: {}", self.fragment) write!(f, "BlockFlow: {}", self.fragment)
} }
} }
} }

View file

@ -553,10 +553,10 @@ impl<'a> FlowConstructor<'a> {
whitespace_style)) whitespace_style))
=> { => {
// Instantiate the whitespace fragment. // Instantiate the whitespace fragment.
let fragment_info = UnscannedTextFragment(UnscannedTextFragmentInfo::from_text(" ".to_owned())); let fragment_info = UnscannedTextFragment(UnscannedTextFragmentInfo::from_text(" ".to_string()));
let fragment = Fragment::from_opaque_node_and_style(whitespace_node, let fragment = Fragment::from_opaque_node_and_style(whitespace_node,
whitespace_style.clone(), whitespace_style.clone(),
fragment_info); fragment_info);
fragment_accumulator.fragments.push(fragment, whitespace_style) fragment_accumulator.fragments.push(fragment, whitespace_style)
} }
ConstructionItemConstructionResult(TableColumnFragmentConstructionItem(_)) => { ConstructionItemConstructionResult(TableColumnFragmentConstructionItem(_)) => {

View file

@ -17,7 +17,7 @@ use servo_msg::constellation_msg::ConstellationChan;
use servo_net::image::holder::LocalImageCacheHandle; use servo_net::image::holder::LocalImageCacheHandle;
use servo_util::geometry::Au; use servo_util::geometry::Au;
use servo_util::opts::Opts; use servo_util::opts::Opts;
use std::cast; use std::mem;
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
use std::ptr; use std::ptr;
#[cfg(not(target_os="android"))] #[cfg(not(target_os="android"))]
@ -104,9 +104,9 @@ impl LayoutContext {
unsafe { unsafe {
if FONT_CONTEXT == ptr::mut_null() { if FONT_CONTEXT == ptr::mut_null() {
let context = box FontContext::new(self.font_context_info.clone()); let context = box FontContext::new(self.font_context_info.clone());
FONT_CONTEXT = cast::transmute(context) FONT_CONTEXT = mem::transmute(context)
} }
cast::transmute(FONT_CONTEXT) mem::transmute(FONT_CONTEXT)
} }
} }
@ -126,9 +126,9 @@ impl LayoutContext {
unsafe { unsafe {
if APPLICABLE_DECLARATIONS_CACHE == ptr::mut_null() { if APPLICABLE_DECLARATIONS_CACHE == ptr::mut_null() {
let cache = box ApplicableDeclarationsCache::new(); let cache = box ApplicableDeclarationsCache::new();
APPLICABLE_DECLARATIONS_CACHE = cast::transmute(cache) APPLICABLE_DECLARATIONS_CACHE = mem::transmute(cache)
} }
cast::transmute(APPLICABLE_DECLARATIONS_CACHE) mem::transmute(APPLICABLE_DECLARATIONS_CACHE)
} }
} }
@ -148,9 +148,9 @@ impl LayoutContext {
unsafe { unsafe {
if STYLE_SHARING_CANDIDATE_CACHE == ptr::mut_null() { if STYLE_SHARING_CANDIDATE_CACHE == ptr::mut_null() {
let cache = box StyleSharingCandidateCache::new(); let cache = box StyleSharingCandidateCache::new();
STYLE_SHARING_CANDIDATE_CACHE = cast::transmute(cache) STYLE_SHARING_CANDIDATE_CACHE = mem::transmute(cache)
} }
cast::transmute(STYLE_SHARING_CANDIDATE_CACHE) mem::transmute(STYLE_SHARING_CANDIDATE_CACHE)
} }
} }
} }
@ -168,13 +168,13 @@ impl LayoutContext {
let opt = font_context.replace(None); let opt = font_context.replace(None);
let mut context; let mut context;
match opt { match opt {
Some(c) => context = cast::transmute(c), Some(c) => context = mem::transmute(c),
None => { None => {
context = cast::transmute(box FontContext::new(self.font_context_info.clone())) context = mem::transmute(box FontContext::new(self.font_context_info.clone()))
} }
} }
font_context.replace(Some(context)); font_context.replace(Some(context));
cast::transmute(context) mem::transmute(context)
} }
} }
@ -183,13 +183,13 @@ impl LayoutContext {
let opt = applicable_declarations_cache.replace(None); let opt = applicable_declarations_cache.replace(None);
let mut cache; let mut cache;
match opt { match opt {
Some(c) => cache = cast::transmute(c), Some(c) => cache = mem::transmute(c),
None => { None => {
cache = cast::transmute(box ApplicableDeclarationsCache::new()); cache = mem::transmute(box ApplicableDeclarationsCache::new());
} }
} }
applicable_declarations_cache.replace(Some(cache)); applicable_declarations_cache.replace(Some(cache));
cast::transmute(cache) mem::transmute(cache)
} }
} }
@ -198,13 +198,13 @@ impl LayoutContext {
let opt = style_sharing_candidate_cache.replace(None); let opt = style_sharing_candidate_cache.replace(None);
let mut cache; let mut cache;
match opt { match opt {
Some(c) => cache = cast::transmute(c), Some(c) => cache = mem::transmute(c),
None => { None => {
cache = cast::transmute(box StyleSharingCandidateCache::new()); cache = mem::transmute(box StyleSharingCandidateCache::new());
} }
} }
style_sharing_candidate_cache.replace(Some(cache)); style_sharing_candidate_cache.replace(Some(cache));
cast::transmute(cache) mem::transmute(cache)
} }
} }
} }

View file

@ -46,7 +46,7 @@ struct Float {
impl fmt::Show for Float { impl fmt::Show for Float {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "bounds={} kind={:?}", self.bounds, self.kind) write!(f, "bounds={} kind={:?}", self.bounds, self.kind)
} }
} }
@ -73,7 +73,7 @@ impl FloatList {
impl fmt::Show for FloatList { impl fmt::Show for FloatList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "max_top={} floats={:?}", self.max_top, self.floats) write!(f, "max_top={} floats={:?}", self.max_top, self.floats)
} }
} }
@ -130,7 +130,7 @@ pub struct PlacementInfo {
impl fmt::Show for PlacementInfo { impl fmt::Show for PlacementInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "size={} ceiling={} max_width={} kind={:?}", self.size, self.ceiling, self.max_width, self.kind) write!(f, "size={} ceiling={} max_width={} kind={:?}", self.size, self.ceiling, self.max_width, self.kind)
} }
} }
@ -152,10 +152,10 @@ impl fmt::Show for Floats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.list.get() { match self.list.get() {
None => { None => {
write!(f.buf, "[empty]") write!(f, "[empty]")
} }
Some(list) => { Some(list) => {
write!(f.buf, "offset={} floats={}", self.offset, list) write!(f, "offset={} floats={}", self.offset, list)
} }
} }
} }

View file

@ -53,7 +53,7 @@ use gfx::display_list::DisplayList;
use gfx::render_task::RenderLayer; use gfx::render_task::RenderLayer;
use servo_msg::compositor_msg::LayerId; use servo_msg::compositor_msg::LayerId;
use servo_util::geometry::Au; use servo_util::geometry::Au;
use std::cast; use std::mem;
use std::fmt; use std::fmt;
use std::iter::Zip; use std::iter::Zip;
use std::num::Zero; use std::num::Zero;
@ -263,7 +263,7 @@ pub trait Flow: fmt::Show + ToStr + Share {
/// Returns a layer ID for the given fragment. /// Returns a layer ID for the given fragment.
fn layer_id(&self, fragment_id: uint) -> LayerId { fn layer_id(&self, fragment_id: uint) -> LayerId {
unsafe { unsafe {
let pointer: uint = cast::transmute(self); let pointer: uint = mem::transmute(self);
LayerId(pointer, fragment_id) LayerId(pointer, fragment_id)
} }
} }
@ -274,7 +274,7 @@ pub trait Flow: fmt::Show + ToStr + Share {
#[inline(always)] #[inline(always)]
pub fn base<'a>(this: &'a Flow) -> &'a BaseFlow { pub fn base<'a>(this: &'a Flow) -> &'a BaseFlow {
unsafe { unsafe {
let (_, ptr): (uint, &BaseFlow) = cast::transmute(this); let (_, ptr): (uint, &BaseFlow) = mem::transmute(this);
ptr ptr
} }
} }
@ -287,7 +287,7 @@ pub fn imm_child_iter<'a>(flow: &'a Flow) -> FlowListIterator<'a> {
#[inline(always)] #[inline(always)]
pub fn mut_base<'a>(this: &'a mut Flow) -> &'a mut BaseFlow { pub fn mut_base<'a>(this: &'a mut Flow) -> &'a mut BaseFlow {
unsafe { unsafe {
let (_, ptr): (uint, &mut BaseFlow) = cast::transmute(this); let (_, ptr): (uint, &mut BaseFlow) = mem::transmute(this);
ptr ptr
} }
} }
@ -582,7 +582,7 @@ impl<'a> Iterator<&'a mut Flow> for DescendantIter<'a> {
None => None, None => None,
Some(ref mut flow) => { Some(ref mut flow) => {
unsafe { unsafe {
let result: &'a mut Flow = cast::transmute(flow.get_mut()); let result: &'a mut Flow = mem::transmute(flow.get_mut());
Some(result) Some(result)
} }
} }
@ -902,7 +902,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow {
/// Dumps the flow tree for debugging, with a prefix to indicate that we're at the given level. /// Dumps the flow tree for debugging, with a prefix to indicate that we're at the given level.
fn dump_with_level(self, level: uint) { fn dump_with_level(self, level: uint) {
let mut indent = StrBuf::new(); let mut indent = String::new();
for _ in range(0, level) { for _ in range(0, level) {
indent.push_str("| ") indent.push_str("| ")
} }

View file

@ -8,7 +8,6 @@
use layout::flow::{Flow, base, mut_base}; use layout::flow::{Flow, base, mut_base};
use layout::flow_ref::FlowRef; use layout::flow_ref::FlowRef;
use std::cast;
use std::mem; use std::mem;
use std::ptr; use std::ptr;
@ -56,7 +55,7 @@ impl Rawlink {
/// Like Option::Some for Rawlink /// Like Option::Some for Rawlink
pub fn some(n: &Flow) -> Rawlink { pub fn some(n: &Flow) -> Rawlink {
unsafe { cast::transmute(n) } unsafe { mem::transmute(n) }
} }
fn from_optional_flow_ref(flow_ref: &Option<FlowRef>) -> Rawlink { fn from_optional_flow_ref(flow_ref: &Option<FlowRef>) -> Rawlink {
@ -70,7 +69,7 @@ impl Rawlink {
if self.obj.is_null() { if self.obj.is_null() {
None None
} else { } else {
let me: &mut Flow = cast::transmute_copy(self); let me: &mut Flow = mem::transmute_copy(self);
Some(me) Some(me)
} }
} }
@ -128,7 +127,7 @@ impl FlowList {
None => None, None => None,
Some(ref mut tail) => { Some(ref mut tail) => {
let x: &mut Flow = tail.get_mut(); let x: &mut Flow = tail.get_mut();
Some(cast::transmute_copy(&x)) Some(mem::transmute_copy(&x))
} }
} }
} }

View file

@ -9,7 +9,6 @@
use layout::flow::Flow; use layout::flow::Flow;
use layout::flow; use layout::flow;
use std::cast;
use std::mem; use std::mem;
use std::ptr; use std::ptr;
use std::sync::atomics::SeqCst; use std::sync::atomics::SeqCst;
@ -25,22 +24,22 @@ impl FlowRef {
unsafe { unsafe {
let result = { let result = {
let flow_ref: &mut Flow = flow; let flow_ref: &mut Flow = flow;
cast::transmute(flow_ref) mem::transmute(flow_ref)
}; };
cast::forget(flow); mem::forget(flow);
result result
} }
} }
pub fn get<'a>(&'a self) -> &'a Flow { pub fn get<'a>(&'a self) -> &'a Flow {
unsafe { unsafe {
cast::transmute_copy(self) mem::transmute_copy(self)
} }
} }
pub fn get_mut<'a>(&'a mut self) -> &'a mut Flow { pub fn get_mut<'a>(&'a mut self) -> &'a mut Flow {
unsafe { unsafe {
cast::transmute_copy(self) mem::transmute_copy(self)
} }
} }
} }
@ -58,7 +57,7 @@ impl Drop for FlowRef {
vtable: ptr::null(), vtable: ptr::null(),
ptr: ptr::null(), ptr: ptr::null(),
}); });
drop(cast::transmute::<FlowRef,Box<Flow>>(flow_ref)); drop(mem::transmute::<FlowRef,Box<Flow>>(flow_ref));
self.vtable = ptr::null(); self.vtable = ptr::null();
self.ptr = ptr::null(); self.ptr = ptr::null();
} }

View file

@ -263,7 +263,7 @@ impl SplitInfo {
#[deriving(Clone)] #[deriving(Clone)]
pub struct UnscannedTextFragmentInfo { pub struct UnscannedTextFragmentInfo {
/// The text inside the fragment. /// The text inside the fragment.
pub text: ~str, pub text: String,
} }
impl UnscannedTextFragmentInfo { impl UnscannedTextFragmentInfo {
@ -277,7 +277,7 @@ impl UnscannedTextFragmentInfo {
/// Creates a new instance of `UnscannedTextFragmentInfo` from the given text. /// Creates a new instance of `UnscannedTextFragmentInfo` from the given text.
#[inline] #[inline]
pub fn from_text(text: ~str) -> UnscannedTextFragmentInfo { pub fn from_text(text: String) -> UnscannedTextFragmentInfo {
UnscannedTextFragmentInfo { UnscannedTextFragmentInfo {
text: text, text: text,
} }
@ -1245,7 +1245,7 @@ impl Fragment {
/// Returns true if this fragment is an unscanned text fragment that consists entirely of whitespace. /// Returns true if this fragment is an unscanned text fragment that consists entirely of whitespace.
pub fn is_whitespace_only(&self) -> bool { pub fn is_whitespace_only(&self) -> bool {
match self.specific { match self.specific {
UnscannedTextFragment(ref text_fragment_info) => is_whitespace(text_fragment_info.text), UnscannedTextFragment(ref text_fragment_info) => is_whitespace(text_fragment_info.text.as_slice()),
_ => false, _ => false,
} }
} }
@ -1407,12 +1407,12 @@ impl Fragment {
if value.is_zero() { if value.is_zero() {
Ok(()) Ok(())
} else { } else {
write!(f.buf, "{}{},{},{},{}", write!(f, "{}{},{},{},{}",
name, name,
value.top, value.top,
value.right, value.right,
value.bottom, value.bottom,
value.left) value.left)
} }
} }
@ -1443,7 +1443,7 @@ impl Fragment {
impl fmt::Show for Fragment { impl fmt::Show for Fragment {
/// Outputs a debugging string describing this fragment. /// Outputs a debugging string describing this fragment.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, "({} ", try!(write!(f, "({} ",
match self.specific { match self.specific {
GenericFragment => "GenericFragment", GenericFragment => "GenericFragment",
IframeFragment(_) => "IframeFragment", IframeFragment(_) => "IframeFragment",
@ -1457,9 +1457,9 @@ impl fmt::Show for Fragment {
UnscannedTextFragment(_) => "UnscannedTextFragment", UnscannedTextFragment(_) => "UnscannedTextFragment",
})); }));
try!(self.side_offsets_debug_fmt("bp", self.border_padding, f)); try!(self.side_offsets_debug_fmt("bp", self.border_padding, f));
try!(write!(f.buf, " ")); try!(write!(f, " "));
try!(self.side_offsets_debug_fmt("m", self.margin, f)); try!(self.side_offsets_debug_fmt("m", self.margin, f));
write!(f.buf, ")") write!(f, ")")
} }
} }

View file

@ -245,7 +245,7 @@ impl Neg<LineIndices> for LineIndices {
impl fmt::Show for LineIndices { impl fmt::Show for LineIndices {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}.{}", self.fragment_index, self.char_index) write!(f, "{}.{}", self.fragment_index, self.char_index)
} }
} }
@ -1302,12 +1302,12 @@ impl Flow for InlineFlow {
impl fmt::Show for InlineFlow { impl fmt::Show for InlineFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, "InlineFlow")); try!(write!(f, "InlineFlow"));
for (i, (fragment, _)) in self.fragments.iter().enumerate() { for (i, (fragment, _)) in self.fragments.iter().enumerate() {
if i == 0 { if i == 0 {
try!(write!(f.buf, ": {}", fragment)) try!(write!(f, ": {}", fragment))
} else { } else {
try!(write!(f.buf, ", {}", fragment)) try!(write!(f, ", {}", fragment))
} }
} }
Ok(()) Ok(())

View file

@ -54,8 +54,6 @@ use servo_util::time::{ProfilerChan, profile};
use servo_util::time; use servo_util::time;
use servo_util::task::send_on_failure; use servo_util::task::send_on_failure;
use servo_util::workqueue::WorkQueue; use servo_util::workqueue::WorkQueue;
use std::cast::transmute;
use std::cast;
use std::comm::{channel, Sender, Receiver}; use std::comm::{channel, Sender, Receiver};
use std::mem; use std::mem;
use std::ptr; use std::ptr;
@ -318,8 +316,8 @@ impl LayoutTask {
let local_image_cache = box LocalImageCache(image_cache_task.clone()); let local_image_cache = box LocalImageCache(image_cache_task.clone());
let local_image_cache = unsafe { let local_image_cache = unsafe {
let cache = Arc::new(Mutex::new( let cache = Arc::new(Mutex::new(
cast::transmute::<Box<LocalImageCache>, *()>(local_image_cache))); mem::transmute::<Box<LocalImageCache>, *()>(local_image_cache)));
LocalImageCacheHandle::new(cast::transmute::<Arc<Mutex<*()>>,Arc<*()>>(cache)) LocalImageCacheHandle::new(mem::transmute::<Arc<Mutex<*()>>,Arc<*()>>(cache))
}; };
let screen_size = Size2D(Au(0), Au(0)); let screen_size = Size2D(Au(0), Au(0));
let parallel_traversal = if opts.layout_threads != 1 { let parallel_traversal = if opts.layout_threads != 1 {
@ -562,7 +560,7 @@ impl LayoutTask {
// FIXME: Isolate this transmutation into a "bridge" module. // FIXME: Isolate this transmutation into a "bridge" module.
let node: &mut LayoutNode = unsafe { let node: &mut LayoutNode = unsafe {
let mut node: JS<Node> = JS::from_trusted_node_address(data.document_root); let mut node: JS<Node> = JS::from_trusted_node_address(data.document_root);
transmute(&mut node) mem::transmute(&mut node)
}; };
debug!("layout: received layout request for: {:s}", data.url.to_str()); debug!("layout: received layout request for: {:s}", data.url.to_str());
@ -914,7 +912,7 @@ impl LayoutTask {
/// because it contains local managed pointers. /// because it contains local managed pointers.
unsafe fn handle_reap_layout_data(&self, layout_data: LayoutDataRef) { unsafe fn handle_reap_layout_data(&self, layout_data: LayoutDataRef) {
let mut layout_data_ref = layout_data.borrow_mut(); let mut layout_data_ref = layout_data.borrow_mut();
let _: Option<LayoutDataWrapper> = cast::transmute( let _: Option<LayoutDataWrapper> = mem::transmute(
mem::replace(&mut *layout_data_ref, None)); mem::replace(&mut *layout_data_ref, None));
} }
} }

View file

@ -254,7 +254,7 @@ pub struct IntrinsicWidths {
impl fmt::Show for IntrinsicWidths { impl fmt::Show for IntrinsicWidths {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "min={}, pref={}, surr={}", self.minimum_width, self.preferred_width, self.surround_width) write!(f, "min={}, pref={}, surr={}", self.minimum_width, self.preferred_width, self.surround_width)
} }
} }

View file

@ -15,7 +15,7 @@ use layout::flow;
use layout::flow_ref::FlowRef; use layout::flow_ref::FlowRef;
use layout::layout_task::{AssignHeightsAndStoreOverflowTraversal, AssignWidthsTraversal}; use layout::layout_task::{AssignHeightsAndStoreOverflowTraversal, AssignWidthsTraversal};
use layout::layout_task::{BubbleWidthsTraversal}; use layout::layout_task::{BubbleWidthsTraversal};
use layout::util::{LayoutDataAccess, OpaqueNodeMethods}; use layout::util::{LayoutDataAccess, LayoutDataWrapper, OpaqueNodeMethods};
use layout::wrapper::{layout_node_to_unsafe_layout_node, LayoutNode, PostorderNodeMutTraversal}; use layout::wrapper::{layout_node_to_unsafe_layout_node, LayoutNode, PostorderNodeMutTraversal};
use layout::wrapper::{ThreadSafeLayoutNode, UnsafeLayoutNode}; use layout::wrapper::{ThreadSafeLayoutNode, UnsafeLayoutNode};
@ -23,7 +23,7 @@ use gfx::display_list::OpaqueNode;
use servo_util::time::{ProfilerChan, profile}; use servo_util::time::{ProfilerChan, profile};
use servo_util::time; use servo_util::time;
use servo_util::workqueue::{WorkQueue, WorkUnit, WorkerProxy}; use servo_util::workqueue::{WorkQueue, WorkUnit, WorkerProxy};
use std::cast; use std::mem;
use std::ptr; use std::ptr;
use std::sync::atomics::{AtomicInt, Relaxed, SeqCst}; use std::sync::atomics::{AtomicInt, Relaxed, SeqCst};
use style::{Stylist, TNode}; use style::{Stylist, TNode};
@ -66,25 +66,25 @@ fn null_unsafe_flow() -> UnsafeFlow {
pub fn owned_flow_to_unsafe_flow(flow: *FlowRef) -> UnsafeFlow { pub fn owned_flow_to_unsafe_flow(flow: *FlowRef) -> UnsafeFlow {
unsafe { unsafe {
cast::transmute_copy(&*flow) mem::transmute_copy(&*flow)
} }
} }
pub fn mut_owned_flow_to_unsafe_flow(flow: *mut FlowRef) -> UnsafeFlow { pub fn mut_owned_flow_to_unsafe_flow(flow: *mut FlowRef) -> UnsafeFlow {
unsafe { unsafe {
cast::transmute_copy(&*flow) mem::transmute_copy(&*flow)
} }
} }
pub fn borrowed_flow_to_unsafe_flow(flow: &Flow) -> UnsafeFlow { pub fn borrowed_flow_to_unsafe_flow(flow: &Flow) -> UnsafeFlow {
unsafe { unsafe {
cast::transmute_copy(&flow) mem::transmute_copy(&flow)
} }
} }
pub fn mut_borrowed_flow_to_unsafe_flow(flow: &mut Flow) -> UnsafeFlow { pub fn mut_borrowed_flow_to_unsafe_flow(flow: &mut Flow) -> UnsafeFlow {
unsafe { unsafe {
cast::transmute_copy(&flow) mem::transmute_copy(&flow)
} }
} }
@ -142,7 +142,7 @@ trait ParallelPostorderFlowTraversal : PostorderFlowTraversal {
loop { loop {
unsafe { unsafe {
// Get a real flow. // Get a real flow.
let flow: &mut FlowRef = cast::transmute(&unsafe_flow); let flow: &mut FlowRef = mem::transmute(&unsafe_flow);
// Perform the appropriate traversal. // Perform the appropriate traversal.
if self.should_process(flow.get_mut()) { if self.should_process(flow.get_mut()) {
@ -164,7 +164,7 @@ trait ParallelPostorderFlowTraversal : PostorderFlowTraversal {
// No, we're not at the root yet. Then are we the last child // No, we're not at the root yet. Then are we the last child
// of our parent to finish processing? If so, we can continue // of our parent to finish processing? If so, we can continue
// on with our parent; otherwise, we've gotta wait. // on with our parent; otherwise, we've gotta wait.
let parent: &mut FlowRef = cast::transmute(&unsafe_parent); let parent: &mut FlowRef = mem::transmute(&unsafe_parent);
let parent_base = flow::mut_base(parent.get_mut()); let parent_base = flow::mut_base(parent.get_mut());
if parent_base.parallel.children_count.fetch_sub(1, SeqCst) == 1 { if parent_base.parallel.children_count.fetch_sub(1, SeqCst) == 1 {
// We were the last child of our parent. Reflow our parent. // We were the last child of our parent. Reflow our parent.
@ -197,7 +197,7 @@ trait ParallelPreorderFlowTraversal : PreorderFlowTraversal {
let mut had_children = false; let mut had_children = false;
unsafe { unsafe {
// Get a real flow. // Get a real flow.
let flow: &mut FlowRef = cast::transmute(&unsafe_flow); let flow: &mut FlowRef = mem::transmute(&unsafe_flow);
// Perform the appropriate traversal. // Perform the appropriate traversal.
self.process(flow.get_mut()); self.process(flow.get_mut());
@ -238,7 +238,7 @@ impl<'a> ParallelPostorderFlowTraversal for AssignHeightsAndStoreOverflowTravers
fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode, fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode,
proxy: &mut WorkerProxy<*mut LayoutContext,UnsafeLayoutNode>) { proxy: &mut WorkerProxy<*mut LayoutContext,UnsafeLayoutNode>) {
unsafe { unsafe {
let layout_context: &mut LayoutContext = cast::transmute(*proxy.user_data()); let layout_context: &mut LayoutContext = mem::transmute(*proxy.user_data());
// Get a real layout node. // Get a real layout node.
let node: LayoutNode = ::std::intrinsics::transmute(unsafe_layout_node); let node: LayoutNode = ::std::intrinsics::transmute(unsafe_layout_node);
@ -269,7 +269,7 @@ fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode,
if node.is_element() { if node.is_element() {
// Perform the CSS selector matching. // Perform the CSS selector matching.
let stylist: &Stylist = cast::transmute(layout_context.stylist); let stylist: &Stylist = mem::transmute(layout_context.stylist);
node.match_node(stylist, &mut applicable_declarations, &mut shareable); node.match_node(stylist, &mut applicable_declarations, &mut shareable);
} }
@ -327,12 +327,12 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode,
proxy: &mut WorkerProxy<*mut LayoutContext,UnsafeLayoutNode>) { proxy: &mut WorkerProxy<*mut LayoutContext,UnsafeLayoutNode>) {
loop { loop {
let layout_context: &mut LayoutContext = unsafe { let layout_context: &mut LayoutContext = unsafe {
cast::transmute(*proxy.user_data()) mem::transmute(*proxy.user_data())
}; };
// Get a real layout node. // Get a real layout node.
let node: LayoutNode = unsafe { let node: LayoutNode = unsafe {
cast::transmute(unsafe_layout_node) mem::transmute(unsafe_layout_node)
}; };
// Construct flows for this node. // Construct flows for this node.
@ -373,7 +373,7 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode,
unsafe { unsafe {
match *parent.borrow_layout_data_unchecked() { match *parent.borrow_layout_data_unchecked() {
Some(ref parent_layout_data) => { Some(ref parent_layout_data) => {
let parent_layout_data = cast::transmute_mut(parent_layout_data); let parent_layout_data: &mut LayoutDataWrapper = mem::transmute(parent_layout_data);
if parent_layout_data.data if parent_layout_data.data
.parallel .parallel
.children_count .children_count
@ -398,7 +398,7 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode,
fn assign_widths(unsafe_flow: PaddedUnsafeFlow, fn assign_widths(unsafe_flow: PaddedUnsafeFlow,
proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) { proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) {
let layout_context: &mut LayoutContext = unsafe { let layout_context: &mut LayoutContext = unsafe {
cast::transmute(*proxy.user_data()) mem::transmute(*proxy.user_data())
}; };
let mut assign_widths_traversal = AssignWidthsTraversal { let mut assign_widths_traversal = AssignWidthsTraversal {
layout_context: layout_context, layout_context: layout_context,
@ -409,7 +409,7 @@ fn assign_widths(unsafe_flow: PaddedUnsafeFlow,
fn assign_heights_and_store_overflow(unsafe_flow: PaddedUnsafeFlow, fn assign_heights_and_store_overflow(unsafe_flow: PaddedUnsafeFlow,
proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) { proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) {
let layout_context: &mut LayoutContext = unsafe { let layout_context: &mut LayoutContext = unsafe {
cast::transmute(*proxy.user_data()) mem::transmute(*proxy.user_data())
}; };
let mut assign_heights_traversal = AssignHeightsAndStoreOverflowTraversal { let mut assign_heights_traversal = AssignHeightsAndStoreOverflowTraversal {
layout_context: layout_context, layout_context: layout_context,
@ -422,7 +422,7 @@ fn compute_absolute_position(unsafe_flow: PaddedUnsafeFlow,
let mut had_descendants = false; let mut had_descendants = false;
unsafe { unsafe {
// Get a real flow. // Get a real flow.
let flow: &mut FlowRef = cast::transmute(&unsafe_flow); let flow: &mut FlowRef = mem::transmute(&unsafe_flow);
// Compute the absolute position for the flow. // Compute the absolute position for the flow.
flow.get_mut().compute_absolute_position(); flow.get_mut().compute_absolute_position();
@ -475,13 +475,13 @@ fn compute_absolute_position(unsafe_flow: PaddedUnsafeFlow,
fn build_display_list(mut unsafe_flow: PaddedUnsafeFlow, fn build_display_list(mut unsafe_flow: PaddedUnsafeFlow,
proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) { proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) {
let layout_context: &mut LayoutContext = unsafe { let layout_context: &mut LayoutContext = unsafe {
cast::transmute(*proxy.user_data()) mem::transmute(*proxy.user_data())
}; };
loop { loop {
unsafe { unsafe {
// Get a real flow. // Get a real flow.
let flow: &mut FlowRef = cast::transmute(&unsafe_flow); let flow: &mut FlowRef = mem::transmute(&unsafe_flow);
// Build display lists. // Build display lists.
flow.get_mut().build_display_list(layout_context); flow.get_mut().build_display_list(layout_context);
@ -517,7 +517,7 @@ fn build_display_list(mut unsafe_flow: PaddedUnsafeFlow,
// No, we're not at the root yet. Then are we the last child // No, we're not at the root yet. Then are we the last child
// of our parent to finish processing? If so, we can continue // of our parent to finish processing? If so, we can continue
// on with our parent; otherwise, we've gotta wait. // on with our parent; otherwise, we've gotta wait.
let parent: &mut FlowRef = cast::transmute(&unsafe_parent); let parent: &mut FlowRef = mem::transmute(&unsafe_parent);
let parent_base = flow::mut_base(parent.get_mut()); let parent_base = flow::mut_base(parent.get_mut());
if parent_base.parallel if parent_base.parallel
.children_and_absolute_descendant_count .children_and_absolute_descendant_count
@ -536,7 +536,7 @@ pub fn recalc_style_for_subtree(root_node: &LayoutNode,
layout_context: &mut LayoutContext, layout_context: &mut LayoutContext,
queue: &mut WorkQueue<*mut LayoutContext,UnsafeLayoutNode>) { queue: &mut WorkQueue<*mut LayoutContext,UnsafeLayoutNode>) {
unsafe { unsafe {
queue.data = cast::transmute(layout_context) queue.data = mem::transmute(layout_context)
} }
// Enqueue the root node. // Enqueue the root node.
@ -555,7 +555,7 @@ pub fn traverse_flow_tree_preorder(root: &mut FlowRef,
layout_context: &mut LayoutContext, layout_context: &mut LayoutContext,
queue: &mut WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>) { queue: &mut WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>) {
unsafe { unsafe {
queue.data = cast::transmute(layout_context) queue.data = mem::transmute(layout_context)
} }
profile(time::LayoutParallelWarmupCategory, profiler_chan, || { profile(time::LayoutParallelWarmupCategory, profiler_chan, || {
@ -575,7 +575,7 @@ pub fn build_display_list_for_subtree(root: &mut FlowRef,
layout_context: &mut LayoutContext, layout_context: &mut LayoutContext,
queue: &mut WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>) { queue: &mut WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>) {
unsafe { unsafe {
queue.data = cast::transmute(layout_context) queue.data = mem::transmute(layout_context)
} }
profile(time::LayoutParallelWarmupCategory, profiler_chan, || { profile(time::LayoutParallelWarmupCategory, profiler_chan, || {

View file

@ -295,7 +295,7 @@ impl Flow for TableFlow {
impl fmt::Show for TableFlow { impl fmt::Show for TableFlow {
/// Outputs a debugging string describing this table flow. /// Outputs a debugging string describing this table flow.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "TableFlow: {}", self.block_flow) write!(f, "TableFlow: {}", self.block_flow)
} }
} }

View file

@ -68,6 +68,6 @@ impl Flow for TableCaptionFlow {
impl fmt::Show for TableCaptionFlow { impl fmt::Show for TableCaptionFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "TableCaptionFlow: {}", self.block_flow) write!(f, "TableCaptionFlow: {}", self.block_flow)
} }
} }

View file

@ -116,6 +116,6 @@ impl Flow for TableCellFlow {
impl fmt::Show for TableCellFlow { impl fmt::Show for TableCellFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "TableCellFlow: {}", self.block_flow) write!(f, "TableCellFlow: {}", self.block_flow)
} }
} }

View file

@ -81,8 +81,8 @@ impl Flow for TableColGroupFlow {
impl fmt::Show for TableColGroupFlow { impl fmt::Show for TableColGroupFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.fragment { match self.fragment {
Some(ref rb) => write!(f.buf, "TableColGroupFlow: {}", rb), Some(ref rb) => write!(f, "TableColGroupFlow: {}", rb),
None => write!(f.buf, "TableColGroupFlow"), None => write!(f, "TableColGroupFlow"),
} }
} }
} }

View file

@ -220,6 +220,6 @@ impl Flow for TableRowFlow {
impl fmt::Show for TableRowFlow { impl fmt::Show for TableRowFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "TableRowFlow: {}", self.block_flow.fragment) write!(f, "TableRowFlow: {}", self.block_flow.fragment)
} }
} }

View file

@ -202,6 +202,6 @@ impl Flow for TableRowGroupFlow {
impl fmt::Show for TableRowGroupFlow { impl fmt::Show for TableRowGroupFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "TableRowGroupFlow: {}", self.block_flow.fragment) write!(f, "TableRowGroupFlow: {}", self.block_flow.fragment)
} }
} }

View file

@ -196,9 +196,9 @@ impl Flow for TableWrapperFlow {
impl fmt::Show for TableWrapperFlow { impl fmt::Show for TableWrapperFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_float() { if self.is_float() {
write!(f.buf, "TableWrapperFlow(Float): {}", self.block_flow.fragment) write!(f, "TableWrapperFlow(Float): {}", self.block_flow.fragment)
} else { } else {
write!(f.buf, "TableWrapperFlow: {}", self.block_flow.fragment) write!(f, "TableWrapperFlow: {}", self.block_flow.fragment)
} }
} }
} }

View file

@ -131,7 +131,7 @@ impl TextRunScanner {
let mut new_line_pos = vec![]; let mut new_line_pos = vec![];
let (transformed_text, whitespace) = transform_text(*text, let (transformed_text, whitespace) = transform_text(text.as_slice(),
compression, compression,
last_whitespace, last_whitespace,
&mut new_line_pos); &mut new_line_pos);
@ -177,7 +177,7 @@ impl TextRunScanner {
// First, transform/compress text of all the nodes. // First, transform/compress text of all the nodes.
let mut last_whitespace_in_clump = new_whitespace; let mut last_whitespace_in_clump = new_whitespace;
let transformed_strs: Vec<~str> = Vec::from_fn(self.clump.length().to_uint(), |i| { let transformed_strs: Vec<String> = Vec::from_fn(self.clump.length().to_uint(), |i| {
// TODO(#113): We should be passing the compression context between calls to // TODO(#113): We should be passing the compression context between calls to
// `transform_text`, so that fragments starting and/or ending with whitespace can // `transform_text`, so that fragments starting and/or ending with whitespace can
// be compressed correctly with respect to the text run. // be compressed correctly with respect to the text run.
@ -189,7 +189,7 @@ impl TextRunScanner {
let mut new_line_pos = vec![]; let mut new_line_pos = vec![];
let (new_str, new_whitespace) = transform_text(*in_fragment, let (new_str, new_whitespace) = transform_text(in_fragment.as_slice(),
compression, compression,
last_whitespace_in_clump, last_whitespace_in_clump,
&mut new_line_pos); &mut new_line_pos);
@ -202,13 +202,13 @@ impl TextRunScanner {
// Next, concatenate all of the transformed strings together, saving the new // Next, concatenate all of the transformed strings together, saving the new
// character indices. // character indices.
let mut run_str = StrBuf::new(); let mut run_str = String::new();
let mut new_ranges: Vec<Range<CharIndex>> = vec![]; let mut new_ranges: Vec<Range<CharIndex>> = vec![];
let mut char_total = CharIndex(0); let mut char_total = CharIndex(0);
for i in range(0, transformed_strs.len() as int) { for i in range(0, transformed_strs.len() as int) {
let added_chars = CharIndex(transformed_strs.get(i as uint).char_len() as int); let added_chars = CharIndex(transformed_strs.get(i as uint).as_slice().char_len() as int);
new_ranges.push(Range::new(char_total, added_chars)); new_ranges.push(Range::new(char_total, added_chars));
run_str.push_str(*transformed_strs.get(i as uint)); run_str.push_str(transformed_strs.get(i as uint).as_slice());
char_total = char_total + added_chars; char_total = char_total + added_chars;
} }

View file

@ -13,7 +13,7 @@ use script::dom::bindings::js::JS;
use script::dom::bindings::utils::Reflectable; use script::dom::bindings::utils::Reflectable;
use script::dom::node::{Node, SharedLayoutData}; use script::dom::node::{Node, SharedLayoutData};
use script::layout_interface::{LayoutChan, UntrustedNodeAddress, TrustedNodeAddress}; use script::layout_interface::{LayoutChan, UntrustedNodeAddress, TrustedNodeAddress};
use std::cast; use std::mem;
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use style::ComputedValues; use style::ComputedValues;
use style; use style;
@ -76,20 +76,20 @@ pub trait LayoutDataAccess {
impl<'ln> LayoutDataAccess for LayoutNode<'ln> { impl<'ln> LayoutDataAccess for LayoutNode<'ln> {
#[inline(always)] #[inline(always)]
unsafe fn borrow_layout_data_unchecked(&self) -> *Option<LayoutDataWrapper> { unsafe fn borrow_layout_data_unchecked(&self) -> *Option<LayoutDataWrapper> {
cast::transmute(self.get().layout_data.borrow_unchecked()) mem::transmute(self.get().layout_data.borrow_unchecked())
} }
#[inline(always)] #[inline(always)]
fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> { fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> {
unsafe { unsafe {
cast::transmute(self.get().layout_data.borrow()) mem::transmute(self.get().layout_data.borrow())
} }
} }
#[inline(always)] #[inline(always)]
fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> { fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> {
unsafe { unsafe {
cast::transmute(self.get().layout_data.borrow_mut()) mem::transmute(self.get().layout_data.borrow_mut())
} }
} }
} }
@ -135,7 +135,7 @@ impl OpaqueNodeMethods for OpaqueNode {
fn from_jsmanaged(node: &JS<Node>) -> OpaqueNode { fn from_jsmanaged(node: &JS<Node>) -> OpaqueNode {
unsafe { unsafe {
let ptr: uintptr_t = cast::transmute(node.reflector().get_jsobject()); let ptr: uintptr_t = mem::transmute(node.reflector().get_jsobject());
OpaqueNode(ptr) OpaqueNode(ptr)
} }
} }
@ -143,7 +143,7 @@ impl OpaqueNodeMethods for OpaqueNode {
fn to_untrusted_node_address(&self) -> UntrustedNodeAddress { fn to_untrusted_node_address(&self) -> UntrustedNodeAddress {
unsafe { unsafe {
let OpaqueNode(addr) = *self; let OpaqueNode(addr) = *self;
let addr: UntrustedNodeAddress = cast::transmute(addr); let addr: UntrustedNodeAddress = mem::transmute(addr);
addr addr
} }
} }

View file

@ -50,9 +50,9 @@ use servo_msg::constellation_msg::{PipelineId, SubpageId};
use servo_util::namespace::Namespace; use servo_util::namespace::Namespace;
use servo_util::namespace; use servo_util::namespace;
use servo_util::str::is_whitespace; use servo_util::str::is_whitespace;
use std::cast;
use std::cell::{Ref, RefMut}; use std::cell::{Ref, RefMut};
use std::kinds::marker::ContravariantLifetime; use std::kinds::marker::ContravariantLifetime;
use std::mem;
use style::computed_values::{content, display, white_space}; use style::computed_values::{content, display, white_space};
use style::{AnyNamespace, AttrSelector, PropertyDeclarationBlock, SpecificNamespace, TElement}; use style::{AnyNamespace, AttrSelector, PropertyDeclarationBlock, SpecificNamespace, TElement};
use style::{TNode}; use style::{TNode};
@ -120,7 +120,7 @@ pub trait TLayoutNode {
/// If this is a text node, copies out the text. If this is not a text node, fails. /// If this is a text node, copies out the text. If this is not a text node, fails.
/// ///
/// FIXME(pcwalton): Don't copy text. Atomically reference count instead. /// FIXME(pcwalton): Don't copy text. Atomically reference count instead.
fn text(&self) -> ~str; fn text(&self) -> String;
/// Returns the first child of this node. /// Returns the first child of this node.
fn first_child(&self) -> Option<Self>; fn first_child(&self) -> Option<Self>;
@ -188,7 +188,7 @@ impl<'ln> TLayoutNode for LayoutNode<'ln> {
} }
} }
fn text(&self) -> ~str { fn text(&self) -> String {
unsafe { unsafe {
if !self.get().is_text() { if !self.get().is_text() {
fail!("not text!") fail!("not text!")
@ -257,7 +257,7 @@ impl<'ln> TNode<LayoutElement<'ln>> for LayoutNode<'ln> {
let elem: JS<Element> = self.node.transmute_copy(); let elem: JS<Element> = self.node.transmute_copy();
let element = &*elem.unsafe_get(); let element = &*elem.unsafe_get();
LayoutElement { LayoutElement {
element: cast::transmute_lifetime(element), element: mem::transmute(element),
} }
} }
} }
@ -396,16 +396,16 @@ impl<'le> TElement for LayoutElement<'le> {
} }
} }
fn get_content(content_list: &content::T) -> ~str { fn get_content(content_list: &content::T) -> String {
match *content_list { match *content_list {
content::Content(ref value) => { content::Content(ref value) => {
let iter = &mut value.clone().move_iter().peekable(); let iter = &mut value.clone().move_iter().peekable();
match iter.next() { match iter.next() {
Some(content::StringContent(content)) => content, Some(content::StringContent(content)) => content,
_ => "".to_owned(), _ => "".to_string(),
} }
} }
_ => "".to_owned(), _ => "".to_string(),
} }
} }
@ -455,7 +455,7 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
} }
unsafe fn get<'a>(&'a self) -> &'a Node { // this change. unsafe fn get<'a>(&'a self) -> &'a Node { // this change.
cast::transmute::<*mut Node,&'a Node>(self.get_jsmanaged().unsafe_get()) mem::transmute::<*mut Node,&'a Node>(self.get_jsmanaged().unsafe_get())
} }
fn first_child(&self) -> Option<ThreadSafeLayoutNode<'ln>> { fn first_child(&self) -> Option<ThreadSafeLayoutNode<'ln>> {
@ -478,7 +478,7 @@ impl<'ln> TLayoutNode for ThreadSafeLayoutNode<'ln> {
} }
} }
fn text(&self) -> ~str { fn text(&self) -> String {
if self.pseudo == Before || self.pseudo == After { if self.pseudo == Before || self.pseudo == After {
let layout_data_ref = self.borrow_layout_data(); let layout_data_ref = self.borrow_layout_data();
let node_layout_data_wrapper = layout_data_ref.get_ref(); let node_layout_data_wrapper = layout_data_ref.get_ref();
@ -595,7 +595,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
#[inline(always)] #[inline(always)]
pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> { pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> {
unsafe { unsafe {
cast::transmute(self.get().layout_data.borrow()) mem::transmute(self.get().layout_data.borrow())
} }
} }
@ -603,7 +603,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
#[inline(always)] #[inline(always)]
pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> { pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> {
unsafe { unsafe {
cast::transmute(self.get().layout_data.borrow_mut()) mem::transmute(self.get().layout_data.borrow_mut())
} }
} }
@ -639,7 +639,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
Some(TextNodeTypeId) => { Some(TextNodeTypeId) => {
unsafe { unsafe {
let text: JS<Text> = self.get_jsmanaged().transmute_copy(); let text: JS<Text> = self.get_jsmanaged().transmute_copy();
if !is_whitespace((*text.unsafe_get()).characterdata.data) { if !is_whitespace((*text.unsafe_get()).characterdata.data.as_slice()) {
return false return false
} }
@ -748,6 +748,6 @@ pub type UnsafeLayoutNode = (uint, uint);
pub fn layout_node_to_unsafe_layout_node(node: &LayoutNode) -> UnsafeLayoutNode { pub fn layout_node_to_unsafe_layout_node(node: &LayoutNode) -> UnsafeLayoutNode {
unsafe { unsafe {
cast::transmute_copy(node) mem::transmute_copy(node)
} }
} }

View file

@ -197,12 +197,12 @@ impl Pipeline {
} }
pub fn grant_paint_permission(&self) { pub fn grant_paint_permission(&self) {
self.render_chan.send_opt(PaintPermissionGranted); let _ = self.render_chan.send_opt(PaintPermissionGranted);
} }
pub fn revoke_paint_permission(&self) { pub fn revoke_paint_permission(&self) {
debug!("pipeline revoking render channel paint permission"); debug!("pipeline revoking render channel paint permission");
self.render_chan.send_opt(PaintPermissionRevoked); let _ = self.render_chan.send_opt(PaintPermissionRevoked);
} }
pub fn exit(&self) { pub fn exit(&self) {
@ -214,8 +214,8 @@ impl Pipeline {
if chan.send_opt(script_task::ExitPipelineMsg(self.id)).is_ok() { if chan.send_opt(script_task::ExitPipelineMsg(self.id)).is_ok() {
// Wait until all slave tasks have terminated and run destructors // Wait until all slave tasks have terminated and run destructors
// NOTE: We don't wait for script task as we don't always own it // NOTE: We don't wait for script task as we don't always own it
self.render_shutdown_port.recv_opt(); let _ = self.render_shutdown_port.recv_opt();
self.layout_shutdown_port.recv_opt(); let _ = self.layout_shutdown_port.recv_opt();
} }
} }

View file

@ -337,8 +337,8 @@ impl Window {
alert.add_prompt(); alert.add_prompt();
alert.run(); alert.run();
let value = alert.prompt_value(); let value = alert.prompt_value();
if "" == value { // To avoid crashing on Linux. if "" == value.as_slice() { // To avoid crashing on Linux.
self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_owned())) self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_string()))
} else { } else {
self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone())) self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone()))
} }

View file

@ -11,6 +11,8 @@
#[phase(syntax, link)] #[phase(syntax, link)]
extern crate log; extern crate log;
extern crate debug;
extern crate alert; extern crate alert;
extern crate azure; extern crate azure;
extern crate geom; extern crate geom;
@ -131,7 +133,7 @@ pub mod platform;
#[allow(dead_code)] #[allow(dead_code)]
fn start(argc: int, argv: **u8) -> int { fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() { native::start(argc, argv, proc() {
opts::from_cmdline_args(os::args()).map(run); opts::from_cmdline_args(os::args().as_slice()).map(run);
}) })
} }
@ -192,13 +194,13 @@ pub fn run(opts: opts::Opts) {
// Send the URL command to the constellation. // Send the URL command to the constellation.
for filename in opts.urls.iter() { for filename in opts.urls.iter() {
let url = if filename.starts_with("data:") { let url = if filename.as_slice().starts_with("data:") {
// As a hack for easier command-line testing, // As a hack for easier command-line testing,
// assume that data URLs are not URL-encoded. // assume that data URLs are not URL-encoded.
Url::new("data".to_owned(), None, "".to_owned(), None, Url::new("data".to_string(), None, "".to_string(), None,
filename.slice_from(5).to_owned(), vec!(), None) filename.as_slice().slice_from(5).to_string(), vec!(), None)
} else { } else {
parse_url(*filename, None) parse_url(filename.as_slice(), None)
}; };
let ConstellationChan(ref chan) = constellation_chan; let ConstellationChan(ref chan) = constellation_chan;

View file

@ -32,7 +32,7 @@ pub enum WindowEvent {
/// Sent when the window is resized. /// Sent when the window is resized.
ResizeWindowEvent(uint, uint), ResizeWindowEvent(uint, uint),
/// Sent when a new URL is to be loaded. /// Sent when a new URL is to be loaded.
LoadUrlWindowEvent(~str), LoadUrlWindowEvent(String),
/// Sent when a mouse hit test is to be performed. /// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent), MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move. /// Sent when a mouse move.

View file

@ -83,8 +83,7 @@ pub struct LayerId(pub uint, pub uint);
impl Show for LayerId { impl Show for LayerId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let LayerId(a, b) = *self; let LayerId(a, b) = *self;
write!(f.buf, "Layer({}, {})", a, b); write!(f, "Layer({}, {})", a, b)
Ok(())
} }
} }

View file

@ -8,12 +8,12 @@ use platform::surface::NativeSurfaceAzureMethods;
use azure::AzSkiaGrGLSharedSurfaceRef; use azure::AzSkiaGrGLSharedSurfaceRef;
use layers::platform::surface::NativeSurface; use layers::platform::surface::NativeSurface;
use std::cast; use std::mem;
impl NativeSurfaceAzureMethods for NativeSurface { impl NativeSurfaceAzureMethods for NativeSurface {
fn from_azure_surface(surface: AzSkiaGrGLSharedSurfaceRef) -> NativeSurface { fn from_azure_surface(surface: AzSkiaGrGLSharedSurfaceRef) -> NativeSurface {
unsafe { unsafe {
NativeSurface::from_pixmap(cast::transmute(surface)) NativeSurface::from_pixmap(mem::transmute(surface))
} }
} }
} }

View file

@ -10,13 +10,13 @@ use platform::surface::NativeSurfaceAzureMethods;
use azure::AzSkiaGrGLSharedSurfaceRef; use azure::AzSkiaGrGLSharedSurfaceRef;
use io_surface::IOSurface; use io_surface::IOSurface;
use layers::platform::surface::NativeSurface; use layers::platform::surface::NativeSurface;
use std::cast; use std::mem;
impl NativeSurfaceAzureMethods for NativeSurface { impl NativeSurfaceAzureMethods for NativeSurface {
fn from_azure_surface(surface: AzSkiaGrGLSharedSurfaceRef) -> NativeSurface { fn from_azure_surface(surface: AzSkiaGrGLSharedSurfaceRef) -> NativeSurface {
unsafe { unsafe {
let io_surface = IOSurface { let io_surface = IOSurface {
obj: cast::transmute(surface), obj: mem::transmute(surface),
}; };
NativeSurface::from_io_surface(io_surface) NativeSurface::from_io_surface(io_surface)
} }

View file

@ -20,21 +20,21 @@ pub fn factory() -> LoaderTask {
fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
let url = load_data.url; let url = load_data.url;
assert!("data" == url.scheme); assert!("data" == url.scheme.as_slice());
let mut metadata = Metadata::default(url.clone()); let mut metadata = Metadata::default(url.clone());
// Split out content type and data. // Split out content type and data.
let parts: ~[&str] = url.path.splitn(',', 1).collect(); let parts: Vec<&str> = url.path.as_slice().splitn(',', 1).collect();
if parts.len() != 2 { if parts.len() != 2 {
start_sending(start_chan, metadata).send(Done(Err("invalid data uri".to_owned()))); start_sending(start_chan, metadata).send(Done(Err("invalid data uri".to_string())));
return; return;
} }
// ";base64" must come at the end of the content type, per RFC 2397. // ";base64" must come at the end of the content type, per RFC 2397.
// rust-http will fail to parse it because there's no =value part. // rust-http will fail to parse it because there's no =value part.
let mut is_base64 = false; let mut is_base64 = false;
let mut ct_str = parts[0]; let mut ct_str = *parts.get(0);
if ct_str.ends_with(";base64") { if ct_str.ends_with(";base64") {
is_base64 = true; is_base64 = true;
ct_str = ct_str.slice_to(ct_str.as_bytes().len() - 7); ct_str = ct_str.slice_to(ct_str.as_bytes().len() - 7);
@ -48,12 +48,12 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
let progress_chan = start_sending(start_chan, metadata); let progress_chan = start_sending(start_chan, metadata);
if is_base64 { if is_base64 {
match parts[1].from_base64() { match (*parts.get(1)).from_base64() {
Err(..) => { Err(..) => {
progress_chan.send(Done(Err("non-base64 data uri".to_owned()))); progress_chan.send(Done(Err("non-base64 data uri".to_string())));
} }
Ok(data) => { Ok(data) => {
let data: ~[u8] = data; let data: Vec<u8> = data;
progress_chan.send(Payload(data.move_iter().collect())); progress_chan.send(Payload(data.move_iter().collect()));
progress_chan.send(Done(Ok(()))); progress_chan.send(Done(Ok(())));
} }
@ -61,7 +61,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
} else { } else {
// FIXME: Since the %-decoded URL is already a str, we can't // FIXME: Since the %-decoded URL is already a str, we can't
// handle UTF8-incompatible encodings. // handle UTF8-incompatible encodings.
let bytes: &[u8] = parts[1].as_bytes(); let bytes: &[u8] = (*parts.get(1)).as_bytes();
progress_chan.send(Payload(bytes.iter().map(|&x| x).collect())); progress_chan.send(Payload(bytes.iter().map(|&x| x).collect()));
progress_chan.send(Done(Ok(()))); progress_chan.send(Done(Ok(())));
} }
@ -69,8 +69,8 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
#[cfg(test)] #[cfg(test)]
fn assert_parse(url: &'static str, fn assert_parse(url: &'static str,
content_type: Option<(~str, ~str)>, content_type: Option<(String, String)>,
charset: Option<~str>, charset: Option<String>,
data: Option<Vec<u8>>) { data: Option<Vec<u8>>) {
use std::from_str::FromStr; use std::from_str::FromStr;
use std::comm; use std::comm;
@ -86,7 +86,7 @@ fn assert_parse(url: &'static str,
match data { match data {
None => { None => {
assert_eq!(progress, Done(Err("invalid data uri".to_owned()))); assert_eq!(progress, Done(Err("invalid data uri".to_string())));
} }
Some(dat) => { Some(dat) => {
assert_eq!(progress, Payload(dat)); assert_eq!(progress, Payload(dat));
@ -108,13 +108,13 @@ fn plain() {
#[test] #[test]
fn plain_ct() { fn plain_ct() {
assert_parse("data:text/plain,hello", assert_parse("data:text/plain,hello",
Some(("text".to_owned(), "plain".to_owned())), None, Some(bytes!("hello").iter().map(|&x| x).collect())); Some(("text".to_string(), "plain".to_string())), None, Some(bytes!("hello").iter().map(|&x| x).collect()));
} }
#[test] #[test]
fn plain_charset() { fn plain_charset() {
assert_parse("data:text/plain;charset=latin1,hello", assert_parse("data:text/plain;charset=latin1,hello",
Some(("text".to_owned(), "plain".to_owned())), Some("latin1".to_owned()), Some(bytes!("hello").iter().map(|&x| x).collect())); Some(("text".to_string(), "plain".to_string())), Some("latin1".to_string()), Some(bytes!("hello").iter().map(|&x| x).collect()));
} }
#[test] #[test]
@ -125,12 +125,12 @@ fn base64() {
#[test] #[test]
fn base64_ct() { fn base64_ct() {
assert_parse("data:application/octet-stream;base64,C62+7w==", assert_parse("data:application/octet-stream;base64,C62+7w==",
Some(("application".to_owned(), "octet-stream".to_owned())), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); Some(("application".to_string(), "octet-stream".to_string())), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF)));
} }
#[test] #[test]
fn base64_charset() { fn base64_charset() {
assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==",
Some(("text".to_owned(), "plain".to_owned())), Some("koi8-r".to_owned()), Some(("text".to_string(), "plain".to_string())), Some("koi8-r".to_string()),
Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4))); Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4)));
} }

View file

@ -12,14 +12,14 @@ use servo_util::task::spawn_named;
static READ_SIZE: uint = 1; static READ_SIZE: uint = 1;
fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>) fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>)
-> Result<(), ~str> { -> Result<(), String> {
loop { loop {
let mut buf = vec!(); let mut buf = vec!();
match reader.push_exact(&mut buf, READ_SIZE) { match reader.push_at_least(READ_SIZE, READ_SIZE, &mut buf) {
Ok(_) => progress_chan.send(Payload(buf)), Ok(_) => progress_chan.send(Payload(buf)),
Err(e) => match e.kind { Err(e) => match e.kind {
io::EndOfFile => return Ok(()), io::EndOfFile => return Ok(()),
_ => return Err(e.desc.to_owned()), _ => return Err(e.desc.to_string()),
} }
} }
} }
@ -28,7 +28,7 @@ fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>)
pub fn factory() -> LoaderTask { pub fn factory() -> LoaderTask {
let f: LoaderTask = proc(load_data, start_chan) { let f: LoaderTask = proc(load_data, start_chan) {
let url = load_data.url; let url = load_data.url;
assert!("file" == url.scheme); assert!("file" == url.scheme.as_slice());
let progress_chan = start_sending(start_chan, Metadata::default(url.clone())); let progress_chan = start_sending(start_chan, Metadata::default(url.clone()));
spawn_named("file_loader", proc() { spawn_named("file_loader", proc() {
match File::open_mode(&Path::new(url.path), io::Open, io::Read) { match File::open_mode(&Path::new(url.path), io::Open, io::Read) {
@ -37,7 +37,7 @@ pub fn factory() -> LoaderTask {
progress_chan.send(Done(res)); progress_chan.send(Done(res));
} }
Err(e) => { Err(e) => {
progress_chan.send(Done(Err(e.desc.to_owned()))); progress_chan.send(Done(Err(e.desc.to_string())));
} }
}; };
}); });

View file

@ -18,7 +18,7 @@ pub fn factory() -> LoaderTask {
f f
} }
fn send_error(url: Url, err: ~str, start_chan: Sender<LoadResponse>) { fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) {
start_sending(start_chan, Metadata::default(url)).send(Done(Err(err))); start_sending(start_chan, Metadata::default(url)).send(Done(Err(err)));
} }
@ -36,18 +36,18 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
iters = iters + 1; iters = iters + 1;
if iters > max_redirects { if iters > max_redirects {
send_error(url, "too many redirects".to_owned(), start_chan); send_error(url, "too many redirects".to_string(), start_chan);
return; return;
} }
if redirected_to.contains(&url) { if redirected_to.contains(&url) {
send_error(url, "redirect loop".to_owned(), start_chan); send_error(url, "redirect loop".to_string(), start_chan);
return; return;
} }
redirected_to.insert(url.clone()); redirected_to.insert(url.clone());
if "http" != url.scheme { if "http" != url.scheme.as_slice() {
let s = format!("{:s} request, but we don't support that scheme", url.scheme); let s = format!("{:s} request, but we don't support that scheme", url.scheme);
send_error(url, s, start_chan); send_error(url, s, start_chan);
return; return;
@ -59,7 +59,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
let mut writer = match request { let mut writer = match request {
Ok(w) => box w, Ok(w) => box w,
Err(e) => { Err(e) => {
send_error(url, e.desc.to_owned(), start_chan); send_error(url, e.desc.to_string(), start_chan);
return; return;
} }
}; };
@ -74,7 +74,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
writer.headers.content_length = Some(data.len()); writer.headers.content_length = Some(data.len());
match writer.write(data.clone().into_bytes().as_slice()) { match writer.write(data.clone().into_bytes().as_slice()) {
Err(e) => { Err(e) => {
send_error(url, e.desc.to_owned(), start_chan); send_error(url, e.desc.to_string(), start_chan);
return; return;
} }
_ => {} _ => {}
@ -85,7 +85,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
let mut response = match writer.read_response() { let mut response = match writer.read_response() {
Ok(r) => r, Ok(r) => r,
Err((_, e)) => { Err((_, e)) => {
send_error(url, e.desc.to_owned(), start_chan); send_error(url, e.desc.to_string(), start_chan);
return; return;
} }
}; };

View file

@ -41,6 +41,10 @@ fn byte_swap(color_type: png::ColorType, data: &mut [u8]) {
} }
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> { pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
if buffer.len() == 0 {
return None;
}
if png::is_png(buffer) { if png::is_png(buffer) {
match png::load_png_from_memory(buffer) { match png::load_png_from_memory(buffer) {
Ok(mut png_image) => { Ok(mut png_image) => {

View file

@ -7,7 +7,6 @@ use image_cache_task::{ImageReady, ImageNotReady, ImageFailed};
use local_image_cache::LocalImageCache; use local_image_cache::LocalImageCache;
use geom::size::Size2D; use geom::size::Size2D;
use std::cast;
use std::mem; use std::mem;
use std::ptr; use std::ptr;
use sync::{Arc, Mutex}; use sync::{Arc, Mutex};
@ -26,7 +25,7 @@ impl Drop for LocalImageCacheHandle {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
let _: Box<Arc<Mutex<Box<LocalImageCache>>>> = let _: Box<Arc<Mutex<Box<LocalImageCache>>>> =
cast::transmute(mem::replace(&mut self.data, ptr::null())); mem::transmute(mem::replace(&mut self.data, ptr::null()));
} }
} }
} }
@ -34,7 +33,7 @@ impl Drop for LocalImageCacheHandle {
impl Clone for LocalImageCacheHandle { impl Clone for LocalImageCacheHandle {
fn clone(&self) -> LocalImageCacheHandle { fn clone(&self) -> LocalImageCacheHandle {
unsafe { unsafe {
let handle = cast::transmute::<&Arc<Mutex<Box<LocalImageCache>>>,&Arc<*()>>(self.get()); let handle = mem::transmute::<&Arc<Mutex<Box<LocalImageCache>>>,&Arc<*()>>(self.get());
let new_handle = (*handle).clone(); let new_handle = (*handle).clone();
LocalImageCacheHandle::new(new_handle) LocalImageCacheHandle::new(new_handle)
} }
@ -44,13 +43,13 @@ impl Clone for LocalImageCacheHandle {
impl LocalImageCacheHandle { impl LocalImageCacheHandle {
pub unsafe fn new(cache: Arc<*()>) -> LocalImageCacheHandle { pub unsafe fn new(cache: Arc<*()>) -> LocalImageCacheHandle {
LocalImageCacheHandle { LocalImageCacheHandle {
data: cast::transmute(box cache), data: mem::transmute(box cache),
} }
} }
pub fn get<'a>(&'a self) -> &'a Arc<Mutex<Box<LocalImageCache>>> { pub fn get<'a>(&'a self) -> &'a Arc<Mutex<Box<LocalImageCache>>> {
unsafe { unsafe {
cast::transmute::<*uint,&'a Arc<Mutex<Box<LocalImageCache>>>>(self.data) mem::transmute::<*uint,&'a Arc<Mutex<Box<LocalImageCache>>>>(self.data)
} }
} }
} }

View file

@ -36,7 +36,7 @@ pub enum Msg {
// FIXME: We can probably get rid of this Cell now // FIXME: We can probably get rid of this Cell now
/// Used be the prefetch tasks to post back image binaries /// Used be the prefetch tasks to post back image binaries
StorePrefetchedImageData(Url, Result<~[u8], ()>), StorePrefetchedImageData(Url, Result<Vec<u8>, ()>),
/// Used by the decoder tasks to post decoded images back to the cache /// Used by the decoder tasks to post decoded images back to the cache
StoreImage(Url, Option<Arc<Box<Image>>>), StoreImage(Url, Option<Arc<Box<Image>>>),
@ -147,7 +147,7 @@ struct ImageCache {
enum ImageState { enum ImageState {
Init, Init,
Prefetching(AfterPrefetch), Prefetching(AfterPrefetch),
Prefetched(~[u8]), Prefetched(Vec<u8>),
Decoding, Decoding,
Decoded(Arc<Box<Image>>), Decoded(Arc<Box<Image>>),
Failed Failed
@ -270,7 +270,7 @@ impl ImageCache {
} }
} }
fn store_prefetched_image_data(&mut self, url: Url, data: Result<~[u8], ()>) { fn store_prefetched_image_data(&mut self, url: Url, data: Result<Vec<u8>, ()>) {
match self.get_state(url.clone()) { match self.get_state(url.clone()) {
Prefetching(next_step) => { Prefetching(next_step) => {
match data { match data {
@ -318,7 +318,7 @@ impl ImageCache {
spawn(proc() { spawn(proc() {
let url = url_clone; let url = url_clone;
debug!("image_cache_task: started image decode for {:s}", url.to_str()); debug!("image_cache_task: started image decode for {:s}", url.to_str());
let image = load_from_memory(data); let image = load_from_memory(data.as_slice());
let image = if image.is_some() { let image = if image.is_some() {
Some(Arc::new(box image.unwrap())) Some(Arc::new(box image.unwrap()))
} else { } else {
@ -452,7 +452,7 @@ impl ImageCacheTask {
} }
} }
fn load_image_data(url: Url, resource_task: ResourceTask) -> Result<~[u8], ()> { fn load_image_data(url: Url, resource_task: ResourceTask) -> Result<Vec<u8>, ()> {
let (response_chan, response_port) = channel(); let (response_chan, response_port) = channel();
resource_task.send(resource_task::Load(LoadData::new(url), response_chan)); resource_task.send(resource_task::Load(LoadData::new(url), response_chan));
@ -533,7 +533,7 @@ mod tests {
impl Closure for SendTestImageErr { impl Closure for SendTestImageErr {
fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) {
response.send(resource_task::Payload(test_image_bin())); response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Err("".to_owned()))); response.send(resource_task::Done(Err("".to_string())));
} }
} }
@ -559,7 +559,7 @@ mod tests {
// the image // the image
self.wait_port.recv(); self.wait_port.recv();
response.send(resource_task::Payload(test_image_bin())); response.send(resource_task::Payload(test_image_bin()));
response.send(resource_task::Done(Err("".to_owned()))); response.send(resource_task::Done(Err("".to_string())));
} }
} }
@ -767,7 +767,7 @@ mod tests {
resource_task::Load(_, response) => { resource_task::Load(_, response) => {
let chan = start_sending(response, Metadata::default(parse_url("file:///fake", None))); let chan = start_sending(response, Metadata::default(parse_url("file:///fake", None)));
chan.send(resource_task::Payload(test_image_bin())); chan.send(resource_task::Payload(test_image_bin()));
chan.send(resource_task::Done(Err("".to_owned()))); chan.send(resource_task::Done(Err("".to_string())));
image_bin_sent_chan.send(()); image_bin_sent_chan.send(());
} }
resource_task::Exit => { resource_task::Exit => {

View file

@ -9,6 +9,7 @@
#![feature(default_type_params, globs, managed_boxes, phase)] #![feature(default_type_params, globs, managed_boxes, phase)]
extern crate debug;
extern crate collections; extern crate collections;
extern crate geom; extern crate geom;
extern crate http; extern crate http;

View file

@ -33,7 +33,7 @@ pub struct LoadData {
pub url: Url, pub url: Url,
pub method: Method, pub method: Method,
pub headers: RequestHeaderCollection, pub headers: RequestHeaderCollection,
pub data: Option<~str> pub data: Option<String>
} }
impl LoadData { impl LoadData {
@ -53,10 +53,10 @@ pub struct Metadata {
pub final_url: Url, pub final_url: Url,
/// MIME type / subtype. /// MIME type / subtype.
pub content_type: Option<(~str, ~str)>, pub content_type: Option<(String, String)>,
/// Character set. /// Character set.
pub charset: Option<~str>, pub charset: Option<String>,
/// Headers /// Headers
pub headers: Option<ResponseHeaderCollection>, pub headers: Option<ResponseHeaderCollection>,
@ -84,10 +84,10 @@ impl Metadata {
Some(MediaType { type_: ref type_, Some(MediaType { type_: ref type_,
subtype: ref subtype, subtype: ref subtype,
parameters: ref parameters }) => { parameters: ref parameters }) => {
self.content_type = Some((type_.as_slice().to_owned(), subtype.as_slice().to_owned())); self.content_type = Some((type_.clone(), subtype.clone()));
for &(ref k, ref v) in parameters.iter() { for &(ref k, ref v) in parameters.iter() {
if "charset" == k.as_slice() { if "charset" == k.as_slice() {
self.charset = Some(v.as_slice().to_owned()); self.charset = Some(v.clone());
} }
} }
} }
@ -113,7 +113,7 @@ pub enum ProgressMsg {
/// Binary data - there may be multiple of these /// Binary data - there may be multiple of these
Payload(Vec<u8>), Payload(Vec<u8>),
/// Indicates loading is complete, either successfully or not /// Indicates loading is complete, either successfully or not
Done(Result<(), ~str>) Done(Result<(), String>)
} }
/// For use by loaders in responding to a Load message. /// For use by loaders in responding to a Load message.
@ -128,7 +128,7 @@ pub fn start_sending(start_chan: Sender<LoadResponse>, metadata: Metadata) -> Se
/// Convenience function for synchronously loading a whole resource. /// Convenience function for synchronously loading a whole resource.
pub fn load_whole_resource(resource_task: &ResourceTask, url: Url) pub fn load_whole_resource(resource_task: &ResourceTask, url: Url)
-> Result<(Metadata, Vec<u8>), ~str> { -> Result<(Metadata, Vec<u8>), String> {
let (start_chan, start_port) = channel(); let (start_chan, start_port) = channel();
resource_task.send(Load(LoadData::new(url), start_chan)); resource_task.send(Load(LoadData::new(url), start_chan));
let response = start_port.recv(); let response = start_port.recv();
@ -159,14 +159,14 @@ type LoaderTaskFactory = extern "Rust" fn() -> LoaderTask;
/// Create a ResourceTask with the default loaders /// Create a ResourceTask with the default loaders
pub fn ResourceTask() -> ResourceTask { pub fn ResourceTask() -> ResourceTask {
let loaders = vec!( let loaders = vec!(
("file".to_owned(), file_loader::factory), ("file".to_string(), file_loader::factory),
("http".to_owned(), http_loader::factory), ("http".to_string(), http_loader::factory),
("data".to_owned(), data_loader::factory), ("data".to_string(), data_loader::factory),
); );
create_resource_task_with_loaders(loaders) create_resource_task_with_loaders(loaders)
} }
fn create_resource_task_with_loaders(loaders: Vec<(~str, LoaderTaskFactory)>) -> ResourceTask { fn create_resource_task_with_loaders(loaders: Vec<(String, LoaderTaskFactory)>) -> ResourceTask {
let (setup_chan, setup_port) = channel(); let (setup_chan, setup_port) = channel();
let builder = TaskBuilder::new().named("ResourceManager"); let builder = TaskBuilder::new().named("ResourceManager");
builder.spawn(proc() { builder.spawn(proc() {
@ -180,12 +180,12 @@ fn create_resource_task_with_loaders(loaders: Vec<(~str, LoaderTaskFactory)>) ->
struct ResourceManager { struct ResourceManager {
from_client: Receiver<ControlMsg>, from_client: Receiver<ControlMsg>,
/// Per-scheme resource loaders /// Per-scheme resource loaders
loaders: Vec<(~str, LoaderTaskFactory)>, loaders: Vec<(String, LoaderTaskFactory)>,
} }
fn ResourceManager(from_client: Receiver<ControlMsg>, fn ResourceManager(from_client: Receiver<ControlMsg>,
loaders: Vec<(~str, LoaderTaskFactory)>) -> ResourceManager { loaders: Vec<(String, LoaderTaskFactory)>) -> ResourceManager {
ResourceManager { ResourceManager {
from_client : from_client, from_client : from_client,
loaders : loaders, loaders : loaders,
@ -215,7 +215,7 @@ impl ResourceManager {
} }
None => { None => {
debug!("resource_task: no loader for scheme {:s}", load_data.url.scheme); debug!("resource_task: no loader for scheme {:s}", load_data.url.scheme);
start_sending(start_chan, Metadata::default(load_data.url)).send(Done(Err("no loader for scheme".to_owned()))); start_sending(start_chan, Metadata::default(load_data.url)).send(Done(Err("no loader for scheme".to_string())));
} }
} }
} }
@ -268,7 +268,7 @@ fn snicklefritz_loader_factory() -> LoaderTask {
#[test] #[test]
fn should_delegate_to_scheme_loader() { fn should_delegate_to_scheme_loader() {
let loader_factories = vec!(("snicklefritz".to_owned(), snicklefritz_loader_factory)); let loader_factories = vec!(("snicklefritz".to_string(), snicklefritz_loader_factory));
let resource_task = create_resource_task_with_loaders(loader_factories); let resource_task = create_resource_task_with_loaders(loader_factories);
let (start_chan, start) = channel(); let (start_chan, start) = channel();
resource_task.send(Load(LoadData::new(FromStr::from_str("snicklefritz://heya").unwrap()), start_chan)); resource_task.send(Load(LoadData::new(FromStr::from_str("snicklefritz://heya").unwrap()), start_chan));

View file

@ -120,7 +120,7 @@ impl<'a> AttrMethods for JSRef<'a, Attr> {
fn GetNamespaceURI(&self) -> Option<DOMString> { fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.namespace.to_str() { match self.namespace.to_str() {
"" => None, "" => None,
url => Some(url.to_owned()), url => Some(url.to_string()),
} }
} }

View file

@ -641,7 +641,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().to_owned()" value = "str::from_utf8(data).unwrap().to_string()"
if type.nullable(): if type.nullable():
value = "Some(%s)" % value value = "Some(%s)" % value
@ -691,7 +691,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None,
" Ok(None) => { %(handleInvalidEnumValueCode)s },\n" " Ok(None) => { %(handleInvalidEnumValueCode)s },\n"
" Ok(Some(index)) => {\n" " Ok(Some(index)) => {\n"
" //XXXjdm need some range checks up in here.\n" " //XXXjdm need some range checks up in here.\n"
" unsafe { cast::transmute(index) }\n" " unsafe { mem::transmute(index) }\n"
" },\n" " },\n"
"}" % { "values" : enum + "Values::strings", "}" % { "values" : enum + "Values::strings",
"exceptionCode" : exceptionCode, "exceptionCode" : exceptionCode,
@ -2130,7 +2130,7 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod):
trace: Some(%s) trace: Some(%s)
}; };
js_info.dom_static.proxy_handlers.insert(PrototypeList::id::%s as uint, js_info.dom_static.proxy_handlers.insert(PrototypeList::id::%s as uint,
CreateProxyHandler(&traps, cast::transmute(&Class))); CreateProxyHandler(&traps, mem::transmute(&Class)));
""" % (FINALIZE_HOOK_NAME, """ % (FINALIZE_HOOK_NAME,
TRACE_HOOK_NAME, TRACE_HOOK_NAME,
@ -2673,7 +2673,7 @@ pub static strings: &'static [&'static str] = &[
impl ToJSValConvertible for valuelist { impl ToJSValConvertible for valuelist {
fn to_jsval(&self, cx: *mut JSContext) -> JSVal { fn to_jsval(&self, cx: *mut JSContext) -> JSVal {
strings[*self as uint].to_owned().to_jsval(cx) strings[*self as uint].to_string().to_jsval(cx)
} }
} }
""" % (",\n ".join(map(getEnumValueName, enum.values())), """ % (",\n ".join(map(getEnumValueName, enum.values())),
@ -3821,7 +3821,7 @@ class CGAbstractClassHook(CGAbstractExternMethod):
def finalizeHook(descriptor, hookName, context): def finalizeHook(descriptor, hookName, context):
release = """let val = JS_GetReservedSlot(obj, dom_object_slot(obj)); release = """let val = JS_GetReservedSlot(obj, dom_object_slot(obj));
let _: Box<%s> = cast::transmute(val.to_private()); let _: Box<%s> = mem::transmute(val.to_private());
debug!("%s finalize: {:p}", this); debug!("%s finalize: {:p}", this);
""" % (descriptor.concreteType, descriptor.concreteType) """ % (descriptor.concreteType, descriptor.concreteType)
return release return release
@ -4343,7 +4343,7 @@ class CGBindingRoot(CGThing):
'script_task::JSPageInfo', 'script_task::JSPageInfo',
'libc', 'libc',
'servo_util::str::DOMString', 'servo_util::str::DOMString',
'std::cast', 'std::mem',
'std::cmp', 'std::cmp',
'std::ptr', 'std::ptr',
'std::str', 'std::str',

View file

@ -17,9 +17,7 @@ from CodegenRust import GlobalGenRoots, replaceFileIfChanged
# import Codegen in general, so we can set a variable on it # import Codegen in general, so we can set a variable on it
import Codegen import Codegen
def generate_file(config, name): def generate_file(config, name, filename):
filename = name + '.rs'
root = getattr(GlobalGenRoots, name)(config) root = getattr(GlobalGenRoots, name)(config)
code = root.define() code = root.define()
@ -65,21 +63,21 @@ def main():
config = Configuration(configFile, parserResults) config = Configuration(configFile, parserResults)
# Generate the prototype list. # Generate the prototype list.
generate_file(config, 'PrototypeList') generate_file(config, 'PrototypeList', 'PrototypeList.rs')
# Generate the common code. # Generate the common code.
generate_file(config, 'RegisterBindings') generate_file(config, 'RegisterBindings', 'RegisterBindings.rs')
# Generate the type list. # Generate the type list.
generate_file(config, 'InterfaceTypes') generate_file(config, 'InterfaceTypes', 'InterfaceTypes.rs')
# Generate the type list. # Generate the type list.
generate_file(config, 'InheritTypes') generate_file(config, 'InheritTypes', 'InheritTypes.rs')
# Generate the module declarations. # Generate the module declarations.
generate_file(config, 'Bindings') generate_file(config, 'Bindings', 'Bindings/mod.rs')
generate_file(config, 'UnionTypes') generate_file(config, 'UnionTypes', 'UnionTypes.rs')
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -60,7 +60,7 @@ impl ToJSValConvertible for JSVal {
unsafe fn convert_from_jsval<T: Default>( unsafe fn convert_from_jsval<T: Default>(
cx: *mut JSContext, value: JSVal, cx: *mut JSContext, value: JSVal,
convert_fn: extern "C" unsafe fn(*mut JSContext, JSVal, *mut T) -> JSBool) -> Result<T, ()> { convert_fn: unsafe extern "C" fn(*mut JSContext, JSVal, *mut T) -> JSBool) -> Result<T, ()> {
let mut ret = Default::default(); let mut ret = Default::default();
if convert_fn(cx, value, &mut ret) == 0 { if convert_fn(cx, value, &mut ret) == 0 {
Err(()) Err(())
@ -243,7 +243,7 @@ impl Default for StringificationBehavior {
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 == Empty && value.is_null() { if nullBehavior == Empty && value.is_null() {
Ok("".to_owned()) Ok("".to_string())
} 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

@ -46,9 +46,9 @@ use js::jsapi::{JSObject, JS_AddObjectRoot, JS_RemoveObjectRoot};
use layout_interface::TrustedNodeAddress; use layout_interface::TrustedNodeAddress;
use script_task::StackRoots; use script_task::StackRoots;
use std::cast;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::kinds::marker::ContravariantLifetime; use std::kinds::marker::ContravariantLifetime;
use std::mem;
/// A type that represents a JS-owned value that is rooted for the lifetime of this value. /// A type that represents a JS-owned value that is rooted for the lifetime of this value.
/// Importantly, it requires explicit rooting in order to interact with the inner value. /// Importantly, it requires explicit rooting in order to interact with the inner value.
@ -105,7 +105,7 @@ impl<T: Reflectable> Temporary<T> {
//XXXjdm It would be lovely if this could be private. //XXXjdm It would be lovely if this could be private.
pub unsafe fn transmute<To>(self) -> Temporary<To> { pub unsafe fn transmute<To>(self) -> Temporary<To> {
cast::transmute(self) mem::transmute(self)
} }
} }
@ -195,7 +195,7 @@ impl<T: Reflectable> JS<T> {
/// flags. This is the only method that be safely accessed from layout. (The fact that this /// flags. This is the only method that be safely accessed from layout. (The fact that this
/// is unsafe is what necessitates the layout wrappers.) /// is unsafe is what necessitates the layout wrappers.)
pub unsafe fn unsafe_get(&self) -> *mut T { pub unsafe fn unsafe_get(&self) -> *mut T {
cast::transmute_copy(&self.ptr) mem::transmute_copy(&self.ptr)
} }
/// Store an unrooted value in this field. This is safe under the assumption that JS<T> /// Store an unrooted value in this field. This is safe under the assumption that JS<T>
@ -209,11 +209,11 @@ impl<T: Reflectable> JS<T> {
impl<From, To> JS<From> { impl<From, To> JS<From> {
//XXXjdm It would be lovely if this could be private. //XXXjdm It would be lovely if this could be private.
pub unsafe fn transmute(self) -> JS<To> { pub unsafe fn transmute(self) -> JS<To> {
cast::transmute(self) mem::transmute(self)
} }
pub unsafe fn transmute_copy(&self) -> JS<To> { pub unsafe fn transmute_copy(&self) -> JS<To> {
cast::transmute_copy(self) mem::transmute_copy(self)
} }
} }
@ -492,12 +492,12 @@ impl<'a, T> Eq for JSRef<'a, T> {
impl<'a,T> JSRef<'a,T> { impl<'a,T> JSRef<'a,T> {
//XXXjdm It would be lovely if this could be private. //XXXjdm It would be lovely if this could be private.
pub unsafe fn transmute<'b, To>(&'b self) -> &'b JSRef<'a, To> { pub unsafe fn transmute<'b, To>(&'b self) -> &'b JSRef<'a, To> {
cast::transmute(self) mem::transmute(self)
} }
//XXXjdm It would be lovely if this could be private. //XXXjdm It would be lovely if this could be private.
pub unsafe fn transmute_mut<'b, To>(&'b mut self) -> &'b mut JSRef<'a, To> { pub unsafe fn transmute_mut<'b, To>(&'b mut self) -> &'b mut JSRef<'a, To> {
cast::transmute(self) mem::transmute(self)
} }
pub fn unrooted(&self) -> JS<T> { pub fn unrooted(&self) -> JS<T> {

View file

@ -14,7 +14,7 @@ use js::glue::InvokeGetOwnPropertyDescriptor;
use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED}; use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED};
use libc; use libc;
use std::cast; use std::mem;
use std::ptr; use std::ptr;
use std::str; use std::str;
use std::mem::size_of; use std::mem::size_of;
@ -39,7 +39,7 @@ pub extern fn getPropertyDescriptor(cx: *mut JSContext, proxy: *mut JSObject, id
return 1; return 1;
} }
JS_GetPropertyDescriptorById(cx, proto, id, JSRESOLVE_QUALIFIED, cast::transmute(desc)) JS_GetPropertyDescriptorById(cx, proto, id, JSRESOLVE_QUALIFIED, mem::transmute(desc))
} }
} }
@ -47,8 +47,8 @@ pub fn defineProperty_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
desc: *JSPropertyDescriptor) -> JSBool { desc: *JSPropertyDescriptor) -> JSBool {
unsafe { unsafe {
//FIXME: Workaround for https://github.com/mozilla/rust/issues/13385 //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
let setter: *libc::c_void = cast::transmute((*desc).setter); let setter: *libc::c_void = mem::transmute((*desc).setter);
let setter_stub: *libc::c_void = cast::transmute(JS_StrictPropertyStub); let setter_stub: *libc::c_void = mem::transmute(JS_StrictPropertyStub);
if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub { if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub {
/*return JS_ReportErrorFlagsAndNumber(cx, /*return JS_ReportErrorFlagsAndNumber(cx,
JSREPORT_WARNING | JSREPORT_STRICT | JSREPORT_WARNING | JSREPORT_STRICT |
@ -82,7 +82,8 @@ pub fn _obj_toString(cx: *mut JSContext, className: *libc::c_char) -> *mut JSStr
return ptr::mut_null(); return ptr::mut_null();
} }
let result = "[object ".to_owned() + name + "]"; let result = format!("[object {}]", name);
let result = result.as_slice();
for (i, c) in result.chars().enumerate() { for (i, c) in result.chars().enumerate() {
*chars.offset(i as int) = c as jschar; *chars.offset(i as int) = c as jschar;
} }

View file

@ -9,7 +9,7 @@ use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSTRACE_OBJECT};
use js::jsval::JSVal; use js::jsval::JSVal;
use libc; use libc;
use std::cast; use std::mem;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use serialize::{Encodable, Encoder}; use serialize::{Encodable, Encoder};
@ -20,7 +20,7 @@ use serialize::{Encodable, Encoder};
fn get_jstracer<'a, S: Encoder<E>, E>(s: &'a mut S) -> &'a mut JSTracer { fn get_jstracer<'a, S: Encoder<E>, E>(s: &'a mut S) -> &'a mut JSTracer {
unsafe { unsafe {
cast::transmute(s) mem::transmute(s)
} }
} }

View file

@ -14,7 +14,7 @@ use servo_util::str::DOMString;
use collections::hashmap::HashMap; use collections::hashmap::HashMap;
use libc; use libc;
use libc::c_uint; use libc::c_uint;
use std::cast; use std::mem;
use std::cmp::Eq; use std::cmp::Eq;
use std::ptr; use std::ptr;
use std::ptr::null; use std::ptr::null;
@ -141,7 +141,7 @@ pub fn unwrap_jsmanaged<T: Reflectable>(mut obj: *mut JSObject,
} }
pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *T { pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *T {
cast::transmute(x) mem::transmute(x)
} }
pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString {

View file

@ -66,11 +66,11 @@ 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.slice(offset as uint, count as uint).to_str()) Ok(self.data.as_slice().slice(offset as uint, count as uint).to_str())
} }
fn AppendData(&mut self, arg: DOMString) -> ErrorResult { fn AppendData(&mut self, arg: DOMString) -> ErrorResult {
self.data = self.data + arg; self.data.push_str(arg.as_slice());
Ok(()) Ok(())
} }
@ -79,7 +79,7 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> {
} }
fn DeleteData(&mut self, offset: u32, count: u32) -> ErrorResult { fn DeleteData(&mut self, offset: u32, count: u32) -> ErrorResult {
self.ReplaceData(offset, count, "".to_owned()) self.ReplaceData(offset, count, "".to_string())
} }
fn ReplaceData(&mut self, offset: u32, count: u32, arg: DOMString) -> ErrorResult { fn ReplaceData(&mut self, offset: u32, count: u32, arg: DOMString) -> ErrorResult {
@ -92,9 +92,9 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> {
} else { } else {
count count
}; };
let mut data = self.data.slice(0, offset as uint).to_strbuf(); let mut data = self.data.as_slice().slice(0, offset as uint).to_string();
data.push_str(arg); data.push_str(arg.as_slice());
data.push_str(self.data.slice((offset + count) as uint, length as uint)); data.push_str(self.data.as_slice().slice((offset + count) as uint, length as uint));
self.data = data.into_owned(); self.data = data.into_owned();
// FIXME: Once we have `Range`, we should implement step7 to step11 // FIXME: Once we have `Range`, we should implement step7 to step11
Ok(()) Ok(())

View file

@ -219,16 +219,16 @@ 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
HTMLDocument => "text/html".to_owned(), HTMLDocument => "text/html".to_string(),
// http://dom.spec.whatwg.org/#concept-document-content-type // http://dom.spec.whatwg.org/#concept-document-content-type
NonHTMLDocument => "application/xml".to_owned() NonHTMLDocument => "application/xml".to_string()
} }
}, },
url: Untraceable::new(url), url: Untraceable::new(url),
// http://dom.spec.whatwg.org/#concept-document-quirks // http://dom.spec.whatwg.org/#concept-document-quirks
quirks_mode: Untraceable::new(NoQuirks), quirks_mode: Untraceable::new(NoQuirks),
// http://dom.spec.whatwg.org/#concept-document-encoding // http://dom.spec.whatwg.org/#concept-document-encoding
encoding_name: "utf-8".to_owned(), encoding_name: "utf-8".to_string(),
is_html_document: is_html_document == HTMLDocument, is_html_document: is_html_document == HTMLDocument,
} }
} }
@ -355,14 +355,14 @@ 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 { match *self.quirks_mode {
NoQuirks => "CSS1Compat".to_owned(), NoQuirks => "CSS1Compat".to_string(),
LimitedQuirks | FullQuirks => "BackCompat".to_owned() LimitedQuirks | FullQuirks => "BackCompat".to_string()
} }
} }
// http://dom.spec.whatwg.org/#dom-document-characterset // http://dom.spec.whatwg.org/#dom-document-characterset
fn CharacterSet(&self) -> DOMString { fn CharacterSet(&self) -> DOMString {
self.encoding_name.to_ascii_lower() self.encoding_name.as_slice().to_ascii_lower()
} }
// http://dom.spec.whatwg.org/#dom-document-content_type // http://dom.spec.whatwg.org/#dom-document-content_type
@ -398,7 +398,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let namespace = match maybe_ns { let namespace = match maybe_ns {
Some(namespace) => Namespace::from_str(namespace), Some(namespace) => Namespace::from_str(namespace.as_slice()),
None => Null None => Null
}; };
HTMLCollection::by_tag_name_ns(&*window, NodeCast::from_ref(self), tag_name, namespace) HTMLCollection::by_tag_name_ns(&*window, NodeCast::from_ref(self), tag_name, namespace)
@ -421,11 +421,11 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
// http://dom.spec.whatwg.org/#dom-document-createelement // http://dom.spec.whatwg.org/#dom-document-createelement
fn CreateElement(&self, local_name: DOMString) -> Fallible<Temporary<Element>> { fn CreateElement(&self, local_name: DOMString) -> Fallible<Temporary<Element>> {
if xml_name_type(local_name) == InvalidXMLName { if xml_name_type(local_name.as_slice()) == InvalidXMLName {
debug!("Not a valid element name"); debug!("Not a valid element name");
return Err(InvalidCharacter); return Err(InvalidCharacter);
} }
let local_name = local_name.to_ascii_lower(); let local_name = local_name.as_slice().to_ascii_lower();
Ok(build_element_from_tag(local_name, self)) Ok(build_element_from_tag(local_name, self))
} }
@ -434,7 +434,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
namespace: Option<DOMString>, namespace: Option<DOMString>,
qualified_name: DOMString) -> Fallible<Temporary<Element>> { qualified_name: DOMString) -> Fallible<Temporary<Element>> {
let ns = Namespace::from_str(null_str_as_empty_ref(&namespace)); let ns = Namespace::from_str(null_str_as_empty_ref(&namespace));
match xml_name_type(qualified_name) { match xml_name_type(qualified_name.as_slice()) {
InvalidXMLName => { InvalidXMLName => {
debug!("Not a valid element name"); debug!("Not a valid element name");
return Err(InvalidCharacter); return Err(InvalidCharacter);
@ -454,12 +454,12 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
return Err(NamespaceError); return Err(NamespaceError);
}, },
// throw if prefix is "xml" and namespace is not the XML namespace // throw if prefix is "xml" and namespace is not the XML namespace
(_, Some(ref prefix), _) if "xml" == *prefix && ns != namespace::XML => { (_, Some(ref prefix), _) if "xml" == prefix.as_slice() && ns != namespace::XML => {
debug!("Namespace must be the xml namespace if the prefix is 'xml'"); debug!("Namespace must be the xml namespace if the prefix is 'xml'");
return Err(NamespaceError); return Err(NamespaceError);
}, },
// throw if namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns" // throw if namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"
(&namespace::XMLNS, Some(ref prefix), _) if "xmlns" == *prefix => {}, (&namespace::XMLNS, Some(ref prefix), _) if "xmlns" == prefix.as_slice() => {},
(&namespace::XMLNS, _, "xmlns") => {}, (&namespace::XMLNS, _, "xmlns") => {},
(&namespace::XMLNS, _, _) => { (&namespace::XMLNS, _, _) => {
debug!("The prefix or the qualified name must be 'xmlns' if namespace is the XMLNS namespace "); debug!("The prefix or the qualified name must be 'xmlns' if namespace is the XMLNS namespace ");
@ -495,12 +495,12 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
fn CreateProcessingInstruction(&self, target: DOMString, fn CreateProcessingInstruction(&self, target: DOMString,
data: DOMString) -> Fallible<Temporary<ProcessingInstruction>> { data: DOMString) -> Fallible<Temporary<ProcessingInstruction>> {
// Step 1. // Step 1.
if xml_name_type(target) == InvalidXMLName { if xml_name_type(target.as_slice()) == InvalidXMLName {
return Err(InvalidCharacter); return Err(InvalidCharacter);
} }
// Step 2. // Step 2.
if data.contains("?>") { if data.as_slice().contains("?>") {
return Err(InvalidCharacter); return Err(InvalidCharacter);
} }
@ -542,7 +542,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
fn CreateEvent(&self, interface: DOMString) -> Fallible<Temporary<Event>> { fn CreateEvent(&self, interface: DOMString) -> Fallible<Temporary<Event>> {
let window = self.window.root(); let window = self.window.root();
match interface.to_ascii_lower().as_slice() { match interface.as_slice().to_ascii_lower().as_slice() {
// FIXME: Implement CustomEvent (http://dom.spec.whatwg.org/#customevent) // FIXME: Implement CustomEvent (http://dom.spec.whatwg.org/#customevent)
"uievents" | "uievent" => Ok(EventCast::from_temporary(UIEvent::new_uninitialized(&*window))), "uievents" | "uievent" => Ok(EventCast::from_temporary(UIEvent::new_uninitialized(&*window))),
"mouseevents" | "mouseevent" => Ok(EventCast::from_temporary(MouseEvent::new_uninitialized(&*window))), "mouseevents" | "mouseevent" => Ok(EventCast::from_temporary(MouseEvent::new_uninitialized(&*window))),
@ -554,7 +554,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
// http://www.whatwg.org/specs/web-apps/current-work/#document.title // http://www.whatwg.org/specs/web-apps/current-work/#document.title
fn Title(&self) -> DOMString { fn Title(&self) -> DOMString {
let mut title = StrBuf::new(); let mut title = String::new();
self.GetDocumentElement().root().map(|root| { self.GetDocumentElement().root().map(|root| {
let root: &JSRef<Node> = NodeCast::from_ref(&*root); let root: &JSRef<Node> = NodeCast::from_ref(&*root);
root.traverse_preorder() root.traverse_preorder()
@ -570,7 +570,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
}); });
let v: Vec<&str> = title.as_slice().words().collect(); let v: Vec<&str> = title.as_slice().words().collect();
let title = v.connect(" "); let title = v.connect(" ");
title.trim().to_owned() title.as_slice().trim().to_string()
} }
// http://www.whatwg.org/specs/web-apps/current-work/#document.title // http://www.whatwg.org/specs/web-apps/current-work/#document.title
@ -595,7 +595,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
assert!(title_node.AppendChild(NodeCast::from_ref(&*new_text)).is_ok()); assert!(title_node.AppendChild(NodeCast::from_ref(&*new_text)).is_ok());
}, },
None => { None => {
let new_title = HTMLTitleElement::new("title".to_owned(), self).root(); let new_title = HTMLTitleElement::new("title".to_string(), self).root();
let new_title: &JSRef<Node> = NodeCast::from_ref(&*new_title); let new_title: &JSRef<Node> = NodeCast::from_ref(&*new_title);
let new_text = self.CreateTextNode(title.clone()).root(); let new_text = self.CreateTextNode(title.clone()).root();
@ -691,7 +691,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap(); let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
element.get_attribute(Null, "name").root().map_or(false, |mut attr| { element.get_attribute(Null, "name").root().map_or(false, |mut attr| {
attr.value_ref() == name attr.value_ref() == name.as_slice()
}) })
}) })
} }
@ -703,7 +703,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct ImagesFilter; struct ImagesFilter;
impl CollectionFilter for ImagesFilter { impl CollectionFilter for ImagesFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"img" == elem.deref().local_name "img" == elem.deref().local_name.as_slice()
} }
} }
let filter = box ImagesFilter; let filter = box ImagesFilter;
@ -717,7 +717,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct EmbedsFilter; struct EmbedsFilter;
impl CollectionFilter for EmbedsFilter { impl CollectionFilter for EmbedsFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"embed" == elem.deref().local_name "embed" == elem.deref().local_name.as_slice()
} }
} }
let filter = box EmbedsFilter; let filter = box EmbedsFilter;
@ -736,7 +736,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct LinksFilter; struct LinksFilter;
impl CollectionFilter for LinksFilter { impl CollectionFilter for LinksFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
("a" == elem.deref().local_name || "area" == elem.deref().local_name) && ("a" == elem.deref().local_name.as_slice() || "area" == elem.deref().local_name.as_slice()) &&
elem.get_attribute(Null, "href").is_some() elem.get_attribute(Null, "href").is_some()
} }
} }
@ -751,7 +751,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct FormsFilter; struct FormsFilter;
impl CollectionFilter for FormsFilter { impl CollectionFilter for FormsFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"form" == elem.deref().local_name "form" == elem.deref().local_name.as_slice()
} }
} }
let filter = box FormsFilter; let filter = box FormsFilter;
@ -765,7 +765,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct ScriptsFilter; struct ScriptsFilter;
impl CollectionFilter for ScriptsFilter { impl CollectionFilter for ScriptsFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"script" == elem.deref().local_name "script" == elem.deref().local_name.as_slice()
} }
} }
let filter = box ScriptsFilter; let filter = box ScriptsFilter;
@ -779,7 +779,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct AnchorsFilter; struct AnchorsFilter;
impl CollectionFilter for AnchorsFilter { impl CollectionFilter for AnchorsFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"a" == elem.deref().local_name && elem.get_attribute(Null, "name").is_some() "a" == elem.deref().local_name.as_slice() && elem.get_attribute(Null, "name").is_some()
} }
} }
let filter = box AnchorsFilter; let filter = box AnchorsFilter;
@ -793,7 +793,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
struct AppletsFilter; struct AppletsFilter;
impl CollectionFilter for AppletsFilter { impl CollectionFilter for AppletsFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"applet" == elem.deref().local_name "applet" == elem.deref().local_name.as_slice()
} }
} }
let filter = box AppletsFilter; let filter = box AppletsFilter;

View file

@ -34,8 +34,8 @@ impl DocumentType {
DocumentType { DocumentType {
node: Node::new_inherited(DoctypeNodeTypeId, document), node: Node::new_inherited(DoctypeNodeTypeId, document),
name: name, name: name,
public_id: public_id.unwrap_or("".to_owned()), public_id: public_id.unwrap_or("".to_string()),
system_id: system_id.unwrap_or("".to_owned()) system_id: system_id.unwrap_or("".to_string())
} }
} }

View file

@ -112,27 +112,27 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> {
// http://dom.spec.whatwg.org/#error-names-0 // http://dom.spec.whatwg.org/#error-names-0
fn Message(&self) -> DOMString { fn Message(&self) -> DOMString {
match self.code { match self.code {
IndexSizeError => "The index is not in the allowed range.".to_owned(), IndexSizeError => "The index is not in the allowed range.".to_string(),
HierarchyRequestError => "The operation would yield an incorrect node tree.".to_owned(), HierarchyRequestError => "The operation would yield an incorrect node tree.".to_string(),
WrongDocumentError => "The object is in the wrong document.".to_owned(), WrongDocumentError => "The object is in the wrong document.".to_string(),
InvalidCharacterError => "The string contains invalid characters.".to_owned(), InvalidCharacterError => "The string contains invalid characters.".to_string(),
NoModificationAllowedError => "The object can not be modified.".to_owned(), NoModificationAllowedError => "The object can not be modified.".to_string(),
NotFoundError => "The object can not be found here.".to_owned(), NotFoundError => "The object can not be found here.".to_string(),
NotSupportedError => "The operation is not supported.".to_owned(), NotSupportedError => "The operation is not supported.".to_string(),
InvalidStateError => "The object is in an invalid state.".to_owned(), InvalidStateError => "The object is in an invalid state.".to_string(),
SyntaxError => "The string did not match the expected pattern.".to_owned(), SyntaxError => "The string did not match the expected pattern.".to_string(),
InvalidModificationError => "The object can not be modified in this way.".to_owned(), InvalidModificationError => "The object can not be modified in this way.".to_string(),
NamespaceError => "The operation is not allowed by Namespaces in XML.".to_owned(), NamespaceError => "The operation is not allowed by Namespaces in XML.".to_string(),
InvalidAccessError => "The object does not support the operation or argument.".to_owned(), InvalidAccessError => "The object does not support the operation or argument.".to_string(),
SecurityError => "The operation is insecure.".to_owned(), SecurityError => "The operation is insecure.".to_string(),
NetworkError => "A network error occurred.".to_owned(), NetworkError => "A network error occurred.".to_string(),
AbortError => "The operation was aborted.".to_owned(), AbortError => "The operation was aborted.".to_string(),
URLMismatchError => "The given URL does not match another URL.".to_owned(), URLMismatchError => "The given URL does not match another URL.".to_string(),
QuotaExceededError => "The quota has been exceeded.".to_owned(), QuotaExceededError => "The quota has been exceeded.".to_string(),
TimeoutError => "The operation timed out.".to_owned(), TimeoutError => "The operation timed out.".to_string(),
InvalidNodeTypeError => "The supplied node is incorrect or has an incorrect ancestor for this operation.".to_owned(), InvalidNodeTypeError => "The supplied node is incorrect or has an incorrect ancestor for this operation.".to_string(),
DataCloneError => "The object can not be cloned.".to_owned(), DataCloneError => "The object can not be cloned.".to_string(),
EncodingError => "The encoding operation (either encoded or decoding) failed.".to_owned() EncodingError => "The encoding operation (either encoded or decoding) failed.".to_string()
} }
} }
} }

View file

@ -60,7 +60,7 @@ pub trait DOMImplementationMethods {
impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
// http://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype // http://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype
fn CreateDocumentType(&self, qname: DOMString, pubid: DOMString, sysid: DOMString) -> Fallible<Temporary<DocumentType>> { fn CreateDocumentType(&self, qname: DOMString, pubid: DOMString, sysid: DOMString) -> Fallible<Temporary<DocumentType>> {
match xml_name_type(qname) { match xml_name_type(qname.as_slice()) {
// Step 1. // Step 1.
InvalidXMLName => Err(InvalidCharacter), InvalidXMLName => Err(InvalidCharacter),
// Step 2. // Step 2.
@ -129,19 +129,19 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
{ {
// Step 3. // Step 3.
let doc_type = DocumentType::new("html".to_owned(), None, None, &*doc).root(); let doc_type = DocumentType::new("html".to_string(), None, None, &*doc).root();
assert!(doc_node.AppendChild(NodeCast::from_ref(&*doc_type)).is_ok()); assert!(doc_node.AppendChild(NodeCast::from_ref(&*doc_type)).is_ok());
} }
{ {
// Step 4. // Step 4.
let doc_html: Root<Node> = NodeCast::from_temporary(HTMLHtmlElement::new("html".to_owned(), &*doc)).root(); let doc_html: Root<Node> = NodeCast::from_temporary(HTMLHtmlElement::new("html".to_string(), &*doc)).root();
let doc_html = doc_html.deref(); let doc_html = doc_html.deref();
assert!(doc_node.AppendChild(doc_html).is_ok()); assert!(doc_node.AppendChild(doc_html).is_ok());
{ {
// Step 5. // Step 5.
let doc_head: Root<Node> = NodeCast::from_temporary(HTMLHeadElement::new("head".to_owned(), &*doc)).root(); let doc_head: Root<Node> = NodeCast::from_temporary(HTMLHeadElement::new("head".to_string(), &*doc)).root();
let doc_head = doc_head.deref(); let doc_head = doc_head.deref();
assert!(doc_html.AppendChild(doc_head).is_ok()); assert!(doc_html.AppendChild(doc_head).is_ok());
@ -150,7 +150,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".to_owned(), &*doc)).root(); let doc_title: Root<Node> = NodeCast::from_temporary(HTMLTitleElement::new("title".to_string(), &*doc)).root();
let doc_title = doc_title.deref(); let doc_title = doc_title.deref();
assert!(doc_head.AppendChild(doc_title).is_ok()); assert!(doc_head.AppendChild(doc_title).is_ok());
@ -163,7 +163,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
} }
// Step 7. // Step 7.
let doc_body: Root<HTMLBodyElement> = HTMLBodyElement::new("body".to_owned(), &*doc).root(); let doc_body: Root<HTMLBodyElement> = HTMLBodyElement::new("body".to_string(), &*doc).root();
let doc_body = doc_body.deref(); let doc_body = doc_body.deref();
assert!(doc_html.AppendChild(NodeCast::from_ref(doc_body)).is_ok()); assert!(doc_html.AppendChild(NodeCast::from_ref(doc_body)).is_ok());
} }

View file

@ -48,10 +48,10 @@ impl<'a> DOMParserMethods for JSRef<'a, DOMParser> {
let owner = self.owner.root(); let owner = self.owner.root();
match ty { match ty {
Text_html => { Text_html => {
Ok(Document::new(&owner.root_ref(), None, HTMLDocument, Some("text/html".to_owned()))) Ok(Document::new(&owner.root_ref(), None, HTMLDocument, Some("text/html".to_string())))
} }
Text_xml => { Text_xml => {
Ok(Document::new(&owner.root_ref(), None, NonHTMLDocument, Some("text/xml".to_owned()))) Ok(Document::new(&owner.root_ref(), None, NonHTMLDocument, Some("text/xml".to_string())))
} }
_ => { _ => {
Err(FailureUnknown) Err(FailureUnknown)

View file

@ -30,8 +30,8 @@ use servo_util::namespace::{Namespace, Null};
use servo_util::str::{DOMString, null_str_as_empty_ref, split_html_space_chars}; use servo_util::str::{DOMString, null_str_as_empty_ref, split_html_space_chars};
use std::ascii::StrAsciiExt; use std::ascii::StrAsciiExt;
use std::cast;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use std::mem;
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct Element { pub struct Element {
@ -168,13 +168,13 @@ impl RawLayoutElementHelpers for Element {
unsafe fn get_attr_val_for_layout(&self, namespace: &Namespace, name: &str) unsafe fn get_attr_val_for_layout(&self, namespace: &Namespace, name: &str)
-> Option<&'static str> { -> Option<&'static str> {
// cast to point to T in RefCell<T> directly // cast to point to T in RefCell<T> directly
let attrs: *Vec<JS<Attr>> = cast::transmute(&self.attrs); let attrs: *Vec<JS<Attr>> = mem::transmute(&self.attrs);
(*attrs).iter().find(|attr: & &JS<Attr>| { (*attrs).iter().find(|attr: & &JS<Attr>| {
let attr = attr.unsafe_get(); let attr = attr.unsafe_get();
name == (*attr).local_name && (*attr).namespace == *namespace name == (*attr).local_name.as_slice() && (*attr).namespace == *namespace
}).map(|attr| { }).map(|attr| {
let attr = attr.unsafe_get(); let attr = attr.unsafe_get();
cast::transmute((*attr).value.as_slice()) mem::transmute((*attr).value.as_slice())
}) })
} }
} }
@ -238,7 +238,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
let same_name = if is_html_element { let same_name = if is_html_element {
name.to_ascii_lower() == attr.local_name name.to_ascii_lower() == attr.local_name
} else { } else {
name == attr.local_name name == attr.local_name.as_slice()
}; };
same_name && attr.namespace == namespace same_name && attr.namespace == namespace
@ -274,7 +274,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
let position: |&JSRef<Attr>| -> bool = let position: |&JSRef<Attr>| -> bool =
if self.html_element_in_html_document() { if self.html_element_in_html_document() {
|attr| attr.deref().local_name.eq_ignore_ascii_case(local_name) |attr| attr.deref().local_name.as_slice().eq_ignore_ascii_case(local_name.as_slice())
} else { } else {
|attr| attr.deref().local_name == local_name |attr| attr.deref().local_name == local_name
}; };
@ -345,7 +345,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn has_class(&self, name: &str) -> bool { fn has_class(&self, name: &str) -> bool {
let class_names = self.get_string_attribute("class"); let class_names = self.get_string_attribute("class");
let mut classes = split_html_space_chars(class_names); let mut classes = split_html_space_chars(class_names.as_slice());
classes.any(|class| name == class) classes.any(|class| name == class)
} }
@ -363,17 +363,17 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
let x = x.root(); let x = x.root();
x.deref().Value() x.deref().Value()
} }
None => "".to_owned() None => "".to_string()
} }
} }
fn set_string_attribute(&self, name: &str, value: DOMString) { fn set_string_attribute(&self, name: &str, value: DOMString) {
assert!(name == name.to_ascii_lower()); assert!(name == name.to_ascii_lower().as_slice());
assert!(self.set_attribute(Null, name.to_owned(), value).is_ok()); assert!(self.set_attribute(Null, name.to_string(), value).is_ok());
} }
fn set_uint_attribute(&self, name: &str, value: u32) { fn set_uint_attribute(&self, name: &str, value: u32) {
assert!(name == name.to_ascii_lower()); assert!(name == name.to_ascii_lower().as_slice());
assert!(self.set_attribute(Null, name.to_owned(), value.to_str()).is_ok()); assert!(self.set_attribute(Null, name.to_string(), value.to_str()).is_ok());
} }
} }
@ -425,7 +425,7 @@ pub trait ElementMethods {
impl<'a> ElementMethods for JSRef<'a, Element> { impl<'a> ElementMethods for JSRef<'a, Element> {
// http://dom.spec.whatwg.org/#dom-element-namespaceuri // http://dom.spec.whatwg.org/#dom-element-namespaceuri
fn NamespaceURI(&self) -> DOMString { fn NamespaceURI(&self) -> DOMString {
self.namespace.to_str().to_owned() self.namespace.to_str().to_string()
} }
fn LocalName(&self) -> DOMString { fn LocalName(&self) -> DOMString {
@ -441,10 +441,11 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn TagName(&self) -> DOMString { fn TagName(&self) -> DOMString {
match self.prefix { match self.prefix {
None => { None => {
self.local_name.to_ascii_upper() self.local_name.as_slice().to_ascii_upper()
} }
Some(ref prefix_str) => { Some(ref prefix_str) => {
(*prefix_str + ":" + self.local_name).to_ascii_upper() let s = format!("{}:{}", prefix_str, self.local_name);
s.as_slice().to_ascii_upper()
} }
} }
} }
@ -489,11 +490,11 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
// http://dom.spec.whatwg.org/#dom-element-getattribute // http://dom.spec.whatwg.org/#dom-element-getattribute
fn GetAttribute(&self, name: DOMString) -> Option<DOMString> { fn GetAttribute(&self, name: DOMString) -> Option<DOMString> {
let name = if self.html_element_in_html_document() { let name = if self.html_element_in_html_document() {
name.to_ascii_lower() name.as_slice().to_ascii_lower()
} else { } else {
name name
}; };
self.get_attribute(Null, name).root() self.get_attribute(Null, name.as_slice()).root()
.map(|s| s.deref().Value()) .map(|s| s.deref().Value())
} }
@ -502,7 +503,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
namespace: Option<DOMString>, namespace: Option<DOMString>,
local_name: DOMString) -> Option<DOMString> { local_name: DOMString) -> Option<DOMString> {
let namespace = Namespace::from_str(null_str_as_empty_ref(&namespace)); let namespace = Namespace::from_str(null_str_as_empty_ref(&namespace));
self.get_attribute(namespace, local_name).root() self.get_attribute(namespace, local_name.as_slice()).root()
.map(|attr| attr.deref().Value()) .map(|attr| attr.deref().Value())
} }
@ -516,14 +517,14 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
} }
// Step 1. // Step 1.
match xml_name_type(name) { match xml_name_type(name.as_slice()) {
InvalidXMLName => return Err(InvalidCharacter), InvalidXMLName => return Err(InvalidCharacter),
_ => {} _ => {}
} }
// Step 2. // Step 2.
let name = if self.html_element_in_html_document() { let name = if self.html_element_in_html_document() {
name.to_ascii_lower() name.as_slice().to_ascii_lower()
} else { } else {
name name
}; };
@ -548,7 +549,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
// Step 1. // Step 1.
let namespace = Namespace::from_str(null_str_as_empty_ref(&namespace_url)); let namespace = Namespace::from_str(null_str_as_empty_ref(&namespace_url));
let name_type = xml_name_type(name); let name_type = xml_name_type(name.as_slice());
match name_type { match name_type {
// Step 2. // Step 2.
InvalidXMLName => return Err(InvalidCharacter), InvalidXMLName => return Err(InvalidCharacter),
@ -580,12 +581,12 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
} }
// Step 7a. // Step 7a.
if "xmlns" == name && namespace != namespace::XMLNS { if "xmlns" == name.as_slice() && namespace != namespace::XMLNS {
return Err(NamespaceError); return Err(NamespaceError);
} }
// Step 8. // Step 8.
if namespace == namespace::XMLNS && "xmlns" != name && Some("xmlns".to_owned()) != prefix { if namespace == namespace::XMLNS && "xmlns" != name.as_slice() && Some("xmlns".to_string()) != prefix {
return Err(NamespaceError); return Err(NamespaceError);
} }
@ -601,7 +602,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn RemoveAttribute(&self, fn RemoveAttribute(&self,
name: DOMString) -> ErrorResult { name: DOMString) -> ErrorResult {
let name = if self.html_element_in_html_document() { let name = if self.html_element_in_html_document() {
name.to_ascii_lower() name.as_slice().to_ascii_lower()
} else { } else {
name name
}; };
@ -637,7 +638,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>, fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>,
localname: DOMString) -> Temporary<HTMLCollection> { localname: DOMString) -> Temporary<HTMLCollection> {
let namespace = match maybe_ns { let namespace = match maybe_ns {
Some(namespace) => Namespace::from_str(namespace), Some(namespace) => Namespace::from_str(namespace.as_slice()),
None => Null None => Null
}; };
let window = window_from_node(self).root(); let window = window_from_node(self).root();
@ -700,12 +701,12 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
} }
} }
pub fn get_attribute_parts(name: DOMString) -> (Option<~str>, ~str) { pub fn get_attribute_parts(name: DOMString) -> (Option<String>, String) {
//FIXME: Throw for XML-invalid names //FIXME: Throw for XML-invalid names
//FIXME: Throw for XMLNS-invalid names //FIXME: Throw for XMLNS-invalid names
let (prefix, local_name) = if name.contains(":") { let (prefix, local_name) = if name.as_slice().contains(":") {
let mut parts = name.splitn(':', 1); let mut parts = name.as_slice().splitn(':', 1);
(Some(parts.next().unwrap().to_owned()), parts.next().unwrap().to_owned()) (Some(parts.next().unwrap().to_string()), parts.next().unwrap().to_string())
} else { } else {
(None, name) (None, name)
}; };
@ -729,7 +730,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
"style" => { "style" => {
let doc = document_from_node(self).root(); let doc = document_from_node(self).root();
let base_url = doc.deref().url().clone(); let base_url = doc.deref().url().clone();
self.deref_mut().style_attribute = Some(style::parse_style_attribute(value, &base_url)) self.deref_mut().style_attribute = Some(style::parse_style_attribute(value.as_slice(), &base_url))
} }
"id" => { "id" => {
let node: &JSRef<Node> = NodeCast::from_ref(self); let node: &JSRef<Node> = NodeCast::from_ref(self);

View file

@ -70,7 +70,7 @@ impl Event {
current_target: Cell::new(None), current_target: Cell::new(None),
target: Cell::new(None), target: Cell::new(None),
phase: PhaseNone, phase: PhaseNone,
type_: "".to_owned(), type_: "".to_string(),
canceled: false, canceled: false,
cancelable: true, cancelable: true,
bubbles: false, bubbles: false,

View file

@ -44,7 +44,7 @@ pub fn dispatch_event<'a, 'b>(target: &JSRef<'a, EventTarget>,
/* capturing */ /* capturing */
for cur_target in chain.as_slice().iter().rev() { for cur_target in chain.as_slice().iter().rev() {
let stopped = match cur_target.get_listeners_for(type_, Capturing) { let stopped = match cur_target.get_listeners_for(type_.as_slice(), Capturing) {
Some(listeners) => { Some(listeners) => {
event.current_target.assign(Some(cur_target.deref().clone())); event.current_target.assign(Some(cur_target.deref().clone()));
for listener in listeners.iter() { for listener in listeners.iter() {
@ -74,7 +74,7 @@ pub fn dispatch_event<'a, 'b>(target: &JSRef<'a, EventTarget>,
event.current_target.assign(Some(target.clone())); event.current_target.assign(Some(target.clone()));
} }
let opt_listeners = target.deref().get_listeners(type_); let opt_listeners = target.deref().get_listeners(type_.as_slice());
for listeners in opt_listeners.iter() { for listeners in opt_listeners.iter() {
for listener in listeners.iter() { for listener in listeners.iter() {
// Explicitly drop any exception on the floor. // Explicitly drop any exception on the floor.
@ -92,7 +92,7 @@ pub fn dispatch_event<'a, 'b>(target: &JSRef<'a, EventTarget>,
event.deref_mut().phase = PhaseBubbling; event.deref_mut().phase = PhaseBubbling;
for cur_target in chain.iter() { for cur_target in chain.iter() {
let stopped = match cur_target.deref().get_listeners_for(type_, Bubbling) { let stopped = match cur_target.deref().get_listeners_for(type_.as_slice(), Bubbling) {
Some(listeners) => { Some(listeners) => {
event.deref_mut().current_target.assign(Some(cur_target.deref().clone())); event.deref_mut().current_target.assign(Some(cur_target.deref().clone()));
for listener in listeners.iter() { for listener in listeners.iter() {

View file

@ -192,11 +192,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.to_owned(), event_listener); self.set_inline_event_listener(ty.to_string(), 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.to_owned()); let listener = self.get_inline_event_listener(ty.to_string());
listener.map(|listener| CallbackContainer::new(listener.parent.callback())) listener.map(|listener| CallbackContainer::new(listener.parent.callback()))
} }
} }

View file

@ -54,7 +54,7 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> {
fn Append(&mut self, name: DOMString, value: &JSRef<Blob>, filename: Option<DOMString>) { fn Append(&mut self, name: DOMString, value: &JSRef<Blob>, filename: Option<DOMString>) {
let blob = BlobData { let blob = BlobData {
blob: value.unrooted(), blob: value.unrooted(),
name: filename.unwrap_or("default".to_owned()) name: filename.unwrap_or("default".to_string())
}; };
self.data.insert(name.clone(), blob); self.data.insert(name.clone(), blob);
} }

View file

@ -50,7 +50,7 @@ trait PrivateHTMLAnchorElementHelpers {
impl<'a> PrivateHTMLAnchorElementHelpers for JSRef<'a, HTMLAnchorElement> { impl<'a> PrivateHTMLAnchorElementHelpers for JSRef<'a, HTMLAnchorElement> {
fn handle_event_impl(&self, event: &JSRef<Event>) { fn handle_event_impl(&self, event: &JSRef<Event>) {
if "click" == event.Type() && !event.DefaultPrevented() { if "click" == event.Type().as_slice() && !event.DefaultPrevented() {
let element: &JSRef<Element> = ElementCast::from_ref(self); let element: &JSRef<Element> = ElementCast::from_ref(self);
let attr = element.get_attribute(Null, "href").root(); let attr = element.get_attribute(Null, "href").root();
match attr { match attr {

View file

@ -70,7 +70,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> {
_ => (), _ => (),
} }
if name.starts_with("on") { if name.as_slice().starts_with("on") {
static forwarded_events: &'static [&'static str] = static forwarded_events: &'static [&'static str] =
&["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint", &["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint",
"onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage",
@ -87,7 +87,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> {
EventTargetCast::from_mut_ref(self) EventTargetCast::from_mut_ref(self)
}; };
evtarget.set_event_handler_uncompiled(cx, url, reflector, evtarget.set_event_handler_uncompiled(cx, url, reflector,
name.slice_from(2).to_owned(), name.as_slice().slice_from(2),
value); value);
} }
} }

View file

@ -99,11 +99,11 @@ impl HTMLCollection {
} }
impl CollectionFilter for ClassNameFilter { impl CollectionFilter for ClassNameFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
self.classes.iter().all(|class| elem.has_class(*class)) self.classes.iter().all(|class| elem.has_class(class.as_slice()))
} }
} }
let filter = ClassNameFilter { let filter = ClassNameFilter {
classes: split_html_space_chars(classes).map(|class| class.into_owned()).collect() classes: split_html_space_chars(classes.as_slice()).map(|class| class.into_owned()).collect()
}; };
HTMLCollection::create(window, root, box filter) HTMLCollection::create(window, root, box filter)
} }

View file

@ -46,7 +46,7 @@ impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> {
struct HTMLDataListOptionsFilter; struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter { impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool { fn filter(&self, elem: &JSRef<Element>, _root: &JSRef<Node>) -> bool {
"option" == elem.deref().local_name "option" == elem.deref().local_name.as_slice()
} }
} }
let node: &JSRef<Node> = NodeCast::from_ref(self); let node: &JSRef<Node> = NodeCast::from_ref(self);

View file

@ -52,7 +52,7 @@ impl<'a> HTMLFieldSetElementMethods for JSRef<'a, HTMLFieldSetElement> {
static tag_names: StaticStringVec = &["button", "fieldset", "input", static tag_names: StaticStringVec = &["button", "fieldset", "input",
"keygen", "object", "output", "select", "textarea"]; "keygen", "object", "output", "select", "textarea"];
let root: &JSRef<Element> = ElementCast::to_ref(root).unwrap(); let root: &JSRef<Element> = ElementCast::to_ref(root).unwrap();
elem != root && tag_names.iter().any(|&tag_name| tag_name == elem.deref().local_name) elem != root && tag_names.iter().any(|&tag_name| tag_name == elem.deref().local_name.as_slice())
} }
} }
let node: &JSRef<Node> = NodeCast::from_ref(self); let node: &JSRef<Node> = NodeCast::from_ref(self);

View file

@ -133,9 +133,9 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLIFrameElement> {
_ => (), _ => (),
} }
if "sandbox" == name { if "sandbox" == name.as_slice() {
let mut modes = AllowNothing as u8; let mut modes = AllowNothing as u8;
for word in value.split(' ') { for word in value.as_slice().split(' ') {
modes |= match word.to_ascii_lower().as_slice() { modes |= match word.to_ascii_lower().as_slice() {
"allow-same-origin" => AllowSameOrigin, "allow-same-origin" => AllowSameOrigin,
"allow-forms" => AllowForms, "allow-forms" => AllowForms,
@ -156,7 +156,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLIFrameElement> {
_ => (), _ => (),
} }
if "sandbox" == name { if "sandbox" == name.as_slice() {
self.deref_mut().sandbox = None; self.deref_mut().sandbox = None;
} }
} }

View file

@ -49,7 +49,7 @@ impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
*self.image = None; *self.image = None;
} }
Some(src) => { Some(src) => {
let img_url = parse_url(src, url); let img_url = parse_url(src.as_slice(), url);
*self.image = Some(img_url.clone()); *self.image = Some(img_url.clone());
// inform the image cache to load this, but don't store a // inform the image cache to load this, but don't store a
@ -147,7 +147,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
fn IsMap(&self) -> bool { fn IsMap(&self) -> bool {
let element: &JSRef<Element> = ElementCast::from_ref(self); let element: &JSRef<Element> = ElementCast::from_ref(self);
from_str::<bool>(element.get_string_attribute("hspace")).unwrap() from_str::<bool>(element.get_string_attribute("hspace").as_slice()).unwrap()
} }
fn SetIsMap(&self, is_map: bool) { fn SetIsMap(&self, is_map: bool) {
@ -199,7 +199,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
fn Hspace(&self) -> u32 { fn Hspace(&self) -> u32 {
let element: &JSRef<Element> = ElementCast::from_ref(self); let element: &JSRef<Element> = ElementCast::from_ref(self);
from_str::<u32>(element.get_string_attribute("hspace")).unwrap() from_str::<u32>(element.get_string_attribute("hspace").as_slice()).unwrap()
} }
fn SetHspace(&self, hspace: u32) { fn SetHspace(&self, hspace: u32) {
@ -209,7 +209,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
fn Vspace(&self) -> u32 { fn Vspace(&self) -> u32 {
let element: &JSRef<Element> = ElementCast::from_ref(self); let element: &JSRef<Element> = ElementCast::from_ref(self);
from_str::<u32>(element.get_string_attribute("vspace")).unwrap() from_str::<u32>(element.get_string_attribute("vspace").as_slice()).unwrap()
} }
fn SetVspace(&self, vspace: u32) { fn SetVspace(&self, vspace: u32) {
@ -250,7 +250,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
_ => (), _ => (),
} }
if "src" == name { if "src" == name.as_slice() {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let url = Some(window.deref().get_url()); let url = Some(window.deref().get_url());
self.update_image(Some(value), url); self.update_image(Some(value), url);
@ -263,7 +263,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
_ => (), _ => (),
} }
if "src" == name { if "src" == name.as_slice() {
self.update_image(None, None); self.update_image(None, None);
} }
} }

View file

@ -0,0 +1,40 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLMainElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLMainElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::element::HTMLMainElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLMainElement {
pub htmlelement: HTMLElement
}
impl HTMLMainElementDerived for EventTarget {
fn is_htmlmainelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLMainElementTypeId))
}
}
impl HTMLMainElement {
pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLMainElement {
HTMLMainElement {
htmlelement: HTMLElement::new_inherited(HTMLMainElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLMainElement> {
let element = HTMLMainElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLMainElementBinding::Wrap)
}
}
pub trait HTMLMainElementMethods {
}

View file

@ -62,8 +62,8 @@ impl<'a> ProcessDataURL for JSRef<'a, HTMLObjectElement> {
match (elem.get_attribute(Null, "type").map(|x| x.root().Value()), match (elem.get_attribute(Null, "type").map(|x| x.root().Value()),
elem.get_attribute(Null, "data").map(|x| x.root().Value())) { elem.get_attribute(Null, "data").map(|x| x.root().Value())) {
(None, Some(uri)) => { (None, Some(uri)) => {
if is_image_data(uri) { if is_image_data(uri.as_slice()) {
let data_url = parse_url(uri, url); let data_url = parse_url(uri.as_slice(), url);
// Issue #84 // Issue #84
image_cache.send(image_cache_task::Prefetch(data_url)); image_cache.send(image_cache_task::Prefetch(data_url));
} }
@ -96,7 +96,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> {
_ => (), _ => (),
} }
if "data" == name { if "data" == name.as_slice() {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let url = Some(window.deref().get_url()); let url = Some(window.deref().get_url());
self.process_data_url(window.deref().image_cache_task.clone(), url); self.process_data_url(window.deref().image_cache_task.clone(), url);

View file

@ -19,9 +19,9 @@ use dom::node::{TextNodeTypeId, NodeHelpers};
use dom::processinginstruction::ProcessingInstruction; use dom::processinginstruction::ProcessingInstruction;
use dom::text::Text; use dom::text::Text;
pub fn serialize(iterator: &mut NodeIterator) -> ~str { pub fn serialize(iterator: &mut NodeIterator) -> String {
let mut html = StrBuf::new(); let mut html = String::new();
let mut open_elements: Vec<~str> = vec!(); let mut open_elements: Vec<String> = vec!();
for node in *iterator { for node in *iterator {
while open_elements.len() > iterator.depth { while open_elements.len() > iterator.depth {
@ -65,13 +65,13 @@ pub fn serialize(iterator: &mut NodeIterator) -> ~str {
html.into_owned() html.into_owned()
} }
fn serialize_comment(comment: &JSRef<Comment>, html: &mut StrBuf) { fn serialize_comment(comment: &JSRef<Comment>, html: &mut String) {
html.push_str("<!--"); html.push_str("<!--");
html.push_str(comment.deref().characterdata.data); html.push_str(comment.deref().characterdata.data.as_slice());
html.push_str("-->"); html.push_str("-->");
} }
fn serialize_text(text: &JSRef<Text>, html: &mut StrBuf) { fn serialize_text(text: &JSRef<Text>, html: &mut String) {
let text_node: &JSRef<Node> = NodeCast::from_ref(text); let text_node: &JSRef<Node> = NodeCast::from_ref(text);
match text_node.parent_node().map(|node| node.root()) { match text_node.parent_node().map(|node| node.root()) {
Some(ref parent) if parent.is_element() => { Some(ref parent) if parent.is_element() => {
@ -80,32 +80,32 @@ fn serialize_text(text: &JSRef<Text>, html: &mut StrBuf) {
"style" | "script" | "xmp" | "iframe" | "style" | "script" | "xmp" | "iframe" |
"noembed" | "noframes" | "plaintext" | "noembed" | "noframes" | "plaintext" |
"noscript" if elem.deref().namespace == namespace::HTML "noscript" if elem.deref().namespace == namespace::HTML
=> html.push_str(text.deref().characterdata.data), => html.push_str(text.deref().characterdata.data.as_slice()),
_ => escape(text.deref().characterdata.data, false, html) _ => escape(text.deref().characterdata.data.as_slice(), false, html)
} }
} }
_ => escape(text.deref().characterdata.data, false, html) _ => escape(text.deref().characterdata.data.as_slice(), false, html)
} }
} }
fn serialize_processing_instruction(processing_instruction: &JSRef<ProcessingInstruction>, fn serialize_processing_instruction(processing_instruction: &JSRef<ProcessingInstruction>,
html: &mut StrBuf) { html: &mut String) {
html.push_str("<?"); html.push_str("<?");
html.push_str(processing_instruction.deref().target); html.push_str(processing_instruction.deref().target.as_slice());
html.push_char(' '); html.push_char(' ');
html.push_str(processing_instruction.deref().characterdata.data); html.push_str(processing_instruction.deref().characterdata.data.as_slice());
html.push_str("?>"); html.push_str("?>");
} }
fn serialize_doctype(doctype: &JSRef<DocumentType>, html: &mut StrBuf) { fn serialize_doctype(doctype: &JSRef<DocumentType>, html: &mut String) {
html.push_str("<!DOCTYPE"); html.push_str("<!DOCTYPE");
html.push_str(doctype.deref().name); html.push_str(doctype.deref().name.as_slice());
html.push_char('>'); html.push_char('>');
} }
fn serialize_elem(elem: &JSRef<Element>, open_elements: &mut Vec<~str>, html: &mut StrBuf) { fn serialize_elem(elem: &JSRef<Element>, open_elements: &mut Vec<String>, html: &mut String) {
html.push_char('<'); html.push_char('<');
html.push_str(elem.deref().local_name); html.push_str(elem.deref().local_name.as_slice());
for attr in elem.deref().attrs.borrow().iter() { for attr in elem.deref().attrs.borrow().iter() {
let attr = attr.root(); let attr = attr.root();
serialize_attr(&*attr, html); serialize_attr(&*attr, html);
@ -118,7 +118,7 @@ fn serialize_elem(elem: &JSRef<Element>, open_elements: &mut Vec<~str>, html: &m
match node.first_child().map(|child| child.root()) { match node.first_child().map(|child| child.root()) {
Some(ref child) if child.is_text() => { Some(ref child) if child.is_text() => {
let text: &JSRef<CharacterData> = CharacterDataCast::to_ref(&**child).unwrap(); let text: &JSRef<CharacterData> = CharacterDataCast::to_ref(&**child).unwrap();
if text.deref().data.len() > 0 && text.deref().data[0] == 0x0A as u8 { if text.deref().data.len() > 0 && text.deref().data.as_slice().char_at(0) == '\n' {
html.push_char('\x0A'); html.push_char('\x0A');
} }
}, },
@ -133,29 +133,29 @@ fn serialize_elem(elem: &JSRef<Element>, open_elements: &mut Vec<~str>, html: &m
} }
} }
fn serialize_attr(attr: &JSRef<Attr>, html: &mut StrBuf) { fn serialize_attr(attr: &JSRef<Attr>, html: &mut String) {
html.push_char(' '); html.push_char(' ');
if attr.deref().namespace == namespace::XML { if attr.deref().namespace == namespace::XML {
html.push_str("xml:"); html.push_str("xml:");
html.push_str(attr.deref().local_name); html.push_str(attr.deref().local_name.as_slice());
} else if attr.deref().namespace == namespace::XMLNS && } else if attr.deref().namespace == namespace::XMLNS &&
attr.deref().local_name.as_slice() == "xmlns" { attr.deref().local_name.as_slice() == "xmlns" {
html.push_str("xmlns"); html.push_str("xmlns");
} else if attr.deref().namespace == namespace::XMLNS { } else if attr.deref().namespace == namespace::XMLNS {
html.push_str("xmlns:"); html.push_str("xmlns:");
html.push_str(attr.deref().local_name); html.push_str(attr.deref().local_name.as_slice());
} else if attr.deref().namespace == namespace::XLink { } else if attr.deref().namespace == namespace::XLink {
html.push_str("xlink:"); html.push_str("xlink:");
html.push_str(attr.deref().local_name); html.push_str(attr.deref().local_name.as_slice());
} else { } else {
html.push_str(attr.deref().name); html.push_str(attr.deref().name.as_slice());
}; };
html.push_str("=\""); html.push_str("=\"");
escape(attr.deref().value, true, html); escape(attr.deref().value.as_slice(), true, html);
html.push_char('"'); html.push_char('"');
} }
fn escape(string: &str, attr_mode: bool, html: &mut StrBuf) { fn escape(string: &str, attr_mode: bool, html: &mut String) {
for c in string.chars() { for c in string.chars() {
match c { match c {
'&' => html.push_str("&amp;"), '&' => html.push_str("&amp;"),

View file

@ -37,7 +37,7 @@ pub trait NavigatorMethods {
impl<'a> NavigatorMethods for JSRef<'a, Navigator> { impl<'a> NavigatorMethods for JSRef<'a, Navigator> {
fn Product(&self) -> DOMString { fn Product(&self) -> DOMString {
"Gecko".to_owned() "Gecko".to_string()
} }
fn TaintEnabled(&self) -> bool { fn TaintEnabled(&self) -> bool {
@ -45,15 +45,15 @@ impl<'a> NavigatorMethods for JSRef<'a, Navigator> {
} }
fn AppName(&self) -> DOMString { fn AppName(&self) -> DOMString {
"Netscape".to_owned() // Like Gecko/Webkit "Netscape".to_string() // Like Gecko/Webkit
} }
fn AppCodeName(&self) -> DOMString { fn AppCodeName(&self) -> DOMString {
"Mozilla".to_owned() "Mozilla".to_string()
} }
fn Platform(&self) -> DOMString { fn Platform(&self) -> DOMString {
"".to_owned() "".to_string()
} }
} }

View file

@ -39,8 +39,6 @@ use js::jsapi::{JSContext, JSObject, JSRuntime};
use js::jsfriendapi; use js::jsfriendapi;
use libc; use libc;
use libc::uintptr_t; use libc::uintptr_t;
use std::cast::transmute;
use std::cast;
use std::cell::{Cell, RefCell, Ref, RefMut}; use std::cell::{Cell, RefCell, Ref, RefMut};
use std::iter::{Map, Filter}; use std::iter::{Map, Filter};
use std::mem; use std::mem;
@ -171,7 +169,7 @@ impl LayoutDataRef {
pub unsafe fn from_data<T>(data: Box<T>) -> LayoutDataRef { pub unsafe fn from_data<T>(data: Box<T>) -> LayoutDataRef {
LayoutDataRef { LayoutDataRef {
data_cell: RefCell::new(Some(cast::transmute(data))), data_cell: RefCell::new(Some(mem::transmute(data))),
} }
} }
@ -195,7 +193,7 @@ impl LayoutDataRef {
/// safe layout data accessor. /// safe layout data accessor.
#[inline] #[inline]
pub unsafe fn borrow_unchecked(&self) -> *Option<LayoutData> { pub unsafe fn borrow_unchecked(&self) -> *Option<LayoutData> {
cast::transmute(&self.data_cell) mem::transmute(&self.data_cell)
} }
/// Borrows the layout data immutably. This function is *not* thread-safe. /// Borrows the layout data immutably. This function is *not* thread-safe.
@ -384,7 +382,7 @@ pub trait NodeHelpers {
fn dump(&self); fn dump(&self);
fn dump_indent(&self, indent: uint); fn dump_indent(&self, indent: uint);
fn debug_str(&self) -> ~str; fn debug_str(&self) -> String;
fn traverse_preorder<'a>(&'a self) -> TreeIterator<'a>; fn traverse_preorder<'a>(&'a self) -> TreeIterator<'a>;
fn sequential_traverse_postorder<'a>(&'a self) -> TreeIterator<'a>; fn sequential_traverse_postorder<'a>(&'a self) -> TreeIterator<'a>;
@ -406,12 +404,12 @@ impl<'a> NodeHelpers for JSRef<'a, Node> {
/// Dumps the node tree, for debugging, with indentation. /// Dumps the node tree, for debugging, with indentation.
fn dump_indent(&self, indent: uint) { fn dump_indent(&self, indent: uint) {
let mut s = StrBuf::new(); let mut s = String::new();
for _ in range(0, indent) { for _ in range(0, indent) {
s.push_str(" "); s.push_str(" ");
} }
s.push_str(self.debug_str()); s.push_str(self.debug_str().as_slice());
debug!("{:s}", s); debug!("{:s}", s);
// FIXME: this should have a pure version? // FIXME: this should have a pure version?
@ -421,7 +419,7 @@ impl<'a> NodeHelpers for JSRef<'a, Node> {
} }
/// Returns a string that describes this node. /// Returns a string that describes this node.
fn debug_str(&self) -> ~str { fn debug_str(&self) -> String {
format!("{:?}", self.type_id()) format!("{:?}", self.type_id())
} }
@ -600,7 +598,7 @@ impl<'a> NodeHelpers for JSRef<'a, Node> {
pub fn from_untrusted_node_address(runtime: *mut JSRuntime, candidate: UntrustedNodeAddress) pub fn from_untrusted_node_address(runtime: *mut JSRuntime, candidate: UntrustedNodeAddress)
-> Temporary<Node> { -> Temporary<Node> {
unsafe { unsafe {
let candidate: uintptr_t = cast::transmute(candidate); let candidate: uintptr_t = mem::transmute(candidate);
let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime, let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime,
candidate); candidate);
if object.is_null() { if object.is_null() {
@ -1353,19 +1351,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()
} }
TextNodeTypeId => "#text".to_owned(), TextNodeTypeId => "#text".to_string(),
ProcessingInstructionNodeTypeId => { ProcessingInstructionNodeTypeId => {
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()
} }
CommentNodeTypeId => "#comment".to_owned(), CommentNodeTypeId => "#comment".to_string(),
DoctypeNodeTypeId => { DoctypeNodeTypeId => {
let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap(); let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap();
doctype.deref().name.clone() doctype.deref().name.clone()
}, },
DocumentFragmentNodeTypeId => "#document-fragment".to_owned(), DocumentFragmentNodeTypeId => "#document-fragment".to_string(),
DocumentNodeTypeId => "#document".to_owned() DocumentNodeTypeId => "#document".to_string()
} }
} }
@ -1476,7 +1474,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
match self.type_id { match self.type_id {
DocumentFragmentNodeTypeId | DocumentFragmentNodeTypeId |
ElementNodeTypeId(..) => { ElementNodeTypeId(..) => {
let mut content = StrBuf::new(); let mut content = String::new();
for node in self.traverse_preorder() { for node in self.traverse_preorder() {
if node.is_text() { if node.is_text() {
let text: &JSRef<Text> = TextCast::to_ref(&node).unwrap(); let text: &JSRef<Text> = TextCast::to_ref(&node).unwrap();

View file

@ -48,7 +48,7 @@ pub trait TestBindingMethods {
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 { "".to_owned() } fn StringAttribute(&self) -> DOMString { "".to_string() }
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) {}
@ -83,7 +83,7 @@ pub trait TestBindingMethods {
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("".to_owned()) } fn GetStringAttributeNullable(&self) -> Option<DOMString> { Some("".to_string()) }
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>>;
@ -101,7 +101,7 @@ pub trait TestBindingMethods {
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 { "".to_owned() } fn ReceiveString(&self) -> DOMString { "".to_string() }
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>;
@ -118,7 +118,7 @@ pub trait TestBindingMethods {
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("".to_owned()) } fn ReceiveNullableString(&self) -> Option<DOMString> { Some("".to_string()) }
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>>;

View file

@ -302,9 +302,9 @@ impl<'a> WindowHelpers for JSRef<'a, Window> {
fn load_url(&self, href: DOMString) { fn load_url(&self, href: DOMString) {
let base_url = Some(self.page().get_url()); let base_url = Some(self.page().get_url());
debug!("current page url is {:?}", base_url); debug!("current page url is {:?}", base_url);
let url = parse_url(href, base_url); let url = parse_url(href.as_slice(), base_url);
let ScriptChan(ref script_chan) = self.script_chan; let ScriptChan(ref script_chan) = self.script_chan;
if href.starts_with("#") { if href.as_slice().starts_with("#") {
script_chan.send(TriggerFragmentMsg(self.page.id, url)); script_chan.send(TriggerFragmentMsg(self.page.id, url));
} else { } else {
script_chan.send(TriggerLoadMsg(self.page.id, url)); script_chan.send(TriggerLoadMsg(self.page.id, url));

View file

@ -129,13 +129,13 @@ pub struct XMLHttpRequest {
impl XMLHttpRequest { impl XMLHttpRequest {
pub fn new_inherited(owner: &JSRef<Window>) -> XMLHttpRequest { pub fn new_inherited(owner: &JSRef<Window>) -> XMLHttpRequest {
let mut xhr = XMLHttpRequest { let xhr = XMLHttpRequest {
eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestTypeId), eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestTypeId),
ready_state: Unsent, ready_state: Unsent,
timeout: 0u32, timeout: 0u32,
with_credentials: false, with_credentials: false,
upload: Cell::new(None), upload: Cell::new(None),
response_url: "".to_owned(), response_url: "".to_string(),
status: 0, status: 0,
status_text: ByteString::new(vec!()), status_text: ByteString::new(vec!()),
response: ByteString::new(vec!()), response: ByteString::new(vec!()),
@ -146,7 +146,7 @@ impl XMLHttpRequest {
request_method: Untraceable::new(Get), request_method: Untraceable::new(Get),
request_url: Untraceable::new(parse_url("", None)), request_url: Untraceable::new(parse_url("", None)),
request_headers: Untraceable::new(RequestHeaderCollection::new()), request_headers: Untraceable::new(RequestHeaderCollection::new()),
request_body: "".to_owned(), request_body: "".to_string(),
sync: false, sync: false,
send_flag: false, send_flag: false,
@ -266,7 +266,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
fn Open(&mut self, method: ByteString, url: DOMString) -> ErrorResult { fn Open(&mut self, method: ByteString, url: DOMString) -> ErrorResult {
let maybe_method: Option<Method> = method.as_str().and_then(|s| { let maybe_method: Option<Method> = method.as_str().and_then(|s| {
FromStr::from_str(s.to_ascii_upper()) // rust-http tests against the uppercase versions FromStr::from_str(s.to_ascii_upper().as_slice()) // rust-http tests against the uppercase versions
}); });
// Step 2 // Step 2
let base: Option<Url> = Some(self.global.root().get_url()); let base: Option<Url> = Some(self.global.root().get_url());
@ -276,7 +276,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
*self.request_method = maybe_method.unwrap(); *self.request_method = maybe_method.unwrap();
// Step 6 // Step 6
let parsed_url = match try_parse_url(url, base) { let parsed_url = match try_parse_url(url.as_slice(), base) {
Ok(parsed) => parsed, Ok(parsed) => parsed,
Err(_) => return Err(Syntax) // Step 7 Err(_) => return Err(Syntax) // Step 7
}; };
@ -337,7 +337,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
"upgrade" | "user-agent" | "via" => { "upgrade" | "user-agent" | "via" => {
return Ok(()); // Step 5 return Ok(()); // Step 5
}, },
_ => StrBuf::from_str(s) _ => String::from_str(s)
} }
}, },
None => return Err(Syntax) None => return Err(Syntax)
@ -423,9 +423,9 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
// Step 9 // Step 9
self.send_flag = true; self.send_flag = true;
self.dispatch_response_progress_event("loadstart".to_owned()); self.dispatch_response_progress_event("loadstart".to_string());
if !self.upload_complete { if !self.upload_complete {
self.dispatch_upload_progress_event("loadstart".to_owned(), Some(0)); self.dispatch_upload_progress_event("loadstart".to_string(), Some(0));
} }
} }
@ -436,7 +436,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
// XXXManishearth deal with the Origin/Referer/Accept headers // XXXManishearth deal with the Origin/Referer/Accept headers
// XXXManishearth the below is only valid when content type is not already set by the user. // XXXManishearth the below is only valid when content type is not already set by the user.
self.insert_trusted_header("content-type".to_owned(), "text/plain;charset=UTF-8".to_owned()); self.insert_trusted_header("content-type".to_string(), "text/plain;charset=UTF-8".to_string());
load_data.headers = (*self.request_headers).clone(); load_data.headers = (*self.request_headers).clone();
load_data.method = (*self.request_method).clone(); load_data.method = (*self.request_method).clone();
if self.sync { if self.sync {
@ -488,7 +488,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
if self.ready_state == XHRDone || self.ready_state == Loading { if self.ready_state == XHRDone || self.ready_state == Loading {
self.response.to_jsval(cx) self.response.to_jsval(cx)
} else { } else {
"".to_owned().to_jsval(cx) "".to_string().to_jsval(cx)
} }
}, },
_ => { _ => {
@ -509,8 +509,8 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> {
// XXXManishearth handle charset, etc (http://xhr.spec.whatwg.org/#text-response) // XXXManishearth handle charset, etc (http://xhr.spec.whatwg.org/#text-response)
// 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
Loading | XHRDone => Ok(UTF_8.decode(self.response.as_slice(), DecodeReplace).unwrap().to_owned()), Loading | XHRDone => Ok(UTF_8.decode(self.response.as_slice(), DecodeReplace).unwrap().to_string()),
_ => Ok("".to_owned()) _ => Ok("".to_string())
} }
}, },
_ => Err(InvalidState) _ => Err(InvalidState)
@ -556,7 +556,7 @@ trait PrivateXMLHttpRequestHelpers {
fn release(&mut self); fn release(&mut self);
fn change_ready_state(&mut self, XMLHttpRequestState); fn change_ready_state(&mut self, XMLHttpRequestState);
fn process_partial_response(&mut self, progress: XHRProgress); fn process_partial_response(&mut self, progress: XHRProgress);
fn insert_trusted_header(&mut self, name: ~str, value: ~str); fn insert_trusted_header(&mut self, name: String, value: String);
fn dispatch_progress_event(&self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>); fn dispatch_progress_event(&self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>);
fn dispatch_upload_progress_event(&self, type_: DOMString, partial_load: Option<u64>); fn dispatch_upload_progress_event(&self, type_: DOMString, partial_load: Option<u64>);
fn dispatch_response_progress_event(&self, type_: DOMString); fn dispatch_response_progress_event(&self, type_: DOMString);
@ -584,7 +584,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
self.ready_state = rs; self.ready_state = rs;
let win = &*self.global.root(); let win = &*self.global.root();
let mut event = let mut event =
Event::new(win, "readystatechange".to_owned(), false, true).root(); Event::new(win, "readystatechange".to_string(), false, true).root();
let target: &JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: &JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.dispatch_event_with_target(None, &mut *event).ok(); target.dispatch_event_with_target(None, &mut *event).ok();
} }
@ -598,9 +598,9 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
// Substep 1 // Substep 1
self.upload_complete = true; self.upload_complete = true;
// Substeps 2-4 // Substeps 2-4
self.dispatch_upload_progress_event("progress".to_owned(), None); self.dispatch_upload_progress_event("progress".to_string(), None);
self.dispatch_upload_progress_event("load".to_owned(), None); self.dispatch_upload_progress_event("load".to_string(), None);
self.dispatch_upload_progress_event("loadend".to_owned(), None); self.dispatch_upload_progress_event("loadend".to_string(), None);
// Part of step 13, send() (processing response) // Part of step 13, send() (processing response)
// XXXManishearth handle errors, if any (substep 1) // XXXManishearth handle errors, if any (substep 1)
@ -627,7 +627,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
// Substep 3 // Substep 3
self.response = partial_response; self.response = partial_response;
// Substep 4 // Substep 4
self.dispatch_response_progress_event("progress".to_owned()); self.dispatch_response_progress_event("progress".to_string());
}, },
DoneMsg => { DoneMsg => {
// Part of step 13, send() (processing response end of file) // Part of step 13, send() (processing response end of file)
@ -640,10 +640,9 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
self.change_ready_state(XHRDone); self.change_ready_state(XHRDone);
// Subsubsteps 5-7 // Subsubsteps 5-7
let len = self.response.len() as u64; self.dispatch_response_progress_event("progress".to_string());
self.dispatch_response_progress_event("progress".to_owned()); self.dispatch_response_progress_event("load".to_string());
self.dispatch_response_progress_event("load".to_owned()); self.dispatch_response_progress_event("loadend".to_string());
self.dispatch_response_progress_event("loadend".to_owned());
} }
}, },
ErroredMsg => { ErroredMsg => {
@ -654,13 +653,13 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
if !self.sync { if !self.sync {
if !self.upload_complete { if !self.upload_complete {
self.upload_complete = true; self.upload_complete = true;
self.dispatch_upload_progress_event("progress".to_owned(), None); self.dispatch_upload_progress_event("progress".to_string(), None);
self.dispatch_upload_progress_event("load".to_owned(), None); self.dispatch_upload_progress_event("load".to_string(), None);
self.dispatch_upload_progress_event("loadend".to_owned(), None); self.dispatch_upload_progress_event("loadend".to_string(), None);
} }
self.dispatch_response_progress_event("progress".to_owned()); self.dispatch_response_progress_event("progress".to_string());
self.dispatch_response_progress_event("load".to_owned()); self.dispatch_response_progress_event("load".to_string());
self.dispatch_response_progress_event("loadend".to_owned()); self.dispatch_response_progress_event("loadend".to_string());
} }
}, },
@ -670,14 +669,14 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
} }
} }
fn insert_trusted_header(&mut self, name: ~str, value: ~str) { fn insert_trusted_header(&mut self, name: String, value: String) {
// Insert a header without checking spec-compliance // Insert a header without checking spec-compliance
// Use for hardcoded headers // Use for hardcoded headers
let collection = self.request_headers.deref_mut(); let collection = self.request_headers.deref_mut();
let value_bytes = value.into_bytes(); let value_bytes = value.into_bytes();
let mut reader = BufReader::new(value_bytes); let mut reader = BufReader::new(value_bytes.as_slice());
let maybe_header: Option<Header> = HeaderEnum::value_from_stream( let maybe_header: Option<Header> = HeaderEnum::value_from_stream(
StrBuf::from_str(name), String::from_str(name.as_slice()),
&mut HeaderValueByteIterator::new(&mut reader)); &mut HeaderValueByteIterator::new(&mut reader));
collection.insert(maybe_header.unwrap()); collection.insert(maybe_header.unwrap());
} }
@ -705,7 +704,6 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
} }
fn dispatch_response_progress_event(&self, type_: DOMString) { fn dispatch_response_progress_event(&self, type_: DOMString) {
let win = &*self.global.root();
let len = self.response.len() as u64; let len = self.response.len() as u64;
let total = self.response_headers.deref().content_length.map(|x| {x as u64}); let total = self.response_headers.deref().content_length.map(|x| {x as u64});
self.dispatch_progress_event(false, type_, len, total); self.dispatch_progress_event(false, type_, len, total);

View file

@ -15,11 +15,11 @@ use url::Url;
/// Where a style sheet comes from. /// Where a style sheet comes from.
pub enum StylesheetProvenance { pub enum StylesheetProvenance {
UrlProvenance(Url, ResourceTask), UrlProvenance(Url, ResourceTask),
InlineProvenance(Url, ~str), InlineProvenance(Url, String),
} }
// Parses the style data and returns the stylesheet // Parses the style data and returns the stylesheet
pub fn parse_inline_css(url: Url, data: ~str) -> Stylesheet { pub fn parse_inline_css(url: Url, data: String) -> Stylesheet {
parse_css(InlineProvenance(url, data)) parse_css(InlineProvenance(url, data))
} }
@ -43,7 +43,7 @@ fn parse_css(provenance: StylesheetProvenance) -> Stylesheet {
} }
InlineProvenance(base_url, data) => { InlineProvenance(base_url, data) => {
debug!("cssparse: loading inline stylesheet {:s}", data); debug!("cssparse: loading inline stylesheet {:s}", data);
Stylesheet::from_str(data, base_url, environment_encoding) Stylesheet::from_str(data.as_slice(), base_url, environment_encoding)
} }
} }
} }

View file

@ -25,10 +25,9 @@ use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use servo_util::task::spawn_named; use servo_util::task::spawn_named;
use servo_util::url::parse_url; use servo_util::url::parse_url;
use std::ascii::StrAsciiExt; use std::ascii::StrAsciiExt;
use std::cast; use std::mem;
use std::cell::RefCell; use std::cell::RefCell;
use std::comm::{channel, Sender, Receiver}; use std::comm::{channel, Sender, Receiver};
use std::str;
use style::Stylesheet; use style::Stylesheet;
use url::Url; use url::Url;
@ -38,7 +37,7 @@ macro_rules! handle_element(
$string: expr, $string: expr,
$ctor: ident $ctor: ident
$(, $arg:expr )*) => ( $(, $arg:expr )*) => (
if $string == $localName { if $string == $localName.as_slice() {
return ElementCast::from_temporary($ctor::new($localName, $document $(, $arg)*)); return ElementCast::from_temporary($ctor::new($localName, $document $(, $arg)*));
} }
) )
@ -46,7 +45,7 @@ macro_rules! handle_element(
pub struct JSFile { pub struct JSFile {
pub data: ~str, pub data: String,
pub url: Url pub url: Url
} }
@ -59,7 +58,7 @@ enum CSSMessage {
enum JSMessage { enum JSMessage {
JSTaskNewFile(Url), JSTaskNewFile(Url),
JSTaskNewInlineScript(~str, Url), JSTaskNewInlineScript(String, Url),
JSTaskExit JSTaskExit
} }
@ -79,12 +78,12 @@ trait NodeWrapping<T> {
impl<'a, T: NodeBase+Reflectable> NodeWrapping<T> for JSRef<'a, T> { impl<'a, T: NodeBase+Reflectable> NodeWrapping<T> for JSRef<'a, T> {
unsafe fn to_hubbub_node(&self) -> hubbub::NodeDataPtr { unsafe fn to_hubbub_node(&self) -> hubbub::NodeDataPtr {
cast::transmute(self.deref()) mem::transmute(self.deref())
} }
} }
unsafe fn from_hubbub_node<T: Reflectable>(n: hubbub::NodeDataPtr) -> Temporary<T> { unsafe fn from_hubbub_node<T: Reflectable>(n: hubbub::NodeDataPtr) -> Temporary<T> {
Temporary::new(JS::from_raw(cast::transmute(n))) Temporary::new(JS::from_raw(mem::transmute(n)))
} }
/** /**
@ -120,7 +119,7 @@ fn css_link_listener(to_parent: Sender<HtmlDiscoveryMessage>,
// Send the sheets back in order // Send the sheets back in order
// FIXME: Shouldn't wait until after we've recieved CSSTaskExit to start sending these // FIXME: Shouldn't wait until after we've recieved CSSTaskExit to start sending these
for port in result_vec.iter() { for port in result_vec.iter() {
to_parent.send_opt(HtmlDiscoveredStyle(port.recv())); assert!(to_parent.send_opt(HtmlDiscoveredStyle(port.recv())).is_ok());
} }
} }
@ -138,7 +137,7 @@ fn js_script_listener(to_parent: Sender<HtmlDiscoveryMessage>,
} }
Ok((metadata, bytes)) => { Ok((metadata, bytes)) => {
result_vec.push(JSFile { result_vec.push(JSFile {
data: str::from_utf8(bytes.as_slice()).unwrap().to_owned(), data: String::from_utf8(bytes).unwrap().to_string(),
url: metadata.final_url, url: metadata.final_url,
}); });
} }
@ -153,7 +152,7 @@ fn js_script_listener(to_parent: Sender<HtmlDiscoveryMessage>,
} }
} }
to_parent.send_opt(HtmlDiscoveredScript(result_vec)); assert!(to_parent.send_opt(HtmlDiscoveredScript(result_vec)).is_ok());
} }
// Silly macros to handle constructing DOM nodes. This produces bad code and should be optimized // Silly macros to handle constructing DOM nodes. This produces bad code and should be optimized
@ -340,7 +339,7 @@ pub fn parse_html(page: &Page,
let doc_cell = RefCell::new(document); let doc_cell = RefCell::new(document);
let mut tree_handler = hubbub::TreeHandler { let mut tree_handler = hubbub::TreeHandler {
create_comment: |data: ~str| { create_comment: |data: String| {
debug!("create comment"); debug!("create comment");
// NOTE: tmp vars are workaround for lifetime issues. Both required. // NOTE: tmp vars are workaround for lifetime issues. Both required.
let tmp_borrow = doc_cell.borrow(); let tmp_borrow = doc_cell.borrow();
@ -370,7 +369,7 @@ pub fn parse_html(page: &Page,
// NOTE: tmp vars are workaround for lifetime issues. Both required. // NOTE: tmp vars are workaround for lifetime issues. Both required.
let tmp_borrow = doc_cell.borrow(); let tmp_borrow = doc_cell.borrow();
let tmp = &*tmp_borrow; let tmp = &*tmp_borrow;
let element: Root<Element> = build_element_from_tag(tag.name.clone(), *tmp).root(); let mut element: Root<Element> = build_element_from_tag(tag.name.clone(), *tmp).root();
debug!("-- attach attrs"); debug!("-- attach attrs");
for attr in tag.attributes.iter() { for attr in tag.attributes.iter() {
@ -381,10 +380,10 @@ pub fn parse_html(page: &Page,
XmlNsNs => (namespace::XMLNS, Some("xmlns")), XmlNsNs => (namespace::XMLNS, Some("xmlns")),
ns => fail!("Not expecting namespace {:?}", ns), ns => fail!("Not expecting namespace {:?}", ns),
}; };
element.deref().set_attribute_from_parser(attr.name.clone(), element.set_attribute_from_parser(attr.name.clone(),
attr.value.clone(), attr.value.clone(),
namespace, namespace,
prefix.map(|p| p.to_owned())); prefix.map(|p| p.to_string()));
} }
//FIXME: workaround for https://github.com/mozilla/rust/issues/13246; //FIXME: workaround for https://github.com/mozilla/rust/issues/13246;
@ -407,9 +406,9 @@ pub fn parse_html(page: &Page,
// Handle CSS style sheets from <link> elements // Handle CSS style sheets from <link> elements
ElementNodeTypeId(HTMLLinkElementTypeId) => { ElementNodeTypeId(HTMLLinkElementTypeId) => {
match (rel, href) { match (rel, href) {
(Some(ref rel), Some(ref href)) if rel.split(HTML_SPACE_CHARACTERS.as_slice()) (Some(ref rel), Some(ref href)) if rel.as_slice().split(HTML_SPACE_CHARACTERS.as_slice())
.any(|s| { .any(|s| {
s.eq_ignore_ascii_case("stylesheet") s.as_slice().eq_ignore_ascii_case("stylesheet")
}) => { }) => {
debug!("found CSS stylesheet: {:s}", *href); debug!("found CSS stylesheet: {:s}", *href);
let url = parse_url(href.as_slice(), Some(url2.clone())); let url = parse_url(href.as_slice(), Some(url2.clone()));
@ -423,7 +422,7 @@ pub fn parse_html(page: &Page,
unsafe { element.deref().to_hubbub_node() } unsafe { element.deref().to_hubbub_node() }
}, },
create_text: |data: ~str| { create_text: |data: String| {
debug!("create text"); debug!("create text");
// NOTE: tmp vars are workaround for lifetime issues. Both required. // NOTE: tmp vars are workaround for lifetime issues. Both required.
let tmp_borrow = doc_cell.borrow(); let tmp_borrow = doc_cell.borrow();

Some files were not shown because too many files have changed in this diff Show more