diff options
author | Jack Moffitt <jack@metajack.im> | 2014-06-01 00:21:53 -0600 |
---|---|---|
committer | Jack Moffitt <jack@metajack.im> | 2014-06-05 09:58:59 -0600 |
commit | 629c4c6afe7cea86c051bb9f52adeac716e2c43f (patch) | |
tree | ee84d9a9b37ecd37e0a9606509624e7f728f5a81 /src | |
parent | 2ae671b5aa9d27812adcdb8ebc749733156df66e (diff) | |
download | servo-629c4c6afe7cea86c051bb9f52adeac716e2c43f.tar.gz servo-629c4c6afe7cea86c051bb9f52adeac716e2c43f.zip |
Upgrade Rust.
Diffstat (limited to 'src')
146 files changed, 958 insertions, 938 deletions
diff --git a/src/compiler/rust b/src/compiler/rust -Subproject aa6725407ae0a2cb88458e147e76adf8bcae096 +Subproject d35a38087088301aa58f244ae99d48b282df6fb diff --git a/src/compiler/rust-auto-clean-trigger b/src/compiler/rust-auto-clean-trigger index 86aa184d8bc..4b92af9ef40 100644 --- a/src/compiler/rust-auto-clean-trigger +++ b/src/compiler/rust-auto-clean-trigger @@ -1,4 +1,4 @@ # 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 # build bots then the contents should be changed so git updates the mtime. -2014-05-08 +2014-05-29 diff --git a/src/components/embedding/command_line.rs b/src/components/embedding/command_line.rs index 153fa2f848c..b6a3c35f9c4 100644 --- a/src/components/embedding/command_line.rs +++ b/src/components/embedding/command_line.rs @@ -6,7 +6,6 @@ use libc::{calloc, c_int, size_t}; use std::mem; use std::str; use std::c_vec::CVec; -use std::cast::transmute; 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}; @@ -14,7 +13,7 @@ type command_line_t = command_line; struct command_line { pub cl: cef_command_line_t, pub argc: c_int, - pub argv: Vec<~str>, + pub argv: Vec<String>, } 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) { unsafe { - let mut a: Vec<~str> = vec!(); + let mut a: Vec<String> = vec!(); for i in range(0u, argc as uint) { 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 { //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 - let cl: *mut command_line_t = transmute(cmd); - let cs: *cef_string_utf16_t = transmute(name); + let cl: *mut command_line_t = mem::transmute(cmd); + 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(); //debug!("opt: {}", opt); for s in (*cl).argv.iter() { - let o = s.trim_left_chars('-'); + let o = s.as_slice().trim_left_chars('-'); //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 arg = o.slice_from(opt.len() + 1).as_bytes(); 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 } @@ -74,7 +73,7 @@ pub extern "C" fn cef_command_line_create() -> *mut cef_command_line_t { unsafe { let cl = command_line_new(); (*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 { match GLOBAL_CMDLINE { Some(scl) => { - transmute(scl) + mem::transmute(scl) }, None => { 0 as *mut cef_command_line_t diff --git a/src/components/embedding/core.rs b/src/components/embedding/core.rs index d2c9a601b80..4529d3799f6 100644 --- a/src/components/embedding/core.rs +++ b/src/components/embedding/core.rs @@ -10,7 +10,7 @@ use libc::{c_int, c_void}; use native; use servo; use servo_util::opts; -use std::cast::transmute; +use std::mem; 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 { command_line_init((*args).argc, (*args).argv); let cb = (*application).get_browser_process_handler; - if !fptr_is_null(transmute(cb)) { + if !fptr_is_null(mem::transmute(cb)) { let handler = cb(application); if handler.is_not_null() { let hcb = (*handler).on_context_initialized; - if !fptr_is_null(transmute(hcb)) { + if !fptr_is_null(mem::transmute(hcb)) { hcb(handler); } } @@ -43,7 +43,7 @@ pub extern "C" fn cef_shutdown() { #[no_mangle] pub extern "C" fn cef_run_message_loop() { 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 { urls: urls, render_backend: azure::azure_hl::SkiaBackend, diff --git a/src/components/embedding/string.rs b/src/components/embedding/string.rs index 860b5d71651..184f921b96a 100644 --- a/src/components/embedding/string.rs +++ b/src/components/embedding/string.rs @@ -7,7 +7,7 @@ use eutil::fptr_is_null; use libc::{size_t, c_int, c_ushort,c_void}; use libc::types::os::arch::c95::wchar_t; use mem::{new0,newarray0,delete,deletearray}; -use std::cast::transmute; +use std::mem; use std::ptr; 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}; @@ -50,13 +50,13 @@ pub extern "C" fn cef_string_userfree_utf16_free(cs: *mut cef_string_userfree_ut #[no_mangle] pub extern "C" fn cef_string_utf8_clear(cs: *mut cef_string_utf8_t) { unsafe { - if !fptr_is_null(transmute((*cs).dtor)) { + if !fptr_is_null(mem::transmute((*cs).dtor)) { let dtor = (*cs).dtor; dtor((*cs).str); } (*cs).length = 0; (*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; } } else { - (*output).str = transmute(src); + (*output).str = mem::transmute(src); (*output).length = src_len; - (*output).dtor = transmute(0 as *u8); + (*output).dtor = mem::transmute(0 as *u8); } } 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] pub extern "C" fn cef_string_utf16_clear(cs: *mut cef_string_utf16_t) { unsafe { - if !fptr_is_null(transmute((*cs).dtor)) { + if !fptr_is_null(mem::transmute((*cs).dtor)) { let dtor = (*cs).dtor; dtor((*cs).str); } (*cs).length = 0; (*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; } } else { - (*output).str = transmute(src); + (*output).str = mem::transmute(src); (*output).length = src_len; - (*output).dtor = transmute(0 as *u8); + (*output).dtor = mem::transmute(0 as *u8); } } return 1; @@ -136,13 +136,13 @@ pub extern "C" fn cef_string_utf16_set(src: *c_ushort, src_len: size_t, output: #[no_mangle] pub extern "C" fn cef_string_wide_clear(cs: *mut cef_string_wide_t) { unsafe { - if !fptr_is_null(transmute((*cs).dtor)) { + if !fptr_is_null(mem::transmute((*cs).dtor)) { let dtor = (*cs).dtor; dtor((*cs).str); } (*cs).length = 0; (*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; } } else { - (*output).str = transmute(src); + (*output).str = mem::transmute(src); (*output).length = src_len; - (*output).dtor = transmute(0 as *u8); + (*output).dtor = mem::transmute(0 as *u8); } } return 1; diff --git a/src/components/gfx/display_list.rs b/src/components/gfx/display_list.rs index a05773e5f26..3cff59b52d8 100644 --- a/src/components/gfx/display_list.rs +++ b/src/components/gfx/display_list.rs @@ -631,7 +631,7 @@ impl DisplayItem { } pub fn debug_with_level(&self, level: uint) { - let mut indent = StrBuf::new(); + let mut indent = String::new(); for _ in range(0, level) { indent.push_str("| ") } @@ -644,7 +644,7 @@ impl DisplayItem { impl fmt::Show for DisplayItem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "{} @ {} ({:x})", + write!(f, "{} @ {} ({:x})", match *self { SolidColorDisplayItemClass(_) => "SolidColor", TextDisplayItemClass(_) => "Text", diff --git a/src/components/gfx/font.rs b/src/components/gfx/font.rs index a1e3313d804..f6dbd5063a1 100644 --- a/src/components/gfx/font.rs +++ b/src/components/gfx/font.rs @@ -6,7 +6,7 @@ use azure::{AzFloat, AzScaledFontRef}; use azure::azure_hl::{BackendType, ColorPattern}; use azure::scaled_font::ScaledFont; use geom::{Point2D, Rect, Size2D}; -use std::cast; +use std::mem; use std::num::Zero; use std::ptr; use std::str; @@ -37,9 +37,9 @@ pub trait FontHandleMethods { -> Result<Self,()>; // an identifier usable by FontContextHandle to recreate this FontHandle. - fn face_identifier(&self) -> ~str; - fn family_name(&self) -> ~str; - fn face_name(&self) -> ~str; + fn face_identifier(&self) -> String; + fn family_name(&self) -> String; + fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; @@ -57,17 +57,17 @@ pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { - fn tag_to_str(&self) -> ~str; + fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { - fn tag_to_str(&self) -> ~str { + fn tag_to_str(&self) -> String { unsafe { - let reversed = str::raw::from_buf_len(cast::transmute(self), 4); - return str::from_chars([reversed.char_at(3), - reversed.char_at(2), - reversed.char_at(1), - reversed.char_at(0)]); + let reversed = str::raw::from_buf_len(mem::transmute(self), 4); + return str::from_chars([reversed.as_slice().char_at(3), + reversed.as_slice().char_at(2), + reversed.as_slice().char_at(1), + reversed.as_slice().char_at(0)]); } } } @@ -101,7 +101,7 @@ pub struct FontStyle { pub pt_size: f64, pub weight: font_weight::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 } @@ -132,7 +132,7 @@ impl FontDescriptor { // A FontSelector is a platform-specific strategy for serializing face names. #[deriving(Clone, Eq)] pub enum FontSelector { - SelectorPlatformIdentifier(~str), + SelectorPlatformIdentifier(String), } // 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 // 'font-family' property. The last font is a system fallback font. pub struct FontGroup { - pub families: Vec<~str>, + pub families: Vec<String>, // style of the first western font in group, which is // used for purposes of calculating text run metrics. pub style: UsedFontStyle, @@ -151,7 +151,7 @@ pub struct 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 { families: families, 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); // 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 metrics: FontMetrics, pub backend: BackendType, - pub shape_cache: HashCache<~str, Arc<GlyphStore>>, + pub shape_cache: HashCache<String, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } @@ -285,7 +285,7 @@ impl<'a> Font { let result = self.handle.get_table_for_tag(tag); 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(), self.handle.family_name(), self.handle.face_name()); @@ -413,14 +413,14 @@ impl Font { 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) self.make_shaper(); let shaper = &self.shaper; self.shape_cache.find_or_create(&text, |txt| { - let mut glyphs = GlyphStore::new(text.char_len() as int, is_whitespace); - shaper.get_ref().shape_text(*txt, &mut glyphs); + let mut glyphs = GlyphStore::new(text.as_slice().char_len() as int, is_whitespace); + shaper.get_ref().shape_text(txt.as_slice(), &mut glyphs); Arc::new(glyphs) }) } diff --git a/src/components/gfx/font_context.rs b/src/components/gfx/font_context.rs index 7acadfb5225..0d95b38fb86 100644 --- a/src/components/gfx/font_context.rs +++ b/src/components/gfx/font_context.rs @@ -30,7 +30,7 @@ pub struct FontContextInfo { } 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 { @@ -39,7 +39,7 @@ pub struct FontContext { pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>, pub handle: FontContextHandle, pub backend: BackendType, - pub generic_fonts: HashMap<~str,~str>, + pub generic_fonts: HashMap<String,String>, pub profiler_chan: ProfilerChan, } @@ -54,11 +54,11 @@ impl FontContext { // TODO: Allow users to specify these. let mut generic_fonts = HashMap::with_capacity(5); - generic_fonts.insert("serif".to_owned(), "Times New Roman".to_owned()); - generic_fonts.insert("sans-serif".to_owned(), "Arial".to_owned()); - generic_fonts.insert("cursive".to_owned(), "Apple Chancery".to_owned()); - generic_fonts.insert("fantasy".to_owned(), "Papyrus".to_owned()); - generic_fonts.insert("monospace".to_owned(), "Menlo".to_owned()); + generic_fonts.insert("serif".to_string(), "Times New Roman".to_string()); + generic_fonts.insert("sans-serif".to_string(), "Arial".to_string()); + generic_fonts.insert("cursive".to_string(), "Apple Chancery".to_string()); + generic_fonts.insert("fantasy".to_string(), "Papyrus".to_string()); + generic_fonts.insert("monospace".to_string(), "Menlo".to_string()); FontContext { 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()); match self.generic_fonts.find(family) { - None => family.to_owned(), + None => family.to_string(), Some(mapped_family) => (*mapped_family).clone() } } diff --git a/src/components/gfx/font_list.rs b/src/components/gfx/font_list.rs index 686d72d1ad6..f0001ee223f 100644 --- a/src/components/gfx/font_list.rs +++ b/src/components/gfx/font_list.rs @@ -13,12 +13,12 @@ use style::computed_values::{font_weight, font_style}; use servo_util::time::{ProfilerChan, profile}; use servo_util::time; -pub type FontFamilyMap = HashMap<~str, FontFamily>; +pub type FontFamilyMap = HashMap<String, FontFamily>; trait FontListHandleMethods { fn get_available_families(&self, fctx: &FontContextHandle) -> FontFamilyMap; 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. @@ -53,7 +53,7 @@ impl FontList { } pub fn find_font_in_family<'a>(&'a mut self, - family_name: &~str, + family_name: &String, style: &SpecifiedFontStyle) -> Option<&'a FontEntry> { // TODO(Issue #188): look up localized font family names if canonical name not found // 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() } } // Holds a specific font family, and the various pub struct FontFamily { - pub family_name: ~str, + pub family_name: String, 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 /// standard four faces: Normal, Bold, Italic, BoldItalic. pub struct FontEntry { - pub face_name: ~str, + pub face_name: String, weight: font_weight::T, italic: bool, pub handle: FontHandle, diff --git a/src/components/gfx/gfx.rs b/src/components/gfx/gfx.rs index f88a4b6e61b..4a44f77f350 100644 --- a/src/components/gfx/gfx.rs +++ b/src/components/gfx/gfx.rs @@ -13,6 +13,7 @@ #[phase(syntax, link)] extern crate log; +extern crate debug; extern crate azure; extern crate collections; 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_list = font_list; +pub use render_context::RenderContext; + // Private rendering modules mod render_context; diff --git a/src/components/gfx/platform/linux/font.rs b/src/components/gfx/platform/linux/font.rs index c5b704ac9bb..72d5c5b8693 100644 --- a/src/components/gfx/platform/linux/font.rs +++ b/src/components/gfx/platform/linux/font.rs @@ -24,7 +24,7 @@ use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics}; use freetype::freetype::{ft_sfnt_os2}; use freetype::tt_os2::TT_OS2; -use std::cast; +use std::mem; use std::ptr; use std::str; @@ -48,7 +48,7 @@ impl FontTableMethods for FontTable { pub enum FontSource { FontSourceMem(Vec<u8>), - FontSourceFile(~str) + FontSourceFile(String) } pub struct FontHandle { @@ -117,15 +117,15 @@ impl FontHandleMethods for 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 doesn't give usable results for fontconfig when deserializing. */ 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) } } - fn face_name(&self) -> ~str { + fn face_name(&self) -> String { unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } } fn is_italic(&self) -> bool { @@ -168,7 +168,7 @@ impl FontHandleMethods for FontHandle { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } 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); if res.succeeded() { 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()); debug!("metrics: {:?}", (*slot).metrics); 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, ()> { unsafe { 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 // 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 em_size = face.units_per_EM as f64; diff --git a/src/components/gfx/platform/linux/font_context.rs b/src/components/gfx/platform/linux/font_context.rs index a6df2b55a52..cea1cbf5cb0 100644 --- a/src/components/gfx/platform/linux/font_context.rs +++ b/src/components/gfx/platform/linux/font_context.rs @@ -44,12 +44,12 @@ impl 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, ()> { debug!("Creating font handle for {:s}", name); path_from_identifier(name, &style).and_then(|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) }) } } diff --git a/src/components/gfx/platform/linux/font_list.rs b/src/components/gfx/platform/linux/font_list.rs index d64c90e9db9..83e651c138d 100644 --- a/src/components/gfx/platform/linux/font_list.rs +++ b/src/components/gfx/platform/linux/font_list.rs @@ -55,7 +55,7 @@ impl FontListHandle { while FcPatternGetString(*font, FC_FAMILY, v, &family) == FcResultMatch { let family_name = str::raw::from_c_str(family as *c_char); 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); v += 1; } @@ -131,8 +131,8 @@ impl FontListHandle { } } - pub fn get_last_resort_font_families() -> Vec<~str> { - vec!("Arial".to_owned()) + pub fn get_last_resort_font_families() -> Vec<String> { + 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 { let config = FcConfigGetCurrent(); let wrapper = AutoPattern { pattern: FcPatternCreate() }; diff --git a/src/components/gfx/platform/macos/font.rs b/src/components/gfx/platform/macos/font.rs index 48f0d318b2c..ac0d1fff414 100644 --- a/src/components/gfx/platform/macos/font.rs +++ b/src/components/gfx/platform/macos/font.rs @@ -91,11 +91,11 @@ impl FontHandleMethods for FontHandle { return result; } - fn family_name(&self) -> ~str { + fn family_name(&self) -> String { self.ctfont.family_name() } - fn face_name(&self) -> ~str { + fn face_name(&self) -> String { 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() } } diff --git a/src/components/gfx/platform/macos/font_context.rs b/src/components/gfx/platform/macos/font_context.rs index ef9ea06c447..58c79cd65e2 100644 --- a/src/components/gfx/platform/macos/font_context.rs +++ b/src/components/gfx/platform/macos/font_context.rs @@ -23,10 +23,10 @@ impl FontContextHandle { impl FontContextHandleMethods for FontContextHandle { fn create_font_from_identifier(&self, - name: ~str, + name: String, style: UsedFontStyle) -> 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| { FontHandle::new_from_CTFont(self, ctfont) }) diff --git a/src/components/gfx/platform/macos/font_list.rs b/src/components/gfx/platform/macos/font_list.rs index 9171bd3d0f6..824e59df3cb 100644 --- a/src/components/gfx/platform/macos/font_list.rs +++ b/src/components/gfx/platform/macos/font_list.rs @@ -12,7 +12,7 @@ use core_foundation::base::TCFType; use core_foundation::string::{CFString, CFStringRef}; use core_text::font_descriptor::{CTFontDescriptor, CTFontDescriptorRef}; use core_text; -use std::cast; +use std::mem; pub struct FontListHandle { fctx: FontContextHandle, @@ -29,12 +29,12 @@ impl FontListHandle { let family_names = core_text::font_collection::get_family_names(); let mut family_map: FontFamilyMap = HashMap::new(); 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 = family_name_cf.to_str(); 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 @@ -44,10 +44,10 @@ impl FontListHandle { debug!("Looking for faces of family: {:s}", family.family_name); 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(); 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 font = core_text::font::new_from_descriptor(&desc, 0.0); 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> { - vec!("Arial Unicode MS".to_owned(), "Arial".to_owned()) + pub fn get_last_resort_font_families() -> Vec<String> { + vec!("Arial Unicode MS".to_string(), "Arial".to_string()) } } diff --git a/src/components/gfx/text/shaping/harfbuzz.rs b/src/components/gfx/text/shaping/harfbuzz.rs index f29528a1b01..251ddb8ab36 100644 --- a/src/components/gfx/text/shaping/harfbuzz.rs +++ b/src/components/gfx/text/shaping/harfbuzz.rs @@ -38,7 +38,7 @@ use harfbuzz::{hb_shape, hb_buffer_get_glyph_infos}; use libc::{c_uint, c_int, c_void, c_char}; use servo_util::geometry::Au; use servo_util::range::Range; -use std::cast::transmute; +use std::mem; use std::char; use std::cmp; 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, len as c_uint, HB_MEMORY_MODE_READONLY, - transmute(skinny_font_table_ptr), + mem::transmute(skinny_font_table_ptr), destroy_blob_func); }); diff --git a/src/components/gfx/text/text_run.rs b/src/components/gfx/text/text_run.rs index abcfbc7df54..dab3ee3748e 100644 --- a/src/components/gfx/text/text_run.rs +++ b/src/components/gfx/text/text_run.rs @@ -13,7 +13,7 @@ use text::glyph::{CharIndex, GlyphStore}; /// A text run. #[deriving(Clone)] pub struct TextRun { - pub text: Arc<~str>, + pub text: Arc<String>, pub font_descriptor: FontDescriptor, pub font_metrics: FontMetrics, pub font_style: FontStyle, @@ -97,8 +97,8 @@ impl<'a> Iterator<Range<CharIndex>> for LineIterator<'a> { } impl<'a> TextRun { - pub fn new(font: &mut Font, text: ~str, decoration: text_decoration::T) -> TextRun { - let glyphs = TextRun::break_and_shape(font, text); + pub fn new(font: &mut Font, text: String, decoration: text_decoration::T) -> TextRun { + let glyphs = TextRun::break_and_shape(font, text.as_slice()); let run = TextRun { text: Arc::new(text), @@ -145,7 +145,7 @@ impl<'a> TextRun { // Create a glyph store for this slice if it's nonempty. 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 {}", slice, !cur_slice_is_whitespace, byte_last_boundary, byte_i, text); 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. 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 {}", slice, cur_slice_is_whitespace, byte_last_boundary, text.len(), text); glyphs.push(font.shape_text(slice, cur_slice_is_whitespace)); diff --git a/src/components/gfx/text/util.rs b/src/components/gfx/text/util.rs index 9bf3ba6ebf5..af3e01819e3 100644 --- a/src/components/gfx/text/util.rs +++ b/src/components/gfx/text/util.rs @@ -24,8 +24,8 @@ pub enum CompressionMode { // * Untracked: various edge cases for bidi, CJK, etc. pub fn transform_text(text: &str, mode: CompressionMode, incoming_whitespace: bool, - new_line_pos: &mut Vec<CharIndex>) -> (~str, bool) { - let mut out_str = StrBuf::new(); + new_line_pos: &mut Vec<CharIndex>) -> (String, bool) { + let mut out_str = String::new(); let out_whitespace = match mode { CompressNone | DiscardNewline => { let mut new_line_index = CharIndex(0); @@ -195,7 +195,7 @@ fn test_transform_discard_newline() { /* FIXME: Fix and re-enable #[test] 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\n bar".to_owned(), "foo \nbar".to_owned(), @@ -203,7 +203,7 @@ fn test_transform_compress_whitespace() { "foo bar baz".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\n bar".to_owned(), "foo \nbar".to_owned(), @@ -223,7 +223,7 @@ fn test_transform_compress_whitespace() { #[test] 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\n bar".to_owned(), "foo \nbar".to_owned(), @@ -231,7 +231,7 @@ fn test_transform_compress_whitespace_newline() { "foo bar baz".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(), diff --git a/src/components/macros/macros.rs b/src/components/macros/macros.rs index a90be49ca9f..30cf4baf9fe 100644 --- a/src/components/macros/macros.rs +++ b/src/components/macros/macros.rs @@ -47,7 +47,7 @@ macro_rules! lazy_init( static mut s: *$T = 0 as *$T; static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT; ONCE.doit(|| { - s = ::std::cast::transmute::<Box<$T>, *$T>(box () ($e)); + s = ::std::mem::transmute::<Box<$T>, *$T>(box () ($e)); }); &*s } @@ -66,7 +66,7 @@ mod tests { lazy_init! { static ref NUMBER: uint = times_two(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> = { let mut m = collections::HashMap::new(); m.insert(0u, "abc"); @@ -82,7 +82,7 @@ mod tests { #[test] fn test_basic() { - assert_eq!(*OWNED_STRING, "hello".to_owned()); + assert_eq!(*OWNED_STRING, "hello".to_string()); assert_eq!(*NUMBER, 6); assert!(HASHMAP.find(&1).is_some()); assert!(HASHMAP.find(&3).is_none()); diff --git a/src/components/main/compositing/compositor.rs b/src/components/main/compositing/compositor.rs index 5c9fca24326..dd9aebbea86 100644 --- a/src/components/main/compositing/compositor.rs +++ b/src/components/main/compositing/compositor.rs @@ -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); self.load_complete = false; let root_pipeline_id = match self.compositor_layer { @@ -600,7 +600,7 @@ impl IOCompositor { 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; chan.send(msg); } @@ -718,7 +718,7 @@ impl IOCompositor { if self.load_complete && self.ready_state == FinishedLoading && self.opts.output_file.is_some() { 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, width as gl2::GLsizei, height as gl2::GLsizei, diff --git a/src/components/main/compositing/compositor_layer.rs b/src/components/main/compositing/compositor_layer.rs index cb85ee538ee..42a918fda3f 100644 --- a/src/components/main/compositing/compositor_layer.rs +++ b/src/components/main/compositing/compositor_layer.rs @@ -342,12 +342,12 @@ impl CompositorLayer { } #[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()); for kid in layer.children() { match kid { ContainerLayerKind(ref container_layer) => { - self.dump_layer_tree((*container_layer).clone(), indent + " "); + self.dump_layer_tree((*container_layer).clone(), format!("{} ", indent)); } TextureLayerKind(_) => { println!("{} (texture layer)", indent); @@ -406,13 +406,13 @@ impl CompositorLayer { MouseWindowMouseUpEvent(button, _) => MouseUpEvent(button, cursor), }; 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>) { let message = MouseMoveEvent(cursor); 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 @@ -432,7 +432,7 @@ impl CompositorLayer { redisplay = !unused.is_empty(); if redisplay { // 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() { // Ask for tiles. @@ -440,7 +440,7 @@ impl CompositorLayer { // 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. 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); match self.quadtree { Tree(ref mut quadtree) => { - self.pipeline + let _ = self.pipeline .render_chan .send_opt(UnusedBufferMsg(quadtree.resize(new_size.width as uint, new_size.height as uint))); @@ -655,7 +655,7 @@ impl CompositorLayer { child.page_size = Some(new_size); match child.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))); } NoTree(tile_size, max_mem) => { @@ -829,7 +829,7 @@ impl CompositorLayer { self.epoch, epoch, 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 } @@ -849,7 +849,7 @@ impl CompositorLayer { buffer)); } 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() } - self.pipeline.render_chan.send_opt(UnusedBufferMsg(tiles)); + let _ = self.pipeline.render_chan.send_opt(UnusedBufferMsg(tiles)); } } } diff --git a/src/components/main/constellation.rs b/src/components/main/constellation.rs index e487ece1246..112b5b38ec5 100644 --- a/src/components/main/constellation.rs +++ b/src/components/main/constellation.rs @@ -388,10 +388,10 @@ impl Constellation { fn force_pipeline_exit(old_pipeline: &Rc<Pipeline>) { let ScriptChan(ref old_script) = old_pipeline.script_chan; - old_script.send_opt(ExitPipelineMsg(old_pipeline.id)); - old_pipeline.render_chan.send_opt(render_task::ExitMsg(None)); + let _ = old_script.send_opt(ExitPipelineMsg(old_pipeline.id)); + let _ = old_pipeline.render_chan.send_opt(render_task::ExitMsg(None)); 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); self.pipelines.remove(&pipeline_id); @@ -796,7 +796,7 @@ impl Constellation { debug!("constellation sending resize message to active frame"); let pipeline = &frame_tree.pipeline; 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); } for frame_tree in self.navigation_context.previous.iter() @@ -805,7 +805,7 @@ impl Constellation { if !already_seen.contains(&pipeline.id) { debug!("constellation sending resize message to inactive frame"); 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); } } @@ -818,7 +818,7 @@ impl Constellation { debug!("constellation sending resize message to pending outer frame ({:?})", frame_tree.pipeline.id); 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)); } } diff --git a/src/components/main/css/matching.rs b/src/components/main/css/matching.rs index 3b883a315fa..73c9ef1d2a6 100644 --- a/src/components/main/css/matching.rs +++ b/src/components/main/css/matching.rs @@ -14,9 +14,9 @@ use layout::wrapper::{LayoutElement, LayoutNode, PostorderNodeMutTraversal, Thre use gfx::font_context::FontContext; use servo_util::cache::{Cache, LRUCache, SimpleHashCache}; use servo_util::namespace::Null; -use servo_util::smallvec::{SmallVec, SmallVec0, SmallVec16}; +use servo_util::smallvec::{SmallVec, SmallVec16}; use servo_util::str::DOMString; -use std::cast; +use std::mem; use std::hash::{Hash, sip}; use std::slice::Items; use style::{After, Before, ComputedValues, MatchedProperty, Stylist, TElement, TNode, cascade}; @@ -24,8 +24,8 @@ use sync::Arc; pub struct ApplicableDeclarations { pub normal: SmallVec16<MatchedProperty>, - pub before: SmallVec0<MatchedProperty>, - pub after: SmallVec0<MatchedProperty>, + pub before: Vec<MatchedProperty>, + pub after: Vec<MatchedProperty>, /// Whether the `normal` declarations are shareable with other nodes. pub normal_shareable: bool, @@ -35,28 +35,28 @@ impl ApplicableDeclarations { pub fn new() -> ApplicableDeclarations { ApplicableDeclarations { normal: SmallVec16::new(), - before: SmallVec0::new(), - after: SmallVec0::new(), + before: Vec::new(), + after: Vec::new(), normal_shareable: false, } } pub fn clear(&mut self) { self.normal = SmallVec16::new(); - self.before = SmallVec0::new(); - self.after = SmallVec0::new(); + self.before = Vec::new(); + self.after = Vec::new(); self.normal_shareable = false; } } #[deriving(Clone)] pub struct ApplicableDeclarationsCacheEntry { - pub declarations: SmallVec16<MatchedProperty>, + pub declarations: Vec<MatchedProperty>, } impl ApplicableDeclarationsCacheEntry { fn new(slice: &[MatchedProperty]) -> ApplicableDeclarationsCacheEntry { - let mut entry_declarations = SmallVec16::new(); + let mut entry_declarations = Vec::new(); for declarations in slice.iter() { entry_declarations.push(declarations.clone()); } @@ -96,8 +96,8 @@ impl<'a> ApplicableDeclarationsCacheQuery<'a> { #[inline] fn arc_ptr_eq<T>(a: &Arc<T>, b: &Arc<T>) -> bool { unsafe { - let a: uint = cast::transmute_copy(a); - let b: uint = cast::transmute_copy(b); + let a: uint = mem::transmute_copy(a); + let b: uint = mem::transmute_copy(b); a == b } } @@ -121,7 +121,7 @@ impl<'a> Hash for ApplicableDeclarationsCacheQuery<'a> { fn hash(&self, state: &mut sip::SipState) { for declaration in self.declarations.iter() { let ptr: uint = unsafe { - cast::transmute_copy(declaration) + mem::transmute_copy(declaration) }; ptr.hash(state); } @@ -231,12 +231,12 @@ impl StyleSharingCandidate { } 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 } match (&self.class, element.get_attr(&Null, "class")) { (&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 } (&Some(_), Some(_)) | (&None, None) => {} @@ -383,7 +383,7 @@ impl<'ln> PrivateMatchMethods for LayoutNode<'ln> { }; 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 { &Some(ref parent_layout_data_ref) => { diff --git a/src/components/main/css/node_util.rs b/src/components/main/css/node_util.rs index 63c5573389f..b67098984e8 100644 --- a/src/components/main/css/node_util.rs +++ b/src/components/main/css/node_util.rs @@ -6,7 +6,7 @@ use layout::incremental::RestyleDamage; use layout::util::LayoutDataAccess; use layout::wrapper::{TLayoutNode, ThreadSafeLayoutNode}; use layout::wrapper::{After, AfterBlock, Before, BeforeBlock, Normal}; -use std::cast; +use std::mem; use style::ComputedValues; use sync::Arc; @@ -27,28 +27,28 @@ impl<'ln> NodeUtil for ThreadSafeLayoutNode<'ln> { let layout_data_ref = self.borrow_layout_data(); match self.get_pseudo_element_type() { Before | BeforeBlock => { - cast::transmute_lifetime(layout_data_ref.as_ref() - .unwrap() - .data - .before_style - .as_ref() - .unwrap()) + mem::transmute(layout_data_ref.as_ref() + .unwrap() + .data + .before_style + .as_ref() + .unwrap()) } After | AfterBlock => { - cast::transmute_lifetime(layout_data_ref.as_ref() - .unwrap() - .data - .after_style - .as_ref() - .unwrap()) + mem::transmute(layout_data_ref.as_ref() + .unwrap() + .data + .after_style + .as_ref() + .unwrap()) } Normal => { - cast::transmute_lifetime(layout_data_ref.as_ref() - .unwrap() - .shared_data - .style - .as_ref() - .unwrap()) + mem::transmute(layout_data_ref.as_ref() + .unwrap() + .shared_data + .style + .as_ref() + .unwrap()) } } } diff --git a/src/components/main/layout/block.rs b/src/components/main/layout/block.rs index d0187afda8e..99bb0e076a8 100644 --- a/src/components/main/layout/block.rs +++ b/src/components/main/layout/block.rs @@ -1681,11 +1681,11 @@ impl Flow for BlockFlow { impl fmt::Show for BlockFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_float() { - write!(f.buf, "FloatFlow: {}", self.fragment) + write!(f, "FloatFlow: {}", self.fragment) } else if self.is_root() { - write!(f.buf, "RootFlow: {}", self.fragment) + write!(f, "RootFlow: {}", self.fragment) } else { - write!(f.buf, "BlockFlow: {}", self.fragment) + write!(f, "BlockFlow: {}", self.fragment) } } } diff --git a/src/components/main/layout/construct.rs b/src/components/main/layout/construct.rs index a6f7e97698e..4e9712caa8f 100644 --- a/src/components/main/layout/construct.rs +++ b/src/components/main/layout/construct.rs @@ -553,10 +553,10 @@ impl<'a> FlowConstructor<'a> { whitespace_style)) => { // 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, - whitespace_style.clone(), - fragment_info); + whitespace_style.clone(), + fragment_info); fragment_accumulator.fragments.push(fragment, whitespace_style) } ConstructionItemConstructionResult(TableColumnFragmentConstructionItem(_)) => { diff --git a/src/components/main/layout/context.rs b/src/components/main/layout/context.rs index cce7ba27502..f47cc6775ec 100644 --- a/src/components/main/layout/context.rs +++ b/src/components/main/layout/context.rs @@ -17,7 +17,7 @@ use servo_msg::constellation_msg::ConstellationChan; use servo_net::image::holder::LocalImageCacheHandle; use servo_util::geometry::Au; use servo_util::opts::Opts; -use std::cast; +use std::mem; #[cfg(not(target_os="android"))] use std::ptr; #[cfg(not(target_os="android"))] @@ -104,9 +104,9 @@ impl LayoutContext { unsafe { if FONT_CONTEXT == ptr::mut_null() { 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 { if APPLICABLE_DECLARATIONS_CACHE == ptr::mut_null() { 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 { if STYLE_SHARING_CANDIDATE_CACHE == ptr::mut_null() { 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 mut context; match opt { - Some(c) => context = cast::transmute(c), + Some(c) => context = mem::transmute(c), 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)); - cast::transmute(context) + mem::transmute(context) } } @@ -183,13 +183,13 @@ impl LayoutContext { let opt = applicable_declarations_cache.replace(None); let mut cache; match opt { - Some(c) => cache = cast::transmute(c), + Some(c) => cache = mem::transmute(c), None => { - cache = cast::transmute(box ApplicableDeclarationsCache::new()); + cache = mem::transmute(box ApplicableDeclarationsCache::new()); } } 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 mut cache; match opt { - Some(c) => cache = cast::transmute(c), + Some(c) => cache = mem::transmute(c), None => { - cache = cast::transmute(box StyleSharingCandidateCache::new()); + cache = mem::transmute(box StyleSharingCandidateCache::new()); } } style_sharing_candidate_cache.replace(Some(cache)); - cast::transmute(cache) + mem::transmute(cache) } } } diff --git a/src/components/main/layout/floats.rs b/src/components/main/layout/floats.rs index 007c508029e..15aae932b63 100644 --- a/src/components/main/layout/floats.rs +++ b/src/components/main/layout/floats.rs @@ -46,7 +46,7 @@ struct Float { impl fmt::Show for Float { 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 { 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 { 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 { match self.list.get() { None => { - write!(f.buf, "[empty]") + write!(f, "[empty]") } Some(list) => { - write!(f.buf, "offset={} floats={}", self.offset, list) + write!(f, "offset={} floats={}", self.offset, list) } } } diff --git a/src/components/main/layout/flow.rs b/src/components/main/layout/flow.rs index 4cf331473bb..dc8145d314c 100644 --- a/src/components/main/layout/flow.rs +++ b/src/components/main/layout/flow.rs @@ -53,7 +53,7 @@ use gfx::display_list::DisplayList; use gfx::render_task::RenderLayer; use servo_msg::compositor_msg::LayerId; use servo_util::geometry::Au; -use std::cast; +use std::mem; use std::fmt; use std::iter::Zip; use std::num::Zero; @@ -263,7 +263,7 @@ pub trait Flow: fmt::Show + ToStr + Share { /// Returns a layer ID for the given fragment. fn layer_id(&self, fragment_id: uint) -> LayerId { unsafe { - let pointer: uint = cast::transmute(self); + let pointer: uint = mem::transmute(self); LayerId(pointer, fragment_id) } } @@ -274,7 +274,7 @@ pub trait Flow: fmt::Show + ToStr + Share { #[inline(always)] pub fn base<'a>(this: &'a Flow) -> &'a BaseFlow { unsafe { - let (_, ptr): (uint, &BaseFlow) = cast::transmute(this); + let (_, ptr): (uint, &BaseFlow) = mem::transmute(this); ptr } } @@ -287,7 +287,7 @@ pub fn imm_child_iter<'a>(flow: &'a Flow) -> FlowListIterator<'a> { #[inline(always)] pub fn mut_base<'a>(this: &'a mut Flow) -> &'a mut BaseFlow { unsafe { - let (_, ptr): (uint, &mut BaseFlow) = cast::transmute(this); + let (_, ptr): (uint, &mut BaseFlow) = mem::transmute(this); ptr } } @@ -582,7 +582,7 @@ impl<'a> Iterator<&'a mut Flow> for DescendantIter<'a> { None => None, Some(ref mut flow) => { unsafe { - let result: &'a mut Flow = cast::transmute(flow.get_mut()); + let result: &'a mut Flow = mem::transmute(flow.get_mut()); 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. fn dump_with_level(self, level: uint) { - let mut indent = StrBuf::new(); + let mut indent = String::new(); for _ in range(0, level) { indent.push_str("| ") } diff --git a/src/components/main/layout/flow_list.rs b/src/components/main/layout/flow_list.rs index e0646433e71..93e2fe475a1 100644 --- a/src/components/main/layout/flow_list.rs +++ b/src/components/main/layout/flow_list.rs @@ -8,7 +8,6 @@ use layout::flow::{Flow, base, mut_base}; use layout::flow_ref::FlowRef; -use std::cast; use std::mem; use std::ptr; @@ -56,7 +55,7 @@ impl Rawlink { /// Like Option::Some for 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 { @@ -70,7 +69,7 @@ impl Rawlink { if self.obj.is_null() { None } else { - let me: &mut Flow = cast::transmute_copy(self); + let me: &mut Flow = mem::transmute_copy(self); Some(me) } } @@ -128,7 +127,7 @@ impl FlowList { None => None, Some(ref mut tail) => { let x: &mut Flow = tail.get_mut(); - Some(cast::transmute_copy(&x)) + Some(mem::transmute_copy(&x)) } } } diff --git a/src/components/main/layout/flow_ref.rs b/src/components/main/layout/flow_ref.rs index 8b10d5a41f6..3ad20a9b6f0 100644 --- a/src/components/main/layout/flow_ref.rs +++ b/src/components/main/layout/flow_ref.rs @@ -9,7 +9,6 @@ use layout::flow::Flow; use layout::flow; -use std::cast; use std::mem; use std::ptr; use std::sync::atomics::SeqCst; @@ -25,22 +24,22 @@ impl FlowRef { unsafe { let result = { let flow_ref: &mut Flow = flow; - cast::transmute(flow_ref) + mem::transmute(flow_ref) }; - cast::forget(flow); + mem::forget(flow); result } } pub fn get<'a>(&'a self) -> &'a Flow { unsafe { - cast::transmute_copy(self) + mem::transmute_copy(self) } } pub fn get_mut<'a>(&'a mut self) -> &'a mut Flow { unsafe { - cast::transmute_copy(self) + mem::transmute_copy(self) } } } @@ -58,7 +57,7 @@ impl Drop for FlowRef { vtable: 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.ptr = ptr::null(); } diff --git a/src/components/main/layout/fragment.rs b/src/components/main/layout/fragment.rs index 713daf72368..72a1e2d3be0 100644 --- a/src/components/main/layout/fragment.rs +++ b/src/components/main/layout/fragment.rs @@ -263,7 +263,7 @@ impl SplitInfo { #[deriving(Clone)] pub struct UnscannedTextFragmentInfo { /// The text inside the fragment. - pub text: ~str, + pub text: String, } impl UnscannedTextFragmentInfo { @@ -277,7 +277,7 @@ impl UnscannedTextFragmentInfo { /// Creates a new instance of `UnscannedTextFragmentInfo` from the given text. #[inline] - pub fn from_text(text: ~str) -> UnscannedTextFragmentInfo { + pub fn from_text(text: String) -> UnscannedTextFragmentInfo { UnscannedTextFragmentInfo { text: text, } @@ -1245,7 +1245,7 @@ impl Fragment { /// Returns true if this fragment is an unscanned text fragment that consists entirely of whitespace. pub fn is_whitespace_only(&self) -> bool { 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, } } @@ -1407,12 +1407,12 @@ impl Fragment { if value.is_zero() { Ok(()) } else { - write!(f.buf, "{}{},{},{},{}", - name, - value.top, - value.right, - value.bottom, - value.left) + write!(f, "{}{},{},{},{}", + name, + value.top, + value.right, + value.bottom, + value.left) } } @@ -1443,7 +1443,7 @@ impl Fragment { impl fmt::Show for Fragment { /// Outputs a debugging string describing this fragment. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f.buf, "({} ", + try!(write!(f, "({} ", match self.specific { GenericFragment => "GenericFragment", IframeFragment(_) => "IframeFragment", @@ -1457,9 +1457,9 @@ impl fmt::Show for Fragment { UnscannedTextFragment(_) => "UnscannedTextFragment", })); 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)); - write!(f.buf, ")") + write!(f, ")") } } diff --git a/src/components/main/layout/inline.rs b/src/components/main/layout/inline.rs index 3318aa62ab2..5efc5002952 100644 --- a/src/components/main/layout/inline.rs +++ b/src/components/main/layout/inline.rs @@ -245,7 +245,7 @@ impl Neg<LineIndices> for LineIndices { impl fmt::Show for LineIndices { 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 { 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() { if i == 0 { - try!(write!(f.buf, ": {}", fragment)) + try!(write!(f, ": {}", fragment)) } else { - try!(write!(f.buf, ", {}", fragment)) + try!(write!(f, ", {}", fragment)) } } Ok(()) diff --git a/src/components/main/layout/layout_task.rs b/src/components/main/layout/layout_task.rs index 6cede7b1d9c..fe9ebc2aa65 100644 --- a/src/components/main/layout/layout_task.rs +++ b/src/components/main/layout/layout_task.rs @@ -54,8 +54,6 @@ use servo_util::time::{ProfilerChan, profile}; use servo_util::time; use servo_util::task::send_on_failure; use servo_util::workqueue::WorkQueue; -use std::cast::transmute; -use std::cast; use std::comm::{channel, Sender, Receiver}; use std::mem; use std::ptr; @@ -318,8 +316,8 @@ impl LayoutTask { let local_image_cache = box LocalImageCache(image_cache_task.clone()); let local_image_cache = unsafe { let cache = Arc::new(Mutex::new( - cast::transmute::<Box<LocalImageCache>, *()>(local_image_cache))); - LocalImageCacheHandle::new(cast::transmute::<Arc<Mutex<*()>>,Arc<*()>>(cache)) + mem::transmute::<Box<LocalImageCache>, *()>(local_image_cache))); + LocalImageCacheHandle::new(mem::transmute::<Arc<Mutex<*()>>,Arc<*()>>(cache)) }; let screen_size = Size2D(Au(0), Au(0)); let parallel_traversal = if opts.layout_threads != 1 { @@ -562,7 +560,7 @@ impl LayoutTask { // FIXME: Isolate this transmutation into a "bridge" module. let node: &mut LayoutNode = unsafe { 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()); @@ -914,7 +912,7 @@ impl LayoutTask { /// because it contains local managed pointers. unsafe fn handle_reap_layout_data(&self, layout_data: LayoutDataRef) { 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)); } } diff --git a/src/components/main/layout/model.rs b/src/components/main/layout/model.rs index b0adfbabc82..855dda384ec 100644 --- a/src/components/main/layout/model.rs +++ b/src/components/main/layout/model.rs @@ -254,7 +254,7 @@ pub struct IntrinsicWidths { impl fmt::Show for IntrinsicWidths { 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) } } diff --git a/src/components/main/layout/parallel.rs b/src/components/main/layout/parallel.rs index 6c4c2292c39..e4f7b31ae88 100644 --- a/src/components/main/layout/parallel.rs +++ b/src/components/main/layout/parallel.rs @@ -15,7 +15,7 @@ use layout::flow; use layout::flow_ref::FlowRef; use layout::layout_task::{AssignHeightsAndStoreOverflowTraversal, AssignWidthsTraversal}; 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::{ThreadSafeLayoutNode, UnsafeLayoutNode}; @@ -23,7 +23,7 @@ use gfx::display_list::OpaqueNode; use servo_util::time::{ProfilerChan, profile}; use servo_util::time; use servo_util::workqueue::{WorkQueue, WorkUnit, WorkerProxy}; -use std::cast; +use std::mem; use std::ptr; use std::sync::atomics::{AtomicInt, Relaxed, SeqCst}; use style::{Stylist, TNode}; @@ -66,25 +66,25 @@ fn null_unsafe_flow() -> UnsafeFlow { pub fn owned_flow_to_unsafe_flow(flow: *FlowRef) -> UnsafeFlow { unsafe { - cast::transmute_copy(&*flow) + mem::transmute_copy(&*flow) } } pub fn mut_owned_flow_to_unsafe_flow(flow: *mut FlowRef) -> UnsafeFlow { unsafe { - cast::transmute_copy(&*flow) + mem::transmute_copy(&*flow) } } pub fn borrowed_flow_to_unsafe_flow(flow: &Flow) -> UnsafeFlow { unsafe { - cast::transmute_copy(&flow) + mem::transmute_copy(&flow) } } pub fn mut_borrowed_flow_to_unsafe_flow(flow: &mut Flow) -> UnsafeFlow { unsafe { - cast::transmute_copy(&flow) + mem::transmute_copy(&flow) } } @@ -142,7 +142,7 @@ trait ParallelPostorderFlowTraversal : PostorderFlowTraversal { loop { unsafe { // Get a real flow. - let flow: &mut FlowRef = cast::transmute(&unsafe_flow); + let flow: &mut FlowRef = mem::transmute(&unsafe_flow); // Perform the appropriate traversal. 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 // of our parent to finish processing? If so, we can continue // 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()); if parent_base.parallel.children_count.fetch_sub(1, SeqCst) == 1 { // We were the last child of our parent. Reflow our parent. @@ -197,7 +197,7 @@ trait ParallelPreorderFlowTraversal : PreorderFlowTraversal { let mut had_children = false; unsafe { // Get a real flow. - let flow: &mut FlowRef = cast::transmute(&unsafe_flow); + let flow: &mut FlowRef = mem::transmute(&unsafe_flow); // Perform the appropriate traversal. self.process(flow.get_mut()); @@ -238,7 +238,7 @@ impl<'a> ParallelPostorderFlowTraversal for AssignHeightsAndStoreOverflowTravers fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode, proxy: &mut WorkerProxy<*mut LayoutContext,UnsafeLayoutNode>) { 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. 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() { // 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); } @@ -327,12 +327,12 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode, proxy: &mut WorkerProxy<*mut LayoutContext,UnsafeLayoutNode>) { loop { let layout_context: &mut LayoutContext = unsafe { - cast::transmute(*proxy.user_data()) + mem::transmute(*proxy.user_data()) }; // Get a real layout node. let node: LayoutNode = unsafe { - cast::transmute(unsafe_layout_node) + mem::transmute(unsafe_layout_node) }; // Construct flows for this node. @@ -373,7 +373,7 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode, unsafe { match *parent.borrow_layout_data_unchecked() { 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 .parallel .children_count @@ -398,7 +398,7 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode, fn assign_widths(unsafe_flow: PaddedUnsafeFlow, proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) { let layout_context: &mut LayoutContext = unsafe { - cast::transmute(*proxy.user_data()) + mem::transmute(*proxy.user_data()) }; let mut assign_widths_traversal = AssignWidthsTraversal { layout_context: layout_context, @@ -409,7 +409,7 @@ fn assign_widths(unsafe_flow: PaddedUnsafeFlow, fn assign_heights_and_store_overflow(unsafe_flow: PaddedUnsafeFlow, proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) { let layout_context: &mut LayoutContext = unsafe { - cast::transmute(*proxy.user_data()) + mem::transmute(*proxy.user_data()) }; let mut assign_heights_traversal = AssignHeightsAndStoreOverflowTraversal { layout_context: layout_context, @@ -422,7 +422,7 @@ fn compute_absolute_position(unsafe_flow: PaddedUnsafeFlow, let mut had_descendants = false; unsafe { // 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. 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, proxy: &mut WorkerProxy<*mut LayoutContext,PaddedUnsafeFlow>) { let layout_context: &mut LayoutContext = unsafe { - cast::transmute(*proxy.user_data()) + mem::transmute(*proxy.user_data()) }; loop { unsafe { // Get a real flow. - let flow: &mut FlowRef = cast::transmute(&unsafe_flow); + let flow: &mut FlowRef = mem::transmute(&unsafe_flow); // Build display lists. 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 // of our parent to finish processing? If so, we can continue // 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()); if parent_base.parallel .children_and_absolute_descendant_count @@ -536,7 +536,7 @@ pub fn recalc_style_for_subtree(root_node: &LayoutNode, layout_context: &mut LayoutContext, queue: &mut WorkQueue<*mut LayoutContext,UnsafeLayoutNode>) { unsafe { - queue.data = cast::transmute(layout_context) + queue.data = mem::transmute(layout_context) } // Enqueue the root node. @@ -555,7 +555,7 @@ pub fn traverse_flow_tree_preorder(root: &mut FlowRef, layout_context: &mut LayoutContext, queue: &mut WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>) { unsafe { - queue.data = cast::transmute(layout_context) + queue.data = mem::transmute(layout_context) } profile(time::LayoutParallelWarmupCategory, profiler_chan, || { @@ -575,7 +575,7 @@ pub fn build_display_list_for_subtree(root: &mut FlowRef, layout_context: &mut LayoutContext, queue: &mut WorkQueue<*mut LayoutContext,PaddedUnsafeFlow>) { unsafe { - queue.data = cast::transmute(layout_context) + queue.data = mem::transmute(layout_context) } profile(time::LayoutParallelWarmupCategory, profiler_chan, || { diff --git a/src/components/main/layout/table.rs b/src/components/main/layout/table.rs index daef27fbc76..88dc99562c2 100644 --- a/src/components/main/layout/table.rs +++ b/src/components/main/layout/table.rs @@ -295,7 +295,7 @@ impl Flow for TableFlow { impl fmt::Show for TableFlow { /// Outputs a debugging string describing this table flow. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "TableFlow: {}", self.block_flow) + write!(f, "TableFlow: {}", self.block_flow) } } diff --git a/src/components/main/layout/table_caption.rs b/src/components/main/layout/table_caption.rs index dc6f62e8b59..658da63e603 100644 --- a/src/components/main/layout/table_caption.rs +++ b/src/components/main/layout/table_caption.rs @@ -68,6 +68,6 @@ impl Flow for TableCaptionFlow { impl fmt::Show for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "TableCaptionFlow: {}", self.block_flow) + write!(f, "TableCaptionFlow: {}", self.block_flow) } } diff --git a/src/components/main/layout/table_cell.rs b/src/components/main/layout/table_cell.rs index 8c26118ae92..43847539781 100644 --- a/src/components/main/layout/table_cell.rs +++ b/src/components/main/layout/table_cell.rs @@ -116,6 +116,6 @@ impl Flow for TableCellFlow { impl fmt::Show for TableCellFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "TableCellFlow: {}", self.block_flow) + write!(f, "TableCellFlow: {}", self.block_flow) } } diff --git a/src/components/main/layout/table_colgroup.rs b/src/components/main/layout/table_colgroup.rs index ed281703357..6c3c0189ebe 100644 --- a/src/components/main/layout/table_colgroup.rs +++ b/src/components/main/layout/table_colgroup.rs @@ -81,8 +81,8 @@ impl Flow for TableColGroupFlow { impl fmt::Show for TableColGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.fragment { - Some(ref rb) => write!(f.buf, "TableColGroupFlow: {}", rb), - None => write!(f.buf, "TableColGroupFlow"), + Some(ref rb) => write!(f, "TableColGroupFlow: {}", rb), + None => write!(f, "TableColGroupFlow"), } } } diff --git a/src/components/main/layout/table_row.rs b/src/components/main/layout/table_row.rs index 06594e60bba..065d43dc291 100644 --- a/src/components/main/layout/table_row.rs +++ b/src/components/main/layout/table_row.rs @@ -220,6 +220,6 @@ impl Flow for TableRowFlow { impl fmt::Show for TableRowFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "TableRowFlow: {}", self.block_flow.fragment) + write!(f, "TableRowFlow: {}", self.block_flow.fragment) } } diff --git a/src/components/main/layout/table_rowgroup.rs b/src/components/main/layout/table_rowgroup.rs index 644f2ee5125..c669dc79b6e 100644 --- a/src/components/main/layout/table_rowgroup.rs +++ b/src/components/main/layout/table_rowgroup.rs @@ -202,6 +202,6 @@ impl Flow for TableRowGroupFlow { impl fmt::Show for TableRowGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "TableRowGroupFlow: {}", self.block_flow.fragment) + write!(f, "TableRowGroupFlow: {}", self.block_flow.fragment) } } diff --git a/src/components/main/layout/table_wrapper.rs b/src/components/main/layout/table_wrapper.rs index c83dabaa30c..6f8cc8fcc57 100644 --- a/src/components/main/layout/table_wrapper.rs +++ b/src/components/main/layout/table_wrapper.rs @@ -196,9 +196,9 @@ impl Flow for TableWrapperFlow { impl fmt::Show for TableWrapperFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_float() { - write!(f.buf, "TableWrapperFlow(Float): {}", self.block_flow.fragment) + write!(f, "TableWrapperFlow(Float): {}", self.block_flow.fragment) } else { - write!(f.buf, "TableWrapperFlow: {}", self.block_flow.fragment) + write!(f, "TableWrapperFlow: {}", self.block_flow.fragment) } } } diff --git a/src/components/main/layout/text.rs b/src/components/main/layout/text.rs index ca27a542a82..41082b8ed6e 100644 --- a/src/components/main/layout/text.rs +++ b/src/components/main/layout/text.rs @@ -131,7 +131,7 @@ impl TextRunScanner { let mut new_line_pos = vec![]; - let (transformed_text, whitespace) = transform_text(*text, + let (transformed_text, whitespace) = transform_text(text.as_slice(), compression, last_whitespace, &mut new_line_pos); @@ -177,7 +177,7 @@ impl TextRunScanner { // First, transform/compress text of all the nodes. 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 // `transform_text`, so that fragments starting and/or ending with whitespace can // be compressed correctly with respect to the text run. @@ -189,7 +189,7 @@ impl TextRunScanner { 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, last_whitespace_in_clump, &mut new_line_pos); @@ -202,13 +202,13 @@ impl TextRunScanner { // Next, concatenate all of the transformed strings together, saving the new // character indices. - let mut run_str = StrBuf::new(); + let mut run_str = String::new(); let mut new_ranges: Vec<Range<CharIndex>> = vec![]; let mut char_total = CharIndex(0); 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)); - 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; } diff --git a/src/components/main/layout/util.rs b/src/components/main/layout/util.rs index 3f94b4ff4e2..3a37cdd0d03 100644 --- a/src/components/main/layout/util.rs +++ b/src/components/main/layout/util.rs @@ -13,7 +13,7 @@ use script::dom::bindings::js::JS; use script::dom::bindings::utils::Reflectable; use script::dom::node::{Node, SharedLayoutData}; use script::layout_interface::{LayoutChan, UntrustedNodeAddress, TrustedNodeAddress}; -use std::cast; +use std::mem; use std::cell::{Ref, RefMut}; use style::ComputedValues; use style; @@ -76,20 +76,20 @@ pub trait LayoutDataAccess { impl<'ln> LayoutDataAccess for LayoutNode<'ln> { #[inline(always)] 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)] fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> { unsafe { - cast::transmute(self.get().layout_data.borrow()) + mem::transmute(self.get().layout_data.borrow()) } } #[inline(always)] fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> { 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 { unsafe { - let ptr: uintptr_t = cast::transmute(node.reflector().get_jsobject()); + let ptr: uintptr_t = mem::transmute(node.reflector().get_jsobject()); OpaqueNode(ptr) } } @@ -143,7 +143,7 @@ impl OpaqueNodeMethods for OpaqueNode { fn to_untrusted_node_address(&self) -> UntrustedNodeAddress { unsafe { let OpaqueNode(addr) = *self; - let addr: UntrustedNodeAddress = cast::transmute(addr); + let addr: UntrustedNodeAddress = mem::transmute(addr); addr } } diff --git a/src/components/main/layout/wrapper.rs b/src/components/main/layout/wrapper.rs index 779416f8de8..b6a475af271 100644 --- a/src/components/main/layout/wrapper.rs +++ b/src/components/main/layout/wrapper.rs @@ -50,9 +50,9 @@ use servo_msg::constellation_msg::{PipelineId, SubpageId}; use servo_util::namespace::Namespace; use servo_util::namespace; use servo_util::str::is_whitespace; -use std::cast; use std::cell::{Ref, RefMut}; use std::kinds::marker::ContravariantLifetime; +use std::mem; use style::computed_values::{content, display, white_space}; use style::{AnyNamespace, AttrSelector, PropertyDeclarationBlock, SpecificNamespace, TElement}; 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. /// /// 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. 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 { if !self.get().is_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 element = &*elem.unsafe_get(); 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 { content::Content(ref value) => { let iter = &mut value.clone().move_iter().peekable(); match iter.next() { 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. - 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>> { @@ -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 { let layout_data_ref = self.borrow_layout_data(); let node_layout_data_wrapper = layout_data_ref.get_ref(); @@ -595,7 +595,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> { #[inline(always)] pub fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> { 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)] pub fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> { 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) => { unsafe { 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 } @@ -748,6 +748,6 @@ pub type UnsafeLayoutNode = (uint, uint); pub fn layout_node_to_unsafe_layout_node(node: &LayoutNode) -> UnsafeLayoutNode { unsafe { - cast::transmute_copy(node) + mem::transmute_copy(node) } } diff --git a/src/components/main/pipeline.rs b/src/components/main/pipeline.rs index e2a8f5fbdc2..b3f18b01d8d 100644 --- a/src/components/main/pipeline.rs +++ b/src/components/main/pipeline.rs @@ -197,12 +197,12 @@ impl Pipeline { } 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) { debug!("pipeline revoking render channel paint permission"); - self.render_chan.send_opt(PaintPermissionRevoked); + let _ = self.render_chan.send_opt(PaintPermissionRevoked); } pub fn exit(&self) { @@ -214,8 +214,8 @@ impl Pipeline { if chan.send_opt(script_task::ExitPipelineMsg(self.id)).is_ok() { // 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 - self.render_shutdown_port.recv_opt(); - self.layout_shutdown_port.recv_opt(); + let _ = self.render_shutdown_port.recv_opt(); + let _ = self.layout_shutdown_port.recv_opt(); } } diff --git a/src/components/main/platform/common/glfw_windowing.rs b/src/components/main/platform/common/glfw_windowing.rs index e5571ad757a..68dad142c04 100644 --- a/src/components/main/platform/common/glfw_windowing.rs +++ b/src/components/main/platform/common/glfw_windowing.rs @@ -337,8 +337,8 @@ impl Window { alert.add_prompt(); alert.run(); let value = alert.prompt_value(); - if "" == value { // To avoid crashing on Linux. - self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_owned())) + if "" == value.as_slice() { // To avoid crashing on Linux. + self.event_queue.borrow_mut().push(LoadUrlWindowEvent("http://purple.com/".to_string())) } else { self.event_queue.borrow_mut().push(LoadUrlWindowEvent(value.clone())) } diff --git a/src/components/main/servo.rs b/src/components/main/servo.rs index 14912a7e179..543244de0ba 100644 --- a/src/components/main/servo.rs +++ b/src/components/main/servo.rs @@ -11,6 +11,8 @@ #[phase(syntax, link)] extern crate log; +extern crate debug; + extern crate alert; extern crate azure; extern crate geom; @@ -131,7 +133,7 @@ pub mod platform; #[allow(dead_code)] fn start(argc: int, argv: **u8) -> int { 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. 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, // assume that data URLs are not URL-encoded. - Url::new("data".to_owned(), None, "".to_owned(), None, - filename.slice_from(5).to_owned(), vec!(), None) + Url::new("data".to_string(), None, "".to_string(), None, + filename.as_slice().slice_from(5).to_string(), vec!(), None) } else { - parse_url(*filename, None) + parse_url(filename.as_slice(), None) }; let ConstellationChan(ref chan) = constellation_chan; diff --git a/src/components/main/windowing.rs b/src/components/main/windowing.rs index 1a66a90181a..23767085bbb 100644 --- a/src/components/main/windowing.rs +++ b/src/components/main/windowing.rs @@ -32,7 +32,7 @@ pub enum WindowEvent { /// Sent when the window is resized. ResizeWindowEvent(uint, uint), /// Sent when a new URL is to be loaded. - LoadUrlWindowEvent(~str), + LoadUrlWindowEvent(String), /// Sent when a mouse hit test is to be performed. MouseWindowEventClass(MouseWindowEvent), /// Sent when a mouse move. diff --git a/src/components/msg/compositor_msg.rs b/src/components/msg/compositor_msg.rs index 9ad88386b31..d96798b3184 100644 --- a/src/components/msg/compositor_msg.rs +++ b/src/components/msg/compositor_msg.rs @@ -83,8 +83,7 @@ pub struct LayerId(pub uint, pub uint); impl Show for LayerId { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let LayerId(a, b) = *self; - write!(f.buf, "Layer({}, {})", a, b); - Ok(()) + write!(f, "Layer({}, {})", a, b) } } diff --git a/src/components/msg/platform/linux/surface.rs b/src/components/msg/platform/linux/surface.rs index 3ebd1d5b643..60cc84bc965 100644 --- a/src/components/msg/platform/linux/surface.rs +++ b/src/components/msg/platform/linux/surface.rs @@ -8,12 +8,12 @@ use platform::surface::NativeSurfaceAzureMethods; use azure::AzSkiaGrGLSharedSurfaceRef; use layers::platform::surface::NativeSurface; -use std::cast; +use std::mem; impl NativeSurfaceAzureMethods for NativeSurface { fn from_azure_surface(surface: AzSkiaGrGLSharedSurfaceRef) -> NativeSurface { unsafe { - NativeSurface::from_pixmap(cast::transmute(surface)) + NativeSurface::from_pixmap(mem::transmute(surface)) } } } diff --git a/src/components/msg/platform/macos/surface.rs b/src/components/msg/platform/macos/surface.rs index eee7d091317..30b5e405500 100644 --- a/src/components/msg/platform/macos/surface.rs +++ b/src/components/msg/platform/macos/surface.rs @@ -10,13 +10,13 @@ use platform::surface::NativeSurfaceAzureMethods; use azure::AzSkiaGrGLSharedSurfaceRef; use io_surface::IOSurface; use layers::platform::surface::NativeSurface; -use std::cast; +use std::mem; impl NativeSurfaceAzureMethods for NativeSurface { fn from_azure_surface(surface: AzSkiaGrGLSharedSurfaceRef) -> NativeSurface { unsafe { let io_surface = IOSurface { - obj: cast::transmute(surface), + obj: mem::transmute(surface), }; NativeSurface::from_io_surface(io_surface) } diff --git a/src/components/net/data_loader.rs b/src/components/net/data_loader.rs index 4719b114e7b..8aee4907467 100644 --- a/src/components/net/data_loader.rs +++ b/src/components/net/data_loader.rs @@ -20,21 +20,21 @@ pub fn factory() -> LoaderTask { fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { let url = load_data.url; - assert!("data" == url.scheme); + assert!("data" == url.scheme.as_slice()); let mut metadata = Metadata::default(url.clone()); // 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 { - 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; } // ";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. let mut is_base64 = false; - let mut ct_str = parts[0]; + let mut ct_str = *parts.get(0); if ct_str.ends_with(";base64") { is_base64 = true; 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); if is_base64 { - match parts[1].from_base64() { + match (*parts.get(1)).from_base64() { 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) => { - let data: ~[u8] = data; + let data: Vec<u8> = data; progress_chan.send(Payload(data.move_iter().collect())); progress_chan.send(Done(Ok(()))); } @@ -61,7 +61,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { } else { // FIXME: Since the %-decoded URL is already a str, we can't // 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(Done(Ok(()))); } @@ -69,8 +69,8 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { #[cfg(test)] fn assert_parse(url: &'static str, - content_type: Option<(~str, ~str)>, - charset: Option<~str>, + content_type: Option<(String, String)>, + charset: Option<String>, data: Option<Vec<u8>>) { use std::from_str::FromStr; use std::comm; @@ -86,7 +86,7 @@ fn assert_parse(url: &'static str, match data { None => { - assert_eq!(progress, Done(Err("invalid data uri".to_owned()))); + assert_eq!(progress, Done(Err("invalid data uri".to_string()))); } Some(dat) => { assert_eq!(progress, Payload(dat)); @@ -108,13 +108,13 @@ fn plain() { #[test] fn plain_ct() { 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] fn plain_charset() { 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] @@ -125,12 +125,12 @@ fn base64() { #[test] fn base64_ct() { 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] fn base64_charset() { 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))); } diff --git a/src/components/net/file_loader.rs b/src/components/net/file_loader.rs index a7635a9e16e..8c76ccbdecf 100644 --- a/src/components/net/file_loader.rs +++ b/src/components/net/file_loader.rs @@ -12,14 +12,14 @@ use servo_util::task::spawn_named; static READ_SIZE: uint = 1; fn read_all(reader: &mut io::Stream, progress_chan: &Sender<ProgressMsg>) - -> Result<(), ~str> { + -> Result<(), String> { loop { 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)), Err(e) => match e.kind { 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 { let f: LoaderTask = proc(load_data, start_chan) { 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())); spawn_named("file_loader", proc() { 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)); } Err(e) => { - progress_chan.send(Done(Err(e.desc.to_owned()))); + progress_chan.send(Done(Err(e.desc.to_string()))); } }; }); diff --git a/src/components/net/http_loader.rs b/src/components/net/http_loader.rs index aa4583a6e3b..dbf9f1d4660 100644 --- a/src/components/net/http_loader.rs +++ b/src/components/net/http_loader.rs @@ -18,7 +18,7 @@ pub fn factory() -> LoaderTask { 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))); } @@ -36,18 +36,18 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { iters = iters + 1; 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; } if redirected_to.contains(&url) { - send_error(url, "redirect loop".to_owned(), start_chan); + send_error(url, "redirect loop".to_string(), start_chan); return; } 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); send_error(url, s, start_chan); return; @@ -59,7 +59,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { let mut writer = match request { Ok(w) => box w, Err(e) => { - send_error(url, e.desc.to_owned(), start_chan); + send_error(url, e.desc.to_string(), start_chan); return; } }; @@ -74,7 +74,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { writer.headers.content_length = Some(data.len()); match writer.write(data.clone().into_bytes().as_slice()) { Err(e) => { - send_error(url, e.desc.to_owned(), start_chan); + send_error(url, e.desc.to_string(), start_chan); return; } _ => {} @@ -85,7 +85,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { let mut response = match writer.read_response() { Ok(r) => r, Err((_, e)) => { - send_error(url, e.desc.to_owned(), start_chan); + send_error(url, e.desc.to_string(), start_chan); return; } }; diff --git a/src/components/net/image/base.rs b/src/components/net/image/base.rs index b01c0b7ec20..67eaa0835b2 100644 --- a/src/components/net/image/base.rs +++ b/src/components/net/image/base.rs @@ -41,6 +41,10 @@ fn byte_swap(color_type: png::ColorType, data: &mut [u8]) { } pub fn load_from_memory(buffer: &[u8]) -> Option<Image> { + if buffer.len() == 0 { + return None; + } + if png::is_png(buffer) { match png::load_png_from_memory(buffer) { Ok(mut png_image) => { diff --git a/src/components/net/image/holder.rs b/src/components/net/image/holder.rs index 83c1fa817a4..abe5b208f2e 100644 --- a/src/components/net/image/holder.rs +++ b/src/components/net/image/holder.rs @@ -7,7 +7,6 @@ use image_cache_task::{ImageReady, ImageNotReady, ImageFailed}; use local_image_cache::LocalImageCache; use geom::size::Size2D; -use std::cast; use std::mem; use std::ptr; use sync::{Arc, Mutex}; @@ -26,7 +25,7 @@ impl Drop for LocalImageCacheHandle { fn drop(&mut self) { unsafe { 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 { fn clone(&self) -> LocalImageCacheHandle { 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(); LocalImageCacheHandle::new(new_handle) } @@ -44,13 +43,13 @@ impl Clone for LocalImageCacheHandle { impl LocalImageCacheHandle { pub unsafe fn new(cache: Arc<*()>) -> LocalImageCacheHandle { LocalImageCacheHandle { - data: cast::transmute(box cache), + data: mem::transmute(box cache), } } pub fn get<'a>(&'a self) -> &'a Arc<Mutex<Box<LocalImageCache>>> { unsafe { - cast::transmute::<*uint,&'a Arc<Mutex<Box<LocalImageCache>>>>(self.data) + mem::transmute::<*uint,&'a Arc<Mutex<Box<LocalImageCache>>>>(self.data) } } } diff --git a/src/components/net/image_cache_task.rs b/src/components/net/image_cache_task.rs index 746ec0d8df0..80c9497b475 100644 --- a/src/components/net/image_cache_task.rs +++ b/src/components/net/image_cache_task.rs @@ -36,7 +36,7 @@ pub enum Msg { // FIXME: We can probably get rid of this Cell now /// 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 StoreImage(Url, Option<Arc<Box<Image>>>), @@ -147,7 +147,7 @@ struct ImageCache { enum ImageState { Init, Prefetching(AfterPrefetch), - Prefetched(~[u8]), + Prefetched(Vec<u8>), Decoding, Decoded(Arc<Box<Image>>), 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()) { Prefetching(next_step) => { match data { @@ -318,7 +318,7 @@ impl ImageCache { spawn(proc() { let url = url_clone; 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() { Some(Arc::new(box image.unwrap())) } 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(); resource_task.send(resource_task::Load(LoadData::new(url), response_chan)); @@ -533,7 +533,7 @@ mod tests { impl Closure for SendTestImageErr { fn invoke(&self, response: Sender<resource_task::ProgressMsg>) { 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 self.wait_port.recv(); 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) => { let chan = start_sending(response, Metadata::default(parse_url("file:///fake", None))); 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(()); } resource_task::Exit => { diff --git a/src/components/net/net.rs b/src/components/net/net.rs index 17c5b937671..3ea211292ce 100644 --- a/src/components/net/net.rs +++ b/src/components/net/net.rs @@ -9,6 +9,7 @@ #![feature(default_type_params, globs, managed_boxes, phase)] +extern crate debug; extern crate collections; extern crate geom; extern crate http; diff --git a/src/components/net/resource_task.rs b/src/components/net/resource_task.rs index c996e70e9b0..fcb9af5dd58 100644 --- a/src/components/net/resource_task.rs +++ b/src/components/net/resource_task.rs @@ -33,7 +33,7 @@ pub struct LoadData { pub url: Url, pub method: Method, pub headers: RequestHeaderCollection, - pub data: Option<~str> + pub data: Option<String> } impl LoadData { @@ -53,10 +53,10 @@ pub struct Metadata { pub final_url: Url, /// MIME type / subtype. - pub content_type: Option<(~str, ~str)>, + pub content_type: Option<(String, String)>, /// Character set. - pub charset: Option<~str>, + pub charset: Option<String>, /// Headers pub headers: Option<ResponseHeaderCollection>, @@ -84,10 +84,10 @@ impl Metadata { Some(MediaType { type_: ref type_, subtype: ref subtype, 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() { 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 Payload(Vec<u8>), /// Indicates loading is complete, either successfully or not - Done(Result<(), ~str>) + Done(Result<(), String>) } /// 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. 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(); resource_task.send(Load(LoadData::new(url), start_chan)); let response = start_port.recv(); @@ -159,14 +159,14 @@ type LoaderTaskFactory = extern "Rust" fn() -> LoaderTask; /// Create a ResourceTask with the default loaders pub fn ResourceTask() -> ResourceTask { let loaders = vec!( - ("file".to_owned(), file_loader::factory), - ("http".to_owned(), http_loader::factory), - ("data".to_owned(), data_loader::factory), + ("file".to_string(), file_loader::factory), + ("http".to_string(), http_loader::factory), + ("data".to_string(), data_loader::factory), ); 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 builder = TaskBuilder::new().named("ResourceManager"); builder.spawn(proc() { @@ -180,12 +180,12 @@ fn create_resource_task_with_loaders(loaders: Vec<(~str, LoaderTaskFactory)>) -> struct ResourceManager { from_client: Receiver<ControlMsg>, /// Per-scheme resource loaders - loaders: Vec<(~str, LoaderTaskFactory)>, + loaders: Vec<(String, LoaderTaskFactory)>, } fn ResourceManager(from_client: Receiver<ControlMsg>, - loaders: Vec<(~str, LoaderTaskFactory)>) -> ResourceManager { + loaders: Vec<(String, LoaderTaskFactory)>) -> ResourceManager { ResourceManager { from_client : from_client, loaders : loaders, @@ -215,7 +215,7 @@ impl ResourceManager { } None => { 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] 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 (start_chan, start) = channel(); resource_task.send(Load(LoadData::new(FromStr::from_str("snicklefritz://heya").unwrap()), start_chan)); diff --git a/src/components/script/dom/attr.rs b/src/components/script/dom/attr.rs index a7137a4c8a2..a44e9e3f111 100644 --- a/src/components/script/dom/attr.rs +++ b/src/components/script/dom/attr.rs @@ -120,7 +120,7 @@ impl<'a> AttrMethods for JSRef<'a, Attr> { fn GetNamespaceURI(&self) -> Option<DOMString> { match self.namespace.to_str() { "" => None, - url => Some(url.to_owned()), + url => Some(url.to_string()), } } diff --git a/src/components/script/dom/bindings/codegen/CodegenRust.py b/src/components/script/dom/bindings/codegen/CodegenRust.py index 62cb66d5f1f..171301ac7d4 100644 --- a/src/components/script/dom/bindings/codegen/CodegenRust.py +++ b/src/components/script/dom/bindings/codegen/CodegenRust.py @@ -641,7 +641,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, default = "None" else: 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(): value = "Some(%s)" % value @@ -691,7 +691,7 @@ def getJSToNativeConversionTemplate(type, descriptorProvider, failureCode=None, " Ok(None) => { %(handleInvalidEnumValueCode)s },\n" " Ok(Some(index)) => {\n" " //XXXjdm need some range checks up in here.\n" - " unsafe { cast::transmute(index) }\n" + " unsafe { mem::transmute(index) }\n" " },\n" "}" % { "values" : enum + "Values::strings", "exceptionCode" : exceptionCode, @@ -2130,7 +2130,7 @@ class CGDefineDOMInterfaceMethod(CGAbstractMethod): trace: Some(%s) }; 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, TRACE_HOOK_NAME, @@ -2673,7 +2673,7 @@ pub static strings: &'static [&'static str] = &[ impl ToJSValConvertible for valuelist { 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())), @@ -3821,7 +3821,7 @@ class CGAbstractClassHook(CGAbstractExternMethod): def finalizeHook(descriptor, hookName, context): 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); """ % (descriptor.concreteType, descriptor.concreteType) return release @@ -4343,7 +4343,7 @@ class CGBindingRoot(CGThing): 'script_task::JSPageInfo', 'libc', 'servo_util::str::DOMString', - 'std::cast', + 'std::mem', 'std::cmp', 'std::ptr', 'std::str', diff --git a/src/components/script/dom/bindings/codegen/GlobalGen.py b/src/components/script/dom/bindings/codegen/GlobalGen.py index aa820d497b8..cdca464e029 100644 --- a/src/components/script/dom/bindings/codegen/GlobalGen.py +++ b/src/components/script/dom/bindings/codegen/GlobalGen.py @@ -17,9 +17,7 @@ from CodegenRust import GlobalGenRoots, replaceFileIfChanged # import Codegen in general, so we can set a variable on it import Codegen -def generate_file(config, name): - filename = name + '.rs' - +def generate_file(config, name, filename): root = getattr(GlobalGenRoots, name)(config) code = root.define() @@ -65,21 +63,21 @@ def main(): config = Configuration(configFile, parserResults) # Generate the prototype list. - generate_file(config, 'PrototypeList') + generate_file(config, 'PrototypeList', 'PrototypeList.rs') # Generate the common code. - generate_file(config, 'RegisterBindings') + generate_file(config, 'RegisterBindings', 'RegisterBindings.rs') # Generate the type list. - generate_file(config, 'InterfaceTypes') + generate_file(config, 'InterfaceTypes', 'InterfaceTypes.rs') # Generate the type list. - generate_file(config, 'InheritTypes') + generate_file(config, 'InheritTypes', 'InheritTypes.rs') # 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__': main() diff --git a/src/components/script/dom/bindings/conversions.rs b/src/components/script/dom/bindings/conversions.rs index 867e07ade30..96dc946a3d2 100644 --- a/src/components/script/dom/bindings/conversions.rs +++ b/src/components/script/dom/bindings/conversions.rs @@ -60,7 +60,7 @@ impl ToJSValConvertible for JSVal { unsafe fn convert_from_jsval<T: Default>( 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(); if convert_fn(cx, value, &mut ret) == 0 { Err(()) @@ -243,7 +243,7 @@ impl Default for StringificationBehavior { impl FromJSValConvertible<StringificationBehavior> for DOMString { fn from_jsval(cx: *mut JSContext, value: JSVal, nullBehavior: StringificationBehavior) -> Result<DOMString, ()> { if nullBehavior == Empty && value.is_null() { - Ok("".to_owned()) + Ok("".to_string()) } else { let jsstr = unsafe { JS_ValueToString(cx, value) }; if jsstr.is_null() { diff --git a/src/components/script/dom/bindings/js.rs b/src/components/script/dom/bindings/js.rs index 89898a35ba0..0f96f3e33e6 100644 --- a/src/components/script/dom/bindings/js.rs +++ b/src/components/script/dom/bindings/js.rs @@ -46,9 +46,9 @@ use js::jsapi::{JSObject, JS_AddObjectRoot, JS_RemoveObjectRoot}; use layout_interface::TrustedNodeAddress; use script_task::StackRoots; -use std::cast; use std::cell::{Cell, RefCell}; 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. /// 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. 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 /// is unsafe is what necessitates the layout wrappers.) 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> @@ -209,11 +209,11 @@ impl<T: Reflectable> JS<T> { impl<From, To> JS<From> { //XXXjdm It would be lovely if this could be private. pub unsafe fn transmute(self) -> JS<To> { - cast::transmute(self) + mem::transmute(self) } 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> { //XXXjdm It would be lovely if this could be private. 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. 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> { diff --git a/src/components/script/dom/bindings/proxyhandler.rs b/src/components/script/dom/bindings/proxyhandler.rs index 07b881cf287..0f573df6edc 100644 --- a/src/components/script/dom/bindings/proxyhandler.rs +++ b/src/components/script/dom/bindings/proxyhandler.rs @@ -14,7 +14,7 @@ use js::glue::InvokeGetOwnPropertyDescriptor; use js::{JSPROP_GETTER, JSPROP_ENUMERATE, JSPROP_READONLY, JSRESOLVE_QUALIFIED}; use libc; -use std::cast; +use std::mem; use std::ptr; use std::str; use std::mem::size_of; @@ -39,7 +39,7 @@ pub extern fn getPropertyDescriptor(cx: *mut JSContext, proxy: *mut JSObject, id 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 { unsafe { //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385 - let setter: *libc::c_void = cast::transmute((*desc).setter); - let setter_stub: *libc::c_void = cast::transmute(JS_StrictPropertyStub); + let setter: *libc::c_void = mem::transmute((*desc).setter); + let setter_stub: *libc::c_void = mem::transmute(JS_StrictPropertyStub); if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub { /*return JS_ReportErrorFlagsAndNumber(cx, 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(); } - let result = "[object ".to_owned() + name + "]"; + let result = format!("[object {}]", name); + let result = result.as_slice(); for (i, c) in result.chars().enumerate() { *chars.offset(i as int) = c as jschar; } diff --git a/src/components/script/dom/bindings/trace.rs b/src/components/script/dom/bindings/trace.rs index 9c7f295795e..0c2388ae44c 100644 --- a/src/components/script/dom/bindings/trace.rs +++ b/src/components/script/dom/bindings/trace.rs @@ -9,7 +9,7 @@ use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSTRACE_OBJECT}; use js::jsval::JSVal; use libc; -use std::cast; +use std::mem; use std::cell::{Cell, RefCell}; 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 { unsafe { - cast::transmute(s) + mem::transmute(s) } } diff --git a/src/components/script/dom/bindings/utils.rs b/src/components/script/dom/bindings/utils.rs index 7dc751bfbdb..ff3300ad6e3 100644 --- a/src/components/script/dom/bindings/utils.rs +++ b/src/components/script/dom/bindings/utils.rs @@ -14,7 +14,7 @@ use servo_util::str::DOMString; use collections::hashmap::HashMap; use libc; use libc::c_uint; -use std::cast; +use std::mem; use std::cmp::Eq; use std::ptr; 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 { - cast::transmute(x) + mem::transmute(x) } pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString { diff --git a/src/components/script/dom/characterdata.rs b/src/components/script/dom/characterdata.rs index 88c13f668a3..c4fe6700a3a 100644 --- a/src/components/script/dom/characterdata.rs +++ b/src/components/script/dom/characterdata.rs @@ -66,11 +66,11 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { } 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 { - self.data = self.data + arg; + self.data.push_str(arg.as_slice()); Ok(()) } @@ -79,7 +79,7 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { } 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 { @@ -92,9 +92,9 @@ impl<'a> CharacterDataMethods for JSRef<'a, CharacterData> { } else { count }; - let mut data = self.data.slice(0, offset as uint).to_strbuf(); - data.push_str(arg); - data.push_str(self.data.slice((offset + count) as uint, length as uint)); + let mut data = self.data.as_slice().slice(0, offset as uint).to_string(); + data.push_str(arg.as_slice()); + data.push_str(self.data.as_slice().slice((offset + count) as uint, length as uint)); self.data = data.into_owned(); // FIXME: Once we have `Range`, we should implement step7 to step11 Ok(()) diff --git a/src/components/script/dom/document.rs b/src/components/script/dom/document.rs index 8672da19b55..a00a12c26de 100644 --- a/src/components/script/dom/document.rs +++ b/src/components/script/dom/document.rs @@ -219,16 +219,16 @@ impl Document { Some(string) => string.clone(), None => match is_html_document { // 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 - NonHTMLDocument => "application/xml".to_owned() + NonHTMLDocument => "application/xml".to_string() } }, url: Untraceable::new(url), // http://dom.spec.whatwg.org/#concept-document-quirks quirks_mode: Untraceable::new(NoQuirks), // 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, } } @@ -355,14 +355,14 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { // http://dom.spec.whatwg.org/#dom-document-compatmode fn CompatMode(&self) -> DOMString { match *self.quirks_mode { - NoQuirks => "CSS1Compat".to_owned(), - LimitedQuirks | FullQuirks => "BackCompat".to_owned() + NoQuirks => "CSS1Compat".to_string(), + LimitedQuirks | FullQuirks => "BackCompat".to_string() } } // http://dom.spec.whatwg.org/#dom-document-characterset 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 @@ -398,7 +398,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { let window = self.window.root(); let namespace = match maybe_ns { - Some(namespace) => Namespace::from_str(namespace), + Some(namespace) => Namespace::from_str(namespace.as_slice()), None => Null }; 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 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"); 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)) } @@ -434,7 +434,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { namespace: Option<DOMString>, qualified_name: DOMString) -> Fallible<Temporary<Element>> { 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 => { debug!("Not a valid element name"); return Err(InvalidCharacter); @@ -454,12 +454,12 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { return Err(NamespaceError); }, // 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'"); return Err(NamespaceError); }, // 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, _, _) => { 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, data: DOMString) -> Fallible<Temporary<ProcessingInstruction>> { // Step 1. - if xml_name_type(target) == InvalidXMLName { + if xml_name_type(target.as_slice()) == InvalidXMLName { return Err(InvalidCharacter); } // Step 2. - if data.contains("?>") { + if data.as_slice().contains("?>") { return Err(InvalidCharacter); } @@ -542,7 +542,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { fn CreateEvent(&self, interface: DOMString) -> Fallible<Temporary<Event>> { 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) "uievents" | "uievent" => Ok(EventCast::from_temporary(UIEvent::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 fn Title(&self) -> DOMString { - let mut title = StrBuf::new(); + let mut title = String::new(); self.GetDocumentElement().root().map(|root| { let root: &JSRef<Node> = NodeCast::from_ref(&*root); root.traverse_preorder() @@ -570,7 +570,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { }); let v: Vec<&str> = title.as_slice().words().collect(); 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 @@ -595,7 +595,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { assert!(title_node.AppendChild(NodeCast::from_ref(&*new_text)).is_ok()); }, 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_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(); 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; impl CollectionFilter for ImagesFilter { 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; @@ -717,7 +717,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { struct EmbedsFilter; impl CollectionFilter for EmbedsFilter { 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; @@ -736,7 +736,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { struct LinksFilter; impl CollectionFilter for LinksFilter { 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() } } @@ -751,7 +751,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { struct FormsFilter; impl CollectionFilter for FormsFilter { 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; @@ -765,7 +765,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { struct ScriptsFilter; impl CollectionFilter for ScriptsFilter { 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; @@ -779,7 +779,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { struct AnchorsFilter; impl CollectionFilter for AnchorsFilter { 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; @@ -793,7 +793,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { struct AppletsFilter; impl CollectionFilter for AppletsFilter { 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; diff --git a/src/components/script/dom/documenttype.rs b/src/components/script/dom/documenttype.rs index c10d2730d1f..110e650f288 100644 --- a/src/components/script/dom/documenttype.rs +++ b/src/components/script/dom/documenttype.rs @@ -34,8 +34,8 @@ impl DocumentType { DocumentType { node: Node::new_inherited(DoctypeNodeTypeId, document), name: name, - public_id: public_id.unwrap_or("".to_owned()), - system_id: system_id.unwrap_or("".to_owned()) + public_id: public_id.unwrap_or("".to_string()), + system_id: system_id.unwrap_or("".to_string()) } } diff --git a/src/components/script/dom/domexception.rs b/src/components/script/dom/domexception.rs index 291dd4276a1..bd59020dbbd 100644 --- a/src/components/script/dom/domexception.rs +++ b/src/components/script/dom/domexception.rs @@ -112,27 +112,27 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> { // http://dom.spec.whatwg.org/#error-names-0 fn Message(&self) -> DOMString { match self.code { - IndexSizeError => "The index is not in the allowed range.".to_owned(), - HierarchyRequestError => "The operation would yield an incorrect node tree.".to_owned(), - WrongDocumentError => "The object is in the wrong document.".to_owned(), - InvalidCharacterError => "The string contains invalid characters.".to_owned(), - NoModificationAllowedError => "The object can not be modified.".to_owned(), - NotFoundError => "The object can not be found here.".to_owned(), - NotSupportedError => "The operation is not supported.".to_owned(), - InvalidStateError => "The object is in an invalid state.".to_owned(), - SyntaxError => "The string did not match the expected pattern.".to_owned(), - InvalidModificationError => "The object can not be modified in this way.".to_owned(), - NamespaceError => "The operation is not allowed by Namespaces in XML.".to_owned(), - InvalidAccessError => "The object does not support the operation or argument.".to_owned(), - SecurityError => "The operation is insecure.".to_owned(), - NetworkError => "A network error occurred.".to_owned(), - AbortError => "The operation was aborted.".to_owned(), - URLMismatchError => "The given URL does not match another URL.".to_owned(), - QuotaExceededError => "The quota has been exceeded.".to_owned(), - TimeoutError => "The operation timed out.".to_owned(), - InvalidNodeTypeError => "The supplied node is incorrect or has an incorrect ancestor for this operation.".to_owned(), - DataCloneError => "The object can not be cloned.".to_owned(), - EncodingError => "The encoding operation (either encoded or decoding) failed.".to_owned() + IndexSizeError => "The index is not in the allowed range.".to_string(), + HierarchyRequestError => "The operation would yield an incorrect node tree.".to_string(), + WrongDocumentError => "The object is in the wrong document.".to_string(), + InvalidCharacterError => "The string contains invalid characters.".to_string(), + NoModificationAllowedError => "The object can not be modified.".to_string(), + NotFoundError => "The object can not be found here.".to_string(), + NotSupportedError => "The operation is not supported.".to_string(), + InvalidStateError => "The object is in an invalid state.".to_string(), + SyntaxError => "The string did not match the expected pattern.".to_string(), + InvalidModificationError => "The object can not be modified in this way.".to_string(), + NamespaceError => "The operation is not allowed by Namespaces in XML.".to_string(), + InvalidAccessError => "The object does not support the operation or argument.".to_string(), + SecurityError => "The operation is insecure.".to_string(), + NetworkError => "A network error occurred.".to_string(), + AbortError => "The operation was aborted.".to_string(), + URLMismatchError => "The given URL does not match another URL.".to_string(), + QuotaExceededError => "The quota has been exceeded.".to_string(), + TimeoutError => "The operation timed out.".to_string(), + InvalidNodeTypeError => "The supplied node is incorrect or has an incorrect ancestor for this operation.".to_string(), + DataCloneError => "The object can not be cloned.".to_string(), + EncodingError => "The encoding operation (either encoded or decoding) failed.".to_string() } } } diff --git a/src/components/script/dom/domimplementation.rs b/src/components/script/dom/domimplementation.rs index 4d568ba52fe..370a233f67d 100644 --- a/src/components/script/dom/domimplementation.rs +++ b/src/components/script/dom/domimplementation.rs @@ -60,7 +60,7 @@ pub trait DOMImplementationMethods { impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { // http://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype 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. InvalidXMLName => Err(InvalidCharacter), // Step 2. @@ -129,19 +129,19 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { { // 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()); } { // 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(); assert!(doc_node.AppendChild(doc_html).is_ok()); { // 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(); assert!(doc_html.AppendChild(doc_head).is_ok()); @@ -150,7 +150,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { None => (), Some(title_str) => { // 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(); assert!(doc_head.AppendChild(doc_title).is_ok()); @@ -163,7 +163,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> { } // 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(); assert!(doc_html.AppendChild(NodeCast::from_ref(doc_body)).is_ok()); } diff --git a/src/components/script/dom/domparser.rs b/src/components/script/dom/domparser.rs index a49e97cd61d..540de38727a 100644 --- a/src/components/script/dom/domparser.rs +++ b/src/components/script/dom/domparser.rs @@ -48,10 +48,10 @@ impl<'a> DOMParserMethods for JSRef<'a, DOMParser> { let owner = self.owner.root(); match ty { 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 => { - 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) diff --git a/src/components/script/dom/element.rs b/src/components/script/dom/element.rs index db8658ab9b5..66027956a65 100644 --- a/src/components/script/dom/element.rs +++ b/src/components/script/dom/element.rs @@ -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 std::ascii::StrAsciiExt; -use std::cast; use std::cell::{Cell, RefCell}; +use std::mem; #[deriving(Encodable)] pub struct Element { @@ -168,13 +168,13 @@ impl RawLayoutElementHelpers for Element { unsafe fn get_attr_val_for_layout(&self, namespace: &Namespace, name: &str) -> Option<&'static str> { // 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>| { let attr = attr.unsafe_get(); - name == (*attr).local_name && (*attr).namespace == *namespace + name == (*attr).local_name.as_slice() && (*attr).namespace == *namespace }).map(|attr| { 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 { name.to_ascii_lower() == attr.local_name } else { - name == attr.local_name + name == attr.local_name.as_slice() }; same_name && attr.namespace == namespace @@ -274,7 +274,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { let position: |&JSRef<Attr>| -> bool = 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 { |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 { 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) } @@ -363,17 +363,17 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> { let x = x.root(); x.deref().Value() } - None => "".to_owned() + None => "".to_string() } } fn set_string_attribute(&self, name: &str, value: DOMString) { - assert!(name == name.to_ascii_lower()); - assert!(self.set_attribute(Null, name.to_owned(), value).is_ok()); + assert!(name == name.to_ascii_lower().as_slice()); + assert!(self.set_attribute(Null, name.to_string(), value).is_ok()); } fn set_uint_attribute(&self, name: &str, value: u32) { - assert!(name == name.to_ascii_lower()); - assert!(self.set_attribute(Null, name.to_owned(), value.to_str()).is_ok()); + assert!(name == name.to_ascii_lower().as_slice()); + 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> { // http://dom.spec.whatwg.org/#dom-element-namespaceuri fn NamespaceURI(&self) -> DOMString { - self.namespace.to_str().to_owned() + self.namespace.to_str().to_string() } fn LocalName(&self) -> DOMString { @@ -441,10 +441,11 @@ impl<'a> ElementMethods for JSRef<'a, Element> { fn TagName(&self) -> DOMString { match self.prefix { None => { - self.local_name.to_ascii_upper() + self.local_name.as_slice().to_ascii_upper() } 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 fn GetAttribute(&self, name: DOMString) -> Option<DOMString> { let name = if self.html_element_in_html_document() { - name.to_ascii_lower() + name.as_slice().to_ascii_lower() } else { name }; - self.get_attribute(Null, name).root() + self.get_attribute(Null, name.as_slice()).root() .map(|s| s.deref().Value()) } @@ -502,7 +503,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> { namespace: Option<DOMString>, local_name: DOMString) -> Option<DOMString> { 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()) } @@ -516,14 +517,14 @@ impl<'a> ElementMethods for JSRef<'a, Element> { } // Step 1. - match xml_name_type(name) { + match xml_name_type(name.as_slice()) { InvalidXMLName => return Err(InvalidCharacter), _ => {} } // Step 2. let name = if self.html_element_in_html_document() { - name.to_ascii_lower() + name.as_slice().to_ascii_lower() } else { name }; @@ -548,7 +549,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> { // Step 1. 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 { // Step 2. InvalidXMLName => return Err(InvalidCharacter), @@ -580,12 +581,12 @@ impl<'a> ElementMethods for JSRef<'a, Element> { } // Step 7a. - if "xmlns" == name && namespace != namespace::XMLNS { + if "xmlns" == name.as_slice() && namespace != namespace::XMLNS { return Err(NamespaceError); } // 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); } @@ -601,7 +602,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> { fn RemoveAttribute(&self, name: DOMString) -> ErrorResult { let name = if self.html_element_in_html_document() { - name.to_ascii_lower() + name.as_slice().to_ascii_lower() } else { name }; @@ -637,7 +638,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> { fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>, localname: DOMString) -> Temporary<HTMLCollection> { let namespace = match maybe_ns { - Some(namespace) => Namespace::from_str(namespace), + Some(namespace) => Namespace::from_str(namespace.as_slice()), None => Null }; 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 XMLNS-invalid names - let (prefix, local_name) = if name.contains(":") { - let mut parts = name.splitn(':', 1); - (Some(parts.next().unwrap().to_owned()), parts.next().unwrap().to_owned()) + let (prefix, local_name) = if name.as_slice().contains(":") { + let mut parts = name.as_slice().splitn(':', 1); + (Some(parts.next().unwrap().to_string()), parts.next().unwrap().to_string()) } else { (None, name) }; @@ -729,7 +730,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> { "style" => { let doc = document_from_node(self).root(); 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" => { let node: &JSRef<Node> = NodeCast::from_ref(self); diff --git a/src/components/script/dom/event.rs b/src/components/script/dom/event.rs index 2d238396a0d..b30a4d6dc4b 100644 --- a/src/components/script/dom/event.rs +++ b/src/components/script/dom/event.rs @@ -70,7 +70,7 @@ impl Event { current_target: Cell::new(None), target: Cell::new(None), phase: PhaseNone, - type_: "".to_owned(), + type_: "".to_string(), canceled: false, cancelable: true, bubbles: false, diff --git a/src/components/script/dom/eventdispatcher.rs b/src/components/script/dom/eventdispatcher.rs index 2dc2b3a8c1d..6c199886b75 100644 --- a/src/components/script/dom/eventdispatcher.rs +++ b/src/components/script/dom/eventdispatcher.rs @@ -44,7 +44,7 @@ pub fn dispatch_event<'a, 'b>(target: &JSRef<'a, EventTarget>, /* capturing */ 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) => { event.current_target.assign(Some(cur_target.deref().clone())); 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())); } - 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 listener in listeners.iter() { // 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; 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) => { event.deref_mut().current_target.assign(Some(cur_target.deref().clone())); for listener in listeners.iter() { diff --git a/src/components/script/dom/eventtarget.rs b/src/components/script/dom/eventtarget.rs index 1ebfc77875a..165454f6243 100644 --- a/src/components/script/dom/eventtarget.rs +++ b/src/components/script/dom/eventtarget.rs @@ -192,11 +192,11 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> { { let event_listener = listener.map(|listener| 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> { - 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())) } } diff --git a/src/components/script/dom/formdata.rs b/src/components/script/dom/formdata.rs index a843b62db30..142b08fc262 100644 --- a/src/components/script/dom/formdata.rs +++ b/src/components/script/dom/formdata.rs @@ -54,7 +54,7 @@ impl<'a> FormDataMethods for JSRef<'a, FormData> { fn Append(&mut self, name: DOMString, value: &JSRef<Blob>, filename: Option<DOMString>) { let blob = BlobData { blob: value.unrooted(), - name: filename.unwrap_or("default".to_owned()) + name: filename.unwrap_or("default".to_string()) }; self.data.insert(name.clone(), blob); } diff --git a/src/components/script/dom/htmlanchorelement.rs b/src/components/script/dom/htmlanchorelement.rs index 855588ed196..3ed06945f80 100644 --- a/src/components/script/dom/htmlanchorelement.rs +++ b/src/components/script/dom/htmlanchorelement.rs @@ -50,7 +50,7 @@ trait PrivateHTMLAnchorElementHelpers { impl<'a> PrivateHTMLAnchorElementHelpers for JSRef<'a, HTMLAnchorElement> { 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 attr = element.get_attribute(Null, "href").root(); match attr { diff --git a/src/components/script/dom/htmlbodyelement.rs b/src/components/script/dom/htmlbodyelement.rs index fc3196062b7..bf02ba963cd 100644 --- a/src/components/script/dom/htmlbodyelement.rs +++ b/src/components/script/dom/htmlbodyelement.rs @@ -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] = &["onfocus", "onload", "onscroll", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", @@ -87,7 +87,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { EventTargetCast::from_mut_ref(self) }; evtarget.set_event_handler_uncompiled(cx, url, reflector, - name.slice_from(2).to_owned(), + name.as_slice().slice_from(2), value); } } diff --git a/src/components/script/dom/htmlcollection.rs b/src/components/script/dom/htmlcollection.rs index 3de86456c1c..aeb506938f8 100644 --- a/src/components/script/dom/htmlcollection.rs +++ b/src/components/script/dom/htmlcollection.rs @@ -99,11 +99,11 @@ impl HTMLCollection { } impl CollectionFilter for ClassNameFilter { 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 { - 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) } diff --git a/src/components/script/dom/htmldatalistelement.rs b/src/components/script/dom/htmldatalistelement.rs index fd310d619f9..8b95feb3a84 100644 --- a/src/components/script/dom/htmldatalistelement.rs +++ b/src/components/script/dom/htmldatalistelement.rs @@ -46,7 +46,7 @@ impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> { struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { 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); diff --git a/src/components/script/dom/htmlfieldsetelement.rs b/src/components/script/dom/htmlfieldsetelement.rs index aa622b55216..45394af413e 100644 --- a/src/components/script/dom/htmlfieldsetelement.rs +++ b/src/components/script/dom/htmlfieldsetelement.rs @@ -52,7 +52,7 @@ impl<'a> HTMLFieldSetElementMethods for JSRef<'a, HTMLFieldSetElement> { static tag_names: StaticStringVec = &["button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"]; 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); diff --git a/src/components/script/dom/htmliframeelement.rs b/src/components/script/dom/htmliframeelement.rs index b48d91e8793..9c4467208be 100644 --- a/src/components/script/dom/htmliframeelement.rs +++ b/src/components/script/dom/htmliframeelement.rs @@ -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; - for word in value.split(' ') { + for word in value.as_slice().split(' ') { modes |= match word.to_ascii_lower().as_slice() { "allow-same-origin" => AllowSameOrigin, "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; } } diff --git a/src/components/script/dom/htmlimageelement.rs b/src/components/script/dom/htmlimageelement.rs index 5b6d9f9e54b..33946b588a4 100644 --- a/src/components/script/dom/htmlimageelement.rs +++ b/src/components/script/dom/htmlimageelement.rs @@ -49,7 +49,7 @@ impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> { *self.image = None; } Some(src) => { - let img_url = parse_url(src, url); + let img_url = parse_url(src.as_slice(), url); *self.image = Some(img_url.clone()); // 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 { 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) { @@ -199,7 +199,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> { fn Hspace(&self) -> u32 { 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) { @@ -209,7 +209,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> { fn Vspace(&self) -> u32 { 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) { @@ -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 url = Some(window.deref().get_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); } } diff --git a/src/components/script/dom/htmlmainelement.rs b/src/components/script/dom/htmlmainelement.rs new file mode 100644 index 00000000000..61c4506de7f --- /dev/null +++ b/src/components/script/dom/htmlmainelement.rs @@ -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 { +} diff --git a/src/components/script/dom/htmlobjectelement.rs b/src/components/script/dom/htmlobjectelement.rs index 3a339dd933d..a2bf1b317d3 100644 --- a/src/components/script/dom/htmlobjectelement.rs +++ b/src/components/script/dom/htmlobjectelement.rs @@ -62,8 +62,8 @@ impl<'a> ProcessDataURL for JSRef<'a, HTMLObjectElement> { match (elem.get_attribute(Null, "type").map(|x| x.root().Value()), elem.get_attribute(Null, "data").map(|x| x.root().Value())) { (None, Some(uri)) => { - if is_image_data(uri) { - let data_url = parse_url(uri, url); + if is_image_data(uri.as_slice()) { + let data_url = parse_url(uri.as_slice(), url); // Issue #84 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 url = Some(window.deref().get_url()); self.process_data_url(window.deref().image_cache_task.clone(), url); diff --git a/src/components/script/dom/htmlserializer.rs b/src/components/script/dom/htmlserializer.rs index ea33f79fee0..a1c6d709a47 100644 --- a/src/components/script/dom/htmlserializer.rs +++ b/src/components/script/dom/htmlserializer.rs @@ -19,9 +19,9 @@ use dom::node::{TextNodeTypeId, NodeHelpers}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; -pub fn serialize(iterator: &mut NodeIterator) -> ~str { - let mut html = StrBuf::new(); - let mut open_elements: Vec<~str> = vec!(); +pub fn serialize(iterator: &mut NodeIterator) -> String { + let mut html = String::new(); + let mut open_elements: Vec<String> = vec!(); for node in *iterator { while open_elements.len() > iterator.depth { @@ -65,13 +65,13 @@ pub fn serialize(iterator: &mut NodeIterator) -> ~str { 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(comment.deref().characterdata.data); + html.push_str(comment.deref().characterdata.data.as_slice()); 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); match text_node.parent_node().map(|node| node.root()) { Some(ref parent) if parent.is_element() => { @@ -80,32 +80,32 @@ fn serialize_text(text: &JSRef<Text>, html: &mut StrBuf) { "style" | "script" | "xmp" | "iframe" | "noembed" | "noframes" | "plaintext" | "noscript" if elem.deref().namespace == namespace::HTML - => html.push_str(text.deref().characterdata.data), - _ => escape(text.deref().characterdata.data, false, html) + => html.push_str(text.deref().characterdata.data.as_slice()), + _ => 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>, - html: &mut StrBuf) { + html: &mut String) { html.push_str("<?"); - html.push_str(processing_instruction.deref().target); + html.push_str(processing_instruction.deref().target.as_slice()); html.push_char(' '); - html.push_str(processing_instruction.deref().characterdata.data); + html.push_str(processing_instruction.deref().characterdata.data.as_slice()); 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.deref().name); + html.push_str(doctype.deref().name.as_slice()); 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_str(elem.deref().local_name); + html.push_str(elem.deref().local_name.as_slice()); for attr in elem.deref().attrs.borrow().iter() { let attr = attr.root(); 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()) { Some(ref child) if child.is_text() => { 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'); } }, @@ -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(' '); if attr.deref().namespace == namespace::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 && attr.deref().local_name.as_slice() == "xmlns" { html.push_str("xmlns"); } else if attr.deref().namespace == namespace::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 { html.push_str("xlink:"); - html.push_str(attr.deref().local_name); + html.push_str(attr.deref().local_name.as_slice()); } else { - html.push_str(attr.deref().name); + html.push_str(attr.deref().name.as_slice()); }; html.push_str("=\""); - escape(attr.deref().value, true, html); + escape(attr.deref().value.as_slice(), true, html); 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() { match c { '&' => html.push_str("&"), diff --git a/src/components/script/dom/navigator.rs b/src/components/script/dom/navigator.rs index 9c53c8a220b..3603709971f 100644 --- a/src/components/script/dom/navigator.rs +++ b/src/components/script/dom/navigator.rs @@ -37,7 +37,7 @@ pub trait NavigatorMethods { impl<'a> NavigatorMethods for JSRef<'a, Navigator> { fn Product(&self) -> DOMString { - "Gecko".to_owned() + "Gecko".to_string() } fn TaintEnabled(&self) -> bool { @@ -45,15 +45,15 @@ impl<'a> NavigatorMethods for JSRef<'a, Navigator> { } fn AppName(&self) -> DOMString { - "Netscape".to_owned() // Like Gecko/Webkit + "Netscape".to_string() // Like Gecko/Webkit } fn AppCodeName(&self) -> DOMString { - "Mozilla".to_owned() + "Mozilla".to_string() } fn Platform(&self) -> DOMString { - "".to_owned() + "".to_string() } } diff --git a/src/components/script/dom/node.rs b/src/components/script/dom/node.rs index d722d1abe3e..c7cde126e42 100644 --- a/src/components/script/dom/node.rs +++ b/src/components/script/dom/node.rs @@ -39,8 +39,6 @@ use js::jsapi::{JSContext, JSObject, JSRuntime}; use js::jsfriendapi; use libc; use libc::uintptr_t; -use std::cast::transmute; -use std::cast; use std::cell::{Cell, RefCell, Ref, RefMut}; use std::iter::{Map, Filter}; use std::mem; @@ -171,7 +169,7 @@ impl LayoutDataRef { pub unsafe fn from_data<T>(data: Box<T>) -> 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. #[inline] 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. @@ -384,7 +382,7 @@ pub trait NodeHelpers { fn dump(&self); 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 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. fn dump_indent(&self, indent: uint) { - let mut s = StrBuf::new(); + let mut s = String::new(); for _ in range(0, indent) { s.push_str(" "); } - s.push_str(self.debug_str()); + s.push_str(self.debug_str().as_slice()); debug!("{:s}", s); // 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. - fn debug_str(&self) -> ~str { + fn debug_str(&self) -> String { 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) -> Temporary<Node> { unsafe { - let candidate: uintptr_t = cast::transmute(candidate); + let candidate: uintptr_t = mem::transmute(candidate); let object: *mut JSObject = jsfriendapi::bindgen::JS_GetAddressableObject(runtime, candidate); if object.is_null() { @@ -1353,19 +1351,19 @@ impl<'a> NodeMethods for JSRef<'a, Node> { let elem: &JSRef<Element> = ElementCast::to_ref(self).unwrap(); elem.TagName() } - TextNodeTypeId => "#text".to_owned(), + TextNodeTypeId => "#text".to_string(), ProcessingInstructionNodeTypeId => { let processing_instruction: &JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(self).unwrap(); processing_instruction.Target() } - CommentNodeTypeId => "#comment".to_owned(), + CommentNodeTypeId => "#comment".to_string(), DoctypeNodeTypeId => { let doctype: &JSRef<DocumentType> = DocumentTypeCast::to_ref(self).unwrap(); doctype.deref().name.clone() }, - DocumentFragmentNodeTypeId => "#document-fragment".to_owned(), - DocumentNodeTypeId => "#document".to_owned() + DocumentFragmentNodeTypeId => "#document-fragment".to_string(), + DocumentNodeTypeId => "#document".to_string() } } @@ -1476,7 +1474,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> { match self.type_id { DocumentFragmentNodeTypeId | ElementNodeTypeId(..) => { - let mut content = StrBuf::new(); + let mut content = String::new(); for node in self.traverse_preorder() { if node.is_text() { let text: &JSRef<Text> = TextCast::to_ref(&node).unwrap(); diff --git a/src/components/script/dom/testbinding.rs b/src/components/script/dom/testbinding.rs index 4f6020e8c20..852b7443418 100644 --- a/src/components/script/dom/testbinding.rs +++ b/src/components/script/dom/testbinding.rs @@ -48,7 +48,7 @@ pub trait TestBindingMethods { fn SetFloatAttribute(&self, _: f32) {} fn DoubleAttribute(&self) -> f64 { 0. } fn SetDoubleAttribute(&self, _: f64) {} - fn StringAttribute(&self) -> DOMString { "".to_owned() } + fn StringAttribute(&self) -> DOMString { "".to_string() } fn SetStringAttribute(&self, _: DOMString) {} fn ByteStringAttribute(&self) -> ByteString { ByteString::new(vec!()) } fn SetByteStringAttribute(&self, _: ByteString) {} @@ -83,7 +83,7 @@ pub trait TestBindingMethods { fn SetDoubleAttributeNullable(&self, _: Option<f64>) {} fn GetByteStringAttributeNullable(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) } 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 GetEnumAttributeNullable(&self) -> Option<TestEnum> { Some(_empty) } fn GetInterfaceAttributeNullable(&self) -> Option<Temporary<Blob>>; @@ -101,7 +101,7 @@ pub trait TestBindingMethods { fn ReceiveUnsignedLongLong(&self) -> u64 { 0 } fn ReceiveFloat(&self) -> f32 { 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 ReceiveEnum(&self) -> TestEnum { _empty } fn ReceiveInterface(&self) -> Temporary<Blob>; @@ -118,7 +118,7 @@ pub trait TestBindingMethods { fn ReceiveNullableUnsignedLongLong(&self) -> Option<u64> { Some(0) } fn ReceiveNullableFloat(&self) -> Option<f32> { 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 ReceiveNullableEnum(&self) -> Option<TestEnum> { Some(_empty) } fn ReceiveNullableInterface(&self) -> Option<Temporary<Blob>>; diff --git a/src/components/script/dom/window.rs b/src/components/script/dom/window.rs index edb969cd90f..170c2bfa657 100644 --- a/src/components/script/dom/window.rs +++ b/src/components/script/dom/window.rs @@ -302,9 +302,9 @@ impl<'a> WindowHelpers for JSRef<'a, Window> { fn load_url(&self, href: DOMString) { let base_url = Some(self.page().get_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; - if href.starts_with("#") { + if href.as_slice().starts_with("#") { script_chan.send(TriggerFragmentMsg(self.page.id, url)); } else { script_chan.send(TriggerLoadMsg(self.page.id, url)); diff --git a/src/components/script/dom/xmlhttprequest.rs b/src/components/script/dom/xmlhttprequest.rs index 3d5dd42cdf0..b5240e0536f 100644 --- a/src/components/script/dom/xmlhttprequest.rs +++ b/src/components/script/dom/xmlhttprequest.rs @@ -129,13 +129,13 @@ pub struct XMLHttpRequest { impl XMLHttpRequest { pub fn new_inherited(owner: &JSRef<Window>) -> XMLHttpRequest { - let mut xhr = XMLHttpRequest { + let xhr = XMLHttpRequest { eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestTypeId), ready_state: Unsent, timeout: 0u32, with_credentials: false, upload: Cell::new(None), - response_url: "".to_owned(), + response_url: "".to_string(), status: 0, status_text: ByteString::new(vec!()), response: ByteString::new(vec!()), @@ -146,7 +146,7 @@ impl XMLHttpRequest { request_method: Untraceable::new(Get), request_url: Untraceable::new(parse_url("", None)), request_headers: Untraceable::new(RequestHeaderCollection::new()), - request_body: "".to_owned(), + request_body: "".to_string(), sync: 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 { 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 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(); // 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, Err(_) => return Err(Syntax) // Step 7 }; @@ -337,7 +337,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> { "upgrade" | "user-agent" | "via" => { return Ok(()); // Step 5 }, - _ => StrBuf::from_str(s) + _ => String::from_str(s) } }, None => return Err(Syntax) @@ -423,9 +423,9 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> { // Step 9 self.send_flag = true; - self.dispatch_response_progress_event("loadstart".to_owned()); + self.dispatch_response_progress_event("loadstart".to_string()); 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 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.method = (*self.request_method).clone(); if self.sync { @@ -488,7 +488,7 @@ impl<'a> XMLHttpRequestMethods<'a> for JSRef<'a, XMLHttpRequest> { if self.ready_state == XHRDone || self.ready_state == Loading { self.response.to_jsval(cx) } 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) // 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 - Loading | XHRDone => Ok(UTF_8.decode(self.response.as_slice(), DecodeReplace).unwrap().to_owned()), - _ => Ok("".to_owned()) + Loading | XHRDone => Ok(UTF_8.decode(self.response.as_slice(), DecodeReplace).unwrap().to_string()), + _ => Ok("".to_string()) } }, _ => Err(InvalidState) @@ -556,7 +556,7 @@ trait PrivateXMLHttpRequestHelpers { fn release(&mut self); fn change_ready_state(&mut self, XMLHttpRequestState); 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_upload_progress_event(&self, type_: DOMString, partial_load: Option<u64>); fn dispatch_response_progress_event(&self, type_: DOMString); @@ -584,7 +584,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { self.ready_state = rs; let win = &*self.global.root(); 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); target.dispatch_event_with_target(None, &mut *event).ok(); } @@ -598,9 +598,9 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // Substep 1 self.upload_complete = true; // Substeps 2-4 - self.dispatch_upload_progress_event("progress".to_owned(), None); - self.dispatch_upload_progress_event("load".to_owned(), None); - self.dispatch_upload_progress_event("loadend".to_owned(), None); + self.dispatch_upload_progress_event("progress".to_string(), None); + self.dispatch_upload_progress_event("load".to_string(), None); + self.dispatch_upload_progress_event("loadend".to_string(), None); // Part of step 13, send() (processing response) // XXXManishearth handle errors, if any (substep 1) @@ -627,7 +627,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { // Substep 3 self.response = partial_response; // Substep 4 - self.dispatch_response_progress_event("progress".to_owned()); + self.dispatch_response_progress_event("progress".to_string()); }, DoneMsg => { // 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); // Subsubsteps 5-7 - let len = self.response.len() as u64; - self.dispatch_response_progress_event("progress".to_owned()); - self.dispatch_response_progress_event("load".to_owned()); - self.dispatch_response_progress_event("loadend".to_owned()); + self.dispatch_response_progress_event("progress".to_string()); + self.dispatch_response_progress_event("load".to_string()); + self.dispatch_response_progress_event("loadend".to_string()); } }, ErroredMsg => { @@ -654,13 +653,13 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { if !self.sync { if !self.upload_complete { self.upload_complete = true; - self.dispatch_upload_progress_event("progress".to_owned(), None); - self.dispatch_upload_progress_event("load".to_owned(), None); - self.dispatch_upload_progress_event("loadend".to_owned(), None); + self.dispatch_upload_progress_event("progress".to_string(), None); + self.dispatch_upload_progress_event("load".to_string(), None); + self.dispatch_upload_progress_event("loadend".to_string(), None); } - self.dispatch_response_progress_event("progress".to_owned()); - self.dispatch_response_progress_event("load".to_owned()); - self.dispatch_response_progress_event("loadend".to_owned()); + self.dispatch_response_progress_event("progress".to_string()); + self.dispatch_response_progress_event("load".to_string()); + 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 // Use for hardcoded headers let collection = self.request_headers.deref_mut(); 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( - StrBuf::from_str(name), + String::from_str(name.as_slice()), &mut HeaderValueByteIterator::new(&mut reader)); collection.insert(maybe_header.unwrap()); } @@ -705,7 +704,6 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> { } fn dispatch_response_progress_event(&self, type_: DOMString) { - let win = &*self.global.root(); let len = self.response.len() as u64; let total = self.response_headers.deref().content_length.map(|x| {x as u64}); self.dispatch_progress_event(false, type_, len, total); diff --git a/src/components/script/html/cssparse.rs b/src/components/script/html/cssparse.rs index b8addc5d31b..cb54e9dd198 100644 --- a/src/components/script/html/cssparse.rs +++ b/src/components/script/html/cssparse.rs @@ -15,11 +15,11 @@ use url::Url; /// Where a style sheet comes from. pub enum StylesheetProvenance { UrlProvenance(Url, ResourceTask), - InlineProvenance(Url, ~str), + InlineProvenance(Url, String), } // 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)) } @@ -43,7 +43,7 @@ fn parse_css(provenance: StylesheetProvenance) -> Stylesheet { } InlineProvenance(base_url, 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) } } } diff --git a/src/components/script/html/hubbub_html_parser.rs b/src/components/script/html/hubbub_html_parser.rs index 7978c34fec6..fac27f299b1 100644 --- a/src/components/script/html/hubbub_html_parser.rs +++ b/src/components/script/html/hubbub_html_parser.rs @@ -25,10 +25,9 @@ use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS}; use servo_util::task::spawn_named; use servo_util::url::parse_url; use std::ascii::StrAsciiExt; -use std::cast; +use std::mem; use std::cell::RefCell; use std::comm::{channel, Sender, Receiver}; -use std::str; use style::Stylesheet; use url::Url; @@ -38,7 +37,7 @@ macro_rules! handle_element( $string: expr, $ctor: ident $(, $arg:expr )*) => ( - if $string == $localName { + if $string == $localName.as_slice() { return ElementCast::from_temporary($ctor::new($localName, $document $(, $arg)*)); } ) @@ -46,7 +45,7 @@ macro_rules! handle_element( pub struct JSFile { - pub data: ~str, + pub data: String, pub url: Url } @@ -59,7 +58,7 @@ enum CSSMessage { enum JSMessage { JSTaskNewFile(Url), - JSTaskNewInlineScript(~str, Url), + JSTaskNewInlineScript(String, Url), JSTaskExit } @@ -79,12 +78,12 @@ trait NodeWrapping<T> { impl<'a, T: NodeBase+Reflectable> NodeWrapping<T> for JSRef<'a, T> { 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> { - 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 // FIXME: Shouldn't wait until after we've recieved CSSTaskExit to start sending these 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)) => { 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, }); } @@ -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 @@ -340,7 +339,7 @@ pub fn parse_html(page: &Page, let doc_cell = RefCell::new(document); let mut tree_handler = hubbub::TreeHandler { - create_comment: |data: ~str| { + create_comment: |data: String| { debug!("create comment"); // NOTE: tmp vars are workaround for lifetime issues. Both required. 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. let tmp_borrow = doc_cell.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"); for attr in tag.attributes.iter() { @@ -381,10 +380,10 @@ pub fn parse_html(page: &Page, XmlNsNs => (namespace::XMLNS, Some("xmlns")), ns => fail!("Not expecting namespace {:?}", ns), }; - element.deref().set_attribute_from_parser(attr.name.clone(), - attr.value.clone(), - namespace, - prefix.map(|p| p.to_owned())); + element.set_attribute_from_parser(attr.name.clone(), + attr.value.clone(), + namespace, + prefix.map(|p| p.to_string())); } //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 ElementNodeTypeId(HTMLLinkElementTypeId) => { 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| { - s.eq_ignore_ascii_case("stylesheet") + s.as_slice().eq_ignore_ascii_case("stylesheet") }) => { debug!("found CSS stylesheet: {:s}", *href); 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() } }, - create_text: |data: ~str| { + create_text: |data: String| { debug!("create text"); // NOTE: tmp vars are workaround for lifetime issues. Both required. let tmp_borrow = doc_cell.borrow(); diff --git a/src/components/script/script.rs b/src/components/script/script.rs index 4a2974d8cd2..f6dd0ba7025 100644 --- a/src/components/script/script.rs +++ b/src/components/script/script.rs @@ -16,6 +16,7 @@ #[phase(syntax, link)] extern crate log; +extern crate debug; extern crate collections; extern crate geom; extern crate hubbub; @@ -48,11 +49,11 @@ pub mod dom { pub mod str; pub mod trace; pub mod codegen { + pub mod Bindings; pub mod InterfaceTypes; pub mod InheritTypes; pub mod PrototypeList; pub mod RegisterBindings; - pub mod Bindings; pub mod UnionTypes; } } diff --git a/src/components/script/script_task.rs b/src/components/script/script_task.rs index 918e80c4c47..1929449f9a7 100644 --- a/src/components/script/script_task.rs +++ b/src/components/script/script_task.rs @@ -53,7 +53,6 @@ use servo_util::geometry::to_frac_px; use servo_util::task::send_on_failure; use servo_util::namespace::Null; use servo_util::str::DOMString; -use std::cast; use std::cell::{Cell, RefCell, Ref, RefMut}; use std::comm::{channel, Sender, Receiver, Empty, Disconnected}; use std::mem::replace; @@ -239,10 +238,8 @@ impl Page { .enumerate() .find(|&(_idx, ref page_tree)| { // FIXME: page_tree has a lifetime such that it's unusable for anything. - let page_tree = unsafe { - cast::transmute_lifetime(page_tree) - }; - page_tree.id == id + let page_tree_id = page_tree.id; + page_tree_id == id }) .map(|(idx, _)| idx) }; @@ -442,7 +439,7 @@ impl Page { /// Attempt to find a named element in this page's document. fn find_fragment_node(&self, fragid: DOMString) -> Option<Temporary<Element>> { let document = self.frame().get_ref().document.root(); - match document.deref().GetElementById(fragid.to_owned()) { + match document.deref().GetElementById(fragid.to_string()) { Some(node) => Some(node), None => { let doc_node: &JSRef<Node> = NodeCast::from_ref(&*document); @@ -451,7 +448,7 @@ impl Page { anchors.find(|node| { let elem: &JSRef<Element> = ElementCast::to_ref(node).unwrap(); elem.get_attribute(Null, "name").root().map_or(false, |attr| { - attr.deref().value_ref() == fragid + attr.deref().value_ref() == fragid.as_slice() }) }).map(|node| Temporary::from_rooted(ElementCast::to_ref(&node).unwrap())) } @@ -1007,7 +1004,7 @@ impl ScriptTask { // Kick off the initial reflow of the page. document.content_changed(); - let fragment = url.fragment.as_ref().map(|ref fragment| fragment.to_owned()); + let fragment = url.fragment.as_ref().map(|ref fragment| fragment.to_string()); { // No more reflow required @@ -1037,7 +1034,7 @@ impl ScriptTask { // "load" event as soon as we've finished executing all scripts parsed during // the initial load. let mut event = - Event::new(&*window, "load".to_owned(), false, false).root(); + Event::new(&*window, "load".to_string(), false, false).root(); let doctarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*document); let wintarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&*window); let _ = wintarget.dispatch_event_with_target(Some((*doctarget).clone()), @@ -1092,7 +1089,7 @@ impl ScriptTask { Some(mut window) => { // http://dev.w3.org/csswg/cssom-view/#resizing-viewports // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize - let mut uievent = UIEvent::new(&window.clone(), "resize".to_owned(), false, false, + let mut uievent = UIEvent::new(&window.clone(), "resize".to_string(), false, false, Some((*window).clone()), 0i32).root(); let event: &mut JSRef<Event> = EventCast::from_mut_ref(&mut *uievent); @@ -1134,7 +1131,7 @@ impl ScriptTask { let window = frame.window.root(); let mut event = Event::new(&*window, - "click".to_owned(), + "click".to_string(), true, true).root(); let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(&node); let _ = eventtarget.dispatch_event_with_target(None, &mut *event); diff --git a/src/components/style/.gitignore b/src/components/style/.gitignore index 79d1b1f5fe2..1f18fa1546d 100644 --- a/src/components/style/.gitignore +++ b/src/components/style/.gitignore @@ -1,2 +1,2 @@ -properties.rs -properties.rs.tmp +properties/mod.rs +properties/mod.rs.tmp diff --git a/src/components/style/errors.rs b/src/components/style/errors.rs index 215512c8e42..eb142d887fe 100644 --- a/src/components/style/errors.rs +++ b/src/components/style/errors.rs @@ -14,7 +14,8 @@ impl<T, I: Iterator<Result<T, SyntaxError>>> Iterator<T> for ErrorLoggerIterator loop { match this.next() { Some(Ok(v)) => return Some(v), - Some(Err(error)) => log_css_error(error.location, format!("{:?}", error.reason)), + Some(Err(error)) => log_css_error(error.location, + format!("{:?}", error.reason).as_slice()), None => return None, } } diff --git a/src/components/style/media_queries.rs b/src/components/style/media_queries.rs index 86198639d39..da2fa989c6f 100644 --- a/src/components/style/media_queries.rs +++ b/src/components/style/media_queries.rs @@ -63,7 +63,7 @@ pub fn parse_media_rule(rule: AtRule, parent_rules: &mut Vec<CSSRule>, match rule { QualifiedRule(rule) => parse_style_rule(rule, &mut rules, namespaces, base_url), AtRule(rule) => parse_nested_at_rule( - rule.name.as_slice().to_ascii_lower(), rule, &mut rules, namespaces, base_url), + rule.name.as_slice().to_ascii_lower().as_slice(), rule, &mut rules, namespaces, base_url), } } parent_rules.push(CSSMediaRule(MediaRule { diff --git a/src/components/style/namespaces.rs b/src/components/style/namespaces.rs index db025de9113..42a6bfae126 100644 --- a/src/components/style/namespaces.rs +++ b/src/components/style/namespaces.rs @@ -9,7 +9,7 @@ use errors::log_css_error; pub struct NamespaceMap { pub default: Option<Namespace>, - pub prefix_map: HashMap<~str, Namespace>, + pub prefix_map: HashMap<String, Namespace>, } @@ -29,7 +29,7 @@ pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) { }}; ); if rule.block.is_some() { syntax_error!() } - let mut prefix: Option<~str> = None; + let mut prefix: Option<String> = None; let mut ns: Option<Namespace> = None; let mut iter = rule.prelude.move_skip_whitespace(); for component_value in iter { diff --git a/src/components/style/parsing_utils.rs b/src/components/style/parsing_utils.rs index 35c88893b45..df355629971 100644 --- a/src/components/style/parsing_utils.rs +++ b/src/components/style/parsing_utils.rs @@ -13,7 +13,7 @@ pub fn one_component_value<'a>(input: &'a [ComponentValue]) -> Option<&'a Compon } -pub fn get_ident_lower(component_value: &ComponentValue) -> Option<~str> { +pub fn get_ident_lower(component_value: &ComponentValue) -> Option<String> { match component_value { &Ident(ref value) => Some(value.as_slice().to_ascii_lower()), _ => None, diff --git a/src/components/style/common_types.rs b/src/components/style/properties/common_types.rs index 680463df474..f7d8bbde60f 100644 --- a/src/components/style/common_types.rs +++ b/src/components/style/properties/common_types.rs @@ -115,7 +115,7 @@ pub mod specified { &ast::Percentage(ref value) if negative_ok || value.value >= 0. => Some(LPA_Percentage(value.value / 100.)), &Number(ref value) if value.value == 0. => Some(LPA_Length(Au_(Au(0)))), - &Ident(ref value) if value.to_owned().eq_ignore_ascii_case("auto") => Some(LPA_Auto), + &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("auto") => Some(LPA_Auto), _ => None } } @@ -144,7 +144,7 @@ pub mod specified { &ast::Percentage(ref value) if negative_ok || value.value >= 0. => Some(LPN_Percentage(value.value / 100.)), &Number(ref value) if value.value == 0. => Some(LPN_Length(Au_(Au(0)))), - &Ident(ref value) if value.to_owned().eq_ignore_ascii_case("none") => Some(LPN_None), + &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("none") => Some(LPN_None), _ => None } } diff --git a/src/components/style/properties.rs.mako b/src/components/style/properties/mod.rs.mako index bbd4d53a887..85240a64204 100644 --- a/src/components/style/properties.rs.mako +++ b/src/components/style/properties/mod.rs.mako @@ -242,7 +242,7 @@ pub mod longhands { -> Option<specified::Length> { match component_value { &Ident(ref value) => { - match value.to_owned().to_ascii_lower().as_slice() { + match value.as_slice().to_ascii_lower().as_slice() { "thin" => Some(specified::Length::from_px(1.)), "medium" => Some(specified::Length::from_px(3.)), "thick" => Some(specified::Length::from_px(5.)), @@ -391,7 +391,7 @@ pub mod longhands { &Dimension(ref value, ref unit) if value.value >= 0. => specified::Length::parse_dimension(value.value, unit.as_slice()) .map(SpecifiedLength), - &Ident(ref value) if value.to_owned().eq_ignore_ascii_case("normal") + &Ident(ref value) if value.as_slice().eq_ignore_ascii_case("normal") => Some(SpecifiedNormal), _ => None, } @@ -472,7 +472,7 @@ pub mod longhands { -> Option<SpecifiedValue> { match input { &Ident(ref value) => { - match value.to_owned().to_ascii_lower().as_slice() { + match value.as_slice().to_ascii_lower().as_slice() { % for keyword in vertical_align_keywords: "${keyword}" => Some(Specified_${to_rust_ident(keyword)}), % endfor @@ -531,7 +531,7 @@ pub mod longhands { pub mod computed_value { #[deriving(Eq, Clone)] pub enum Content { - StringContent(~str), + StringContent(String), } #[allow(non_camel_case_types)] #[deriving(Eq, Clone)] @@ -549,7 +549,7 @@ pub mod longhands { pub fn parse(input: &[ComponentValue], _base_url: &Url) -> Option<SpecifiedValue> { match one_component_value(input) { Some(&Ident(ref keyword)) => { - match keyword.to_owned().to_ascii_lower().as_slice() { + match keyword.as_slice().to_ascii_lower().as_slice() { "normal" => return Some(normal), "none" => return Some(none), _ => () @@ -561,7 +561,7 @@ pub mod longhands { for component_value in input.skip_whitespace() { match component_value { &String(ref value) - => content.push(StringContent(value.to_owned())), + => content.push(StringContent(value.clone())), _ => return None // invalid/unsupported value } } @@ -593,7 +593,7 @@ pub mod longhands { let image_url = parse_url(url.as_slice(), Some(base_url.clone())); Some(Some(image_url)) }, - &ast::Ident(ref value) if value.to_owned().eq_ignore_ascii_case("none") => Some(None), + &ast::Ident(ref value) if value.as_slice().eq_ignore_ascii_case("none") => Some(None), _ => None, } } @@ -705,7 +705,7 @@ pub mod longhands { pub mod computed_value { #[deriving(Eq, Clone)] pub enum FontFamily { - FamilyName(~str), + FamilyName(String), // Generic // Serif, // SansSerif, @@ -716,7 +716,7 @@ pub mod longhands { pub type T = Vec<FontFamily>; } pub type SpecifiedValue = computed_value::T; - #[inline] pub fn get_initial_value() -> computed_value::T { vec!(FamilyName("serif".to_owned())) } + #[inline] pub fn get_initial_value() -> computed_value::T { vec!(FamilyName("serif".to_string())) } /// <familiy-name># /// <familiy-name> = <string> | [ <ident>+ ] /// TODO: <generic-familiy> @@ -740,9 +740,9 @@ pub mod longhands { 'outer: loop { match iter.next() { // TODO: avoid copying strings? - Some(&String(ref value)) => add!(FamilyName(value.to_owned()), break 'outer), + Some(&String(ref value)) => add!(FamilyName(value.clone()), break 'outer), Some(&Ident(ref value)) => { - match value.to_owned().to_ascii_lower().as_slice() { + match value.as_slice().to_ascii_lower().as_slice() { // "serif" => add!(Serif, break 'outer), // "sans-serif" => add!(SansSerif, break 'outer), // "cursive" => add!(Cursive, break 'outer), @@ -792,7 +792,7 @@ pub mod longhands { -> Option<SpecifiedValue> { match input { &Ident(ref value) => { - match value.to_owned().to_ascii_lower().as_slice() { + match value.as_slice().to_ascii_lower().as_slice() { "bold" => Some(SpecifiedWeight700), "normal" => Some(SpecifiedWeight400), "bolder" => Some(Bolder), @@ -1269,7 +1269,7 @@ pub mod shorthands { // font-style, font-weight and font-variant. // Leaves the values to None, 'normal' is the initial value for each of them. match get_ident_lower(component_value) { - Some(ref ident) if ident.to_owned().eq_ignore_ascii_case("normal") => { + Some(ref ident) if ident.as_slice().eq_ignore_ascii_case("normal") => { nb_normals += 1; continue; } @@ -1348,7 +1348,7 @@ mod property_bit_field { impl PropertyBitField { #[inline] pub fn new() -> PropertyBitField { - PropertyBitField { storage: unsafe { mem::init() } } + PropertyBitField { storage: unsafe { mem::zeroed() } } } #[inline] @@ -1410,7 +1410,7 @@ pub fn parse_property_declaration_list<I: Iterator<Node>>(input: I, base_url: &U for item in items.move_iter().rev() { match item { DeclAtRule(rule) => log_css_error( - rule.location, format!("Unsupported at-rule in declaration list: @{:s}", rule.name)), + rule.location, format!("Unsupported at-rule in declaration list: @{:s}", rule.name).as_slice()), Declaration(Declaration{ location: l, name: n, value: v, important: i}) => { // TODO: only keep the last valid declaration for a given name. let (list, seen) = if i { @@ -1418,11 +1418,11 @@ pub fn parse_property_declaration_list<I: Iterator<Node>>(input: I, base_url: &U } else { (&mut normal_declarations, &mut normal_seen) }; - match PropertyDeclaration::parse(n.to_owned(), v.as_slice(), list, base_url, seen) { + match PropertyDeclaration::parse(n.as_slice(), v.as_slice(), list, base_url, seen) { UnknownProperty => log_css_error(l, format!( - "Unsupported property: {}:{}", n, v.iter().to_css())), + "Unsupported property: {}:{}", n, v.iter().to_css()).as_slice()), InvalidValue => log_css_error(l, format!( - "Invalid value: {}:{}", n, v.iter().to_css())), + "Invalid value: {}:{}", n, v.iter().to_css()).as_slice()), ValidOrIgnoredDeclaration => (), } } @@ -1482,7 +1482,7 @@ impl PropertyDeclaration { base_url: &Url, seen: &mut PropertyBitField) -> PropertyDeclarationParseResult { // FIXME: local variable to work around Rust #10683 - let name_lower = name.to_owned().to_ascii_lower(); + let name_lower = name.as_slice().to_ascii_lower(); match name_lower.as_slice() { % for property in LONGHANDS: % if property.derived_from is None: diff --git a/src/components/style/selector_matching.rs b/src/components/style/selector_matching.rs index a553044128f..66a874ae798 100644 --- a/src/components/style/selector_matching.rs +++ b/src/components/style/selector_matching.rs @@ -10,7 +10,7 @@ use num::div_rem; use sync::Arc; use servo_util::namespace; -use servo_util::smallvec::SmallVec; +use servo_util::smallvec::VecLike; use servo_util::sort; use servo_util::str::DOMString; @@ -36,7 +36,7 @@ struct LowercaseAsciiString<'a>(&'a str); impl<'a> Equiv<DOMString> for LowercaseAsciiString<'a> { fn equiv(&self, other: &DOMString) -> bool { let LowercaseAsciiString(this) = *self; - this.eq_ignore_ascii_case(*other) + this.eq_ignore_ascii_case(other.as_slice()) } } @@ -49,7 +49,7 @@ impl<'a> Hash for LowercaseAsciiString<'a> { // `Ascii` type's invariants by using `to_ascii_nocheck`, but it's OK as we simply // convert to a byte afterward. unsafe { - state.write_u8(b.to_ascii_nocheck().to_lower().to_byte()).unwrap() + state.write_u8(b.to_ascii_nocheck().to_lowercase().to_byte()).unwrap() }; } // Terminate the string with a non-UTF-8 character, to match what the built-in string @@ -106,7 +106,7 @@ impl SelectorMap { /// Sort the Rules at the end to maintain cascading order. fn get_all_matching_rules<E:TElement, N:TNode<E>, - V:SmallVec<MatchedProperty>>( + V:VecLike<MatchedProperty>>( &self, node: &N, matching_rules_list: &mut V, @@ -116,15 +116,15 @@ impl SelectorMap { } // At the end, we're going to sort the rules that we added, so remember where we began. - let init_len = matching_rules_list.len(); + let init_len = matching_rules_list.vec_len(); let element = node.as_element(); match element.get_attr(&namespace::Null, "id") { Some(id) => { SelectorMap::get_matching_rules_from_hash(node, - &self.id_hash, - id, - matching_rules_list, - shareable) + &self.id_hash, + id, + matching_rules_list, + shareable) } None => {} } @@ -156,12 +156,12 @@ impl SelectorMap { shareable); // Sort only the rules we just added. - sort::quicksort(matching_rules_list.mut_slice_from(init_len)); + sort::quicksort(matching_rules_list.vec_mut_slice_from(init_len)); } fn get_matching_rules_from_hash<E:TElement, N:TNode<E>, - V:SmallVec<MatchedProperty>>( + V:VecLike<MatchedProperty>>( node: &N, hash: &HashMap<DOMString, Vec<Rule>>, key: &str, @@ -177,7 +177,7 @@ impl SelectorMap { fn get_matching_rules_from_hash_ignoring_case<E:TElement, N:TNode<E>, - V:SmallVec<MatchedProperty>>( + V:VecLike<MatchedProperty>>( node: &N, hash: &HashMap<DOMString, Vec<Rule>>, key: &str, @@ -194,7 +194,7 @@ impl SelectorMap { /// Adds rules in `rules` that match `node` to the `matching_rules` list. fn get_matching_rules<E:TElement, N:TNode<E>, - V:SmallVec<MatchedProperty>>( + V:VecLike<MatchedProperty>>( node: &N, rules: &[Rule], matching_rules: &mut V, @@ -202,7 +202,7 @@ impl SelectorMap { for rule in rules.iter() { if matches_compound_selector(&*rule.selector, node, shareable) { // TODO(pradeep): Is the cloning inefficient? - matching_rules.push(rule.property.clone()); + matching_rules.vec_push(rule.property.clone()); } } } @@ -260,7 +260,7 @@ impl SelectorMap { } /// Retrieve the first ID name in Rule, or None otherwise. - fn get_id_name(rule: &Rule) -> Option<~str> { + fn get_id_name(rule: &Rule) -> Option<String> { let simple_selector_sequence = &rule.selector.simple_selectors; for ss in simple_selector_sequence.iter() { match *ss { @@ -274,7 +274,7 @@ impl SelectorMap { } /// Retrieve the FIRST class name in Rule, or None otherwise. - fn get_class_name(rule: &Rule) -> Option<~str> { + fn get_class_name(rule: &Rule) -> Option<String> { let simple_selector_sequence = &rule.selector.simple_selectors; for ss in simple_selector_sequence.iter() { match *ss { @@ -288,13 +288,13 @@ impl SelectorMap { } /// Retrieve the name if it is a type selector, or None otherwise. - fn get_element_name(rule: &Rule) -> Option<~str> { + fn get_element_name(rule: &Rule) -> Option<String> { let simple_selector_sequence = &rule.selector.simple_selectors; for ss in simple_selector_sequence.iter() { match *ss { // HTML elements in HTML documents must be matched case-insensitively // TODO: case-sensitivity depends on the document type - LocalNameSelector(ref name) => return Some(name.to_ascii_lower()), + LocalNameSelector(ref name) => return Some(name.as_slice().to_ascii_lower()), _ => {} } } @@ -381,7 +381,7 @@ impl Stylist { /// in `css::matching::PrivateMatchMethods::candidate_element_allows_for_style_sharing`. pub fn push_applicable_declarations<E:TElement, N:TNode<E>, - V:SmallVec<MatchedProperty>>( + V:VecLike<MatchedProperty>>( &self, element: &N, style_attribute: Option<&PropertyDeclarationBlock>, @@ -410,7 +410,7 @@ impl Stylist { // Step 2: Normal style attributes. style_attribute.map(|sa| { shareable = false; - applicable_declarations.push(MatchedProperty::from_declarations(sa.normal.clone())) + applicable_declarations.vec_push(MatchedProperty::from_declarations(sa.normal.clone())) }); // Step 3: Author-supplied `!important` rules. @@ -421,7 +421,7 @@ impl Stylist { // Step 4: `!important` style attributes. style_attribute.map(|sa| { shareable = false; - applicable_declarations.push(MatchedProperty::from_declarations(sa.important.clone())) + applicable_declarations.vec_push(MatchedProperty::from_declarations(sa.important.clone())) }); // Step 5: User and UA `!important` rules. @@ -681,7 +681,7 @@ fn matches_simple_selector<E:TElement, let element = element.as_element(); element.get_attr(&namespace::Null, "id") .map_or(false, |attr| { - attr == *id + attr == id.as_slice() }) } // TODO: cache and intern class names on elements. diff --git a/src/components/style/selectors.rs b/src/components/style/selectors.rs index fa0d28d5b9a..30497988f0d 100644 --- a/src/components/style/selectors.rs +++ b/src/components/style/selectors.rs @@ -56,19 +56,19 @@ pub enum Combinator { #[deriving(Eq, Clone)] pub enum SimpleSelector { - IDSelector(~str), - ClassSelector(~str), - LocalNameSelector(~str), + IDSelector(String), + ClassSelector(String), + LocalNameSelector(String), NamespaceSelector(Namespace), // Attribute selectors AttrExists(AttrSelector), // [foo] - AttrEqual(AttrSelector, ~str), // [foo=bar] - AttrIncludes(AttrSelector, ~str), // [foo~=bar] - AttrDashMatch(AttrSelector, ~str, ~str), // [foo|=bar] Second string is the first + "-" - AttrPrefixMatch(AttrSelector, ~str), // [foo^=bar] - AttrSubstringMatch(AttrSelector, ~str), // [foo*=bar] - AttrSuffixMatch(AttrSelector, ~str), // [foo$=bar] + AttrEqual(AttrSelector, String), // [foo=bar] + AttrIncludes(AttrSelector, String), // [foo~=bar] + AttrDashMatch(AttrSelector, String, String), // [foo|=bar] Second string is the first + "-" + AttrPrefixMatch(AttrSelector, String), // [foo^=bar] + AttrSubstringMatch(AttrSelector, String), // [foo*=bar] + AttrSuffixMatch(AttrSelector, String), // [foo$=bar] // Pseudo-classes Negation(Vec<SimpleSelector>), @@ -79,7 +79,7 @@ pub enum SimpleSelector { FirstChild, LastChild, OnlyChild, // Empty, Root, -// Lang(~str), +// Lang(String), NthChild(i32, i32), NthLastChild(i32, i32), NthOfType(i32, i32), @@ -92,8 +92,8 @@ pub enum SimpleSelector { #[deriving(Eq, Clone)] pub struct AttrSelector { - pub name: ~str, - pub lower_name: ~str, + pub name: String, + pub lower_name: String, pub namespace: NamespaceConstraint, } @@ -367,13 +367,13 @@ enum QualifiedNameParseResult { InvalidQualifiedName, NotAQualifiedName, // Namespace URL, local name. None means '*' - QualifiedName(NamespaceConstraint, Option<~str>) + QualifiedName(NamespaceConstraint, Option<String>) } fn parse_qualified_name(iter: &mut Iter, in_attr_selector: bool, namespaces: &NamespaceMap) -> QualifiedNameParseResult { #[inline] - fn default_namespace(namespaces: &NamespaceMap, local_name: Option<~str>) + fn default_namespace(namespaces: &NamespaceMap, local_name: Option<String>) -> QualifiedNameParseResult { QualifiedName(match namespaces.default { Some(ref ns) => SpecificNamespace(ns.clone()), @@ -440,7 +440,7 @@ fn parse_attribute_selector(content: Vec<ComponentValue>, namespaces: &Namespace QualifiedName(_, None) => fail!("Implementation error, this should not happen."), QualifiedName(namespace, Some(local_name)) => AttrSelector { namespace: namespace, - lower_name: local_name.to_ascii_lower(), + lower_name: local_name.as_slice().to_ascii_lower(), name: local_name, }, }; @@ -459,7 +459,7 @@ fn parse_attribute_selector(content: Vec<ComponentValue>, namespaces: &Namespace Some(IncludeMatch) => AttrIncludes(attr, (get_value!()).into_owned()), // [foo~=bar] Some(DashMatch) => { let value = get_value!(); - let dashing_value = value.as_slice() + "-"; + let dashing_value = format!("{}-", value); AttrDashMatch(attr, value.into_owned(), dashing_value) // [foo|=bar] }, Some(PrefixMatch) => AttrPrefixMatch(attr, (get_value!()).into_owned()), // [foo^=bar] @@ -491,7 +491,7 @@ fn parse_simple_pseudo_class(name: &str) -> Option<SimpleSelector> { } -fn parse_functional_pseudo_class(name: StrBuf, arguments: Vec<ComponentValue>, +fn parse_functional_pseudo_class(name: String, arguments: Vec<ComponentValue>, namespaces: &NamespaceMap, inside_negation: bool) -> Option<SimpleSelector> { match name.as_slice().to_ascii_lower().as_slice() { @@ -506,7 +506,7 @@ fn parse_functional_pseudo_class(name: StrBuf, arguments: Vec<ComponentValue>, } -fn parse_pseudo_element(name: StrBuf) -> Option<PseudoElement> { +fn parse_pseudo_element(name: String) -> Option<PseudoElement> { match name.as_slice().to_ascii_lower().as_slice() { // All supported pseudo-elements "before" => Some(Before), @@ -549,7 +549,7 @@ fn parse_negation(arguments: Vec<ComponentValue>, namespaces: &NamespaceMap) /// Assuming the next token is an ident, consume it and return its value #[inline] -fn get_next_ident(iter: &mut Iter) -> ~str { +fn get_next_ident(iter: &mut Iter) -> String { match iter.next() { Some(Ident(value)) => value.into_owned(), _ => fail!("Implementation error, this should not happen."), diff --git a/src/components/style/style.rs b/src/components/style/style.rs index a2f7bea6e4e..e667fa743b3 100644 --- a/src/components/style/style.rs +++ b/src/components/style/style.rs @@ -15,6 +15,7 @@ #![feature(phase)] #[phase(syntax, link)] extern crate log; +extern crate debug; extern crate collections; extern crate num; extern crate serialize; diff --git a/src/components/style/stylesheets.rs b/src/components/style/stylesheets.rs index 6a70e9c6d2b..cfe1c52a1c4 100644 --- a/src/components/style/stylesheets.rs +++ b/src/components/style/stylesheets.rs @@ -113,7 +113,7 @@ impl Stylesheet { }, _ => { next_state = STATE_BODY; - parse_nested_at_rule(lower_name, rule, &mut rules, &namespaces, &base_url) + parse_nested_at_rule(lower_name.as_slice(), rule, &mut rules, &namespaces, &base_url) }, } }, @@ -136,7 +136,7 @@ pub fn parse_style_rule(rule: QualifiedRule, parent_rules: &mut Vec<CSSRule>, declarations: properties::parse_property_declaration_list(block.move_iter(), base_url) })), None => log_css_error(location, format!( - "Invalid/unsupported selector: {}", serialized)), + "Invalid/unsupported selector: {}", serialized).as_slice()), } } @@ -146,7 +146,8 @@ pub fn parse_nested_at_rule(lower_name: &str, rule: AtRule, parent_rules: &mut Vec<CSSRule>, namespaces: &NamespaceMap, base_url: &Url) { match lower_name { "media" => parse_media_rule(rule, parent_rules, namespaces, base_url), - _ => log_css_error(rule.location, format!("Unsupported at-rule: @{:s}", lower_name)) + _ => log_css_error(rule.location, + format!("Unsupported at-rule: @{:s}", lower_name).as_slice()) } } diff --git a/src/components/util/debug.rs b/src/components/util/debug_utils.rs index 6bd32517138..579632f24c8 100644 --- a/src/components/util/debug.rs +++ b/src/components/util/debug_utils.rs @@ -4,7 +4,7 @@ use std::io; use std::io::Writer; -use std::cast::transmute; +use std::mem; use std::mem::size_of; use std::slice::raw::buf_as_slice; @@ -26,7 +26,7 @@ fn hexdump_slice(buf: &[u8]) { pub fn hexdump<T>(obj: &T) { unsafe { - let buf: *u8 = transmute(obj); + let buf: *u8 = mem::transmute(obj); debug!("dumping at {:p}", buf); buf_as_slice(buf, size_of::<T>(), hexdump_slice); } diff --git a/src/components/util/geometry.rs b/src/components/util/geometry.rs index f63b7aa1cce..c72dd03bd23 100644 --- a/src/components/util/geometry.rs +++ b/src/components/util/geometry.rs @@ -25,7 +25,7 @@ impl Default for Au { impl fmt::Show for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Au(n) = *self; - write!(f.buf, "Au(au={} px={})", n, to_frac_px(*self)) + write!(f, "Au(au={} px={})", n, to_frac_px(*self)) }} impl Add<Au,Au> for Au { diff --git a/src/components/util/namespace.rs b/src/components/util/namespace.rs index b23b235bad0..22dd1655443 100644 --- a/src/components/util/namespace.rs +++ b/src/components/util/namespace.rs @@ -11,7 +11,7 @@ pub enum Namespace { XLink, SVG, MathML, - Other(~str) + Other(String) } impl Namespace { @@ -25,7 +25,7 @@ impl Namespace { "http://www.w3.org/2000/svg" => SVG, "http://www.w3.org/1998/Math/MathML" => MathML, "" => Null, - ns => Other(ns.to_owned()) + ns => Other(ns.to_string()) } } pub fn to_str<'a>(&'a self) -> &'a str { diff --git a/src/components/util/opts.rs b/src/components/util/opts.rs index c18132dec1f..b17d2d196c2 100644 --- a/src/components/util/opts.rs +++ b/src/components/util/opts.rs @@ -17,7 +17,7 @@ use std::rt; #[deriving(Clone)] pub struct Opts { /// The initial URLs to load. - pub urls: Vec<~str>, + pub urls: Vec<String>, /// The rendering backend to use (`-r`). pub render_backend: BackendType, @@ -49,7 +49,7 @@ pub struct Opts { /// True to exit after the page load (`-x`). pub exit_after_load: bool, - pub output_file: Option<~str>, + pub output_file: Option<String>, pub headless: bool, pub hard_fail: bool, @@ -62,7 +62,7 @@ pub struct Opts { fn print_usage(app: &str, opts: &[getopts::OptGroup]) { let message = format!("Usage: {} [ options ... ] [URL]\n\twhere options include", app); - println!("{}", getopts::usage(message, opts)); + println!("{}", getopts::usage(message.as_slice(), opts)); } fn args_fail(msg: &str) { @@ -70,11 +70,11 @@ fn args_fail(msg: &str) { os::set_exit_status(1); } -pub fn from_cmdline_args(args: &[~str]) -> Option<Opts> { +pub fn from_cmdline_args(args: &[String]) -> Option<Opts> { let app_name = args[0].to_str(); let args = args.tail(); - let opts = ~[ + let opts = vec!( getopts::optflag("c", "cpu", "CPU rendering"), getopts::optopt("o", "output", "Output file", "output.png"), getopts::optopt("r", "rendering", "Rendering backend", "direct2d|core-graphics|core-graphics-accelerated|cairo|skia."), @@ -88,23 +88,23 @@ pub fn from_cmdline_args(args: &[~str]) -> Option<Opts> { getopts::optflag("f", "hard-fail", "Exit on task failure instead of displaying about:failure"), getopts::optflag("b", "bubble-widths", "Bubble intrinsic widths separately like other engines"), getopts::optflag("h", "help", "Print this message") - ]; + ); - let opt_match = match getopts::getopts(args, opts) { + let opt_match = match getopts::getopts(args, opts.as_slice()) { Ok(m) => m, Err(f) => { - args_fail(f.to_err_msg()); + args_fail(f.to_err_msg().as_slice()); return None; } }; if opt_match.opt_present("h") || opt_match.opt_present("help") { - print_usage(app_name, opts); + print_usage(app_name.as_slice(), opts.as_slice()); return None; }; let urls = if opt_match.free.is_empty() { - print_usage(app_name, opts); + print_usage(app_name.as_slice(), opts.as_slice()); args_fail("servo asks that you provide 1 or more URLs"); return None; } else { @@ -113,15 +113,15 @@ pub fn from_cmdline_args(args: &[~str]) -> Option<Opts> { let render_backend = match opt_match.opt_str("r") { Some(backend_str) => { - if "direct2d" == backend_str { + if "direct2d" == backend_str.as_slice() { Direct2DBackend - } else if "core-graphics" == backend_str { + } else if "core-graphics" == backend_str.as_slice() { CoreGraphicsBackend - } else if "core-graphics-accelerated" == backend_str { + } else if "core-graphics-accelerated" == backend_str.as_slice() { CoreGraphicsAcceleratedBackend - } else if "cairo" == backend_str { + } else if "cairo" == backend_str.as_slice() { CairoBackend - } else if "skia" == backend_str { + } else if "skia" == backend_str.as_slice() { SkiaBackend } else { fail!("unknown backend type") @@ -131,28 +131,28 @@ pub fn from_cmdline_args(args: &[~str]) -> Option<Opts> { }; let tile_size: uint = match opt_match.opt_str("s") { - Some(tile_size_str) => from_str(tile_size_str).unwrap(), + Some(tile_size_str) => from_str(tile_size_str.as_slice()).unwrap(), None => 512, }; let device_pixels_per_px = opt_match.opt_str("device-pixel-ratio").map(|dppx_str| - from_str(dppx_str).unwrap() + from_str(dppx_str.as_slice()).unwrap() ); let n_render_threads: uint = match opt_match.opt_str("t") { - Some(n_render_threads_str) => from_str(n_render_threads_str).unwrap(), + Some(n_render_threads_str) => from_str(n_render_threads_str.as_slice()).unwrap(), None => 1, // FIXME: Number of cores. }; // if only flag is present, default to 5 second period let profiler_period = opt_match.opt_default("p", "5").map(|period| { - from_str(period).unwrap() + from_str(period.as_slice()).unwrap() }); let cpu_painting = opt_match.opt_present("c"); let layout_threads: uint = match opt_match.opt_str("y") { - Some(layout_threads_str) => from_str(layout_threads_str).unwrap(), + Some(layout_threads_str) => from_str(layout_threads_str.as_slice()).unwrap(), None => cmp::max(rt::default_sched_threads() * 3 / 4, 1), }; diff --git a/src/components/util/range.rs b/src/components/util/range.rs index f5e0925c04b..3c261d4c265 100644 --- a/src/components/util/range.rs +++ b/src/components/util/range.rs @@ -108,7 +108,7 @@ pub struct Range<I> { impl<I: RangeIndex> fmt::Show for Range<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f.buf, "[{} .. {})", self.begin(), self.end()) + write!(f, "[{} .. {})", self.begin(), self.end()) } } diff --git a/src/components/util/smallvec.rs b/src/components/util/smallvec.rs index 655f20a685c..daa2083d464 100644 --- a/src/components/util/smallvec.rs +++ b/src/components/util/smallvec.rs @@ -6,17 +6,46 @@ //! to the heap for larger allocations. use i = std::mem::init; -use std::cast; use std::cmp; use std::intrinsics; use std::mem; use std::ptr; -use std::rt::global_heap; -use std::rt::local_heap; use std::raw::Slice; +use std::rt::local_heap; +use alloc::heap; // Generic code for all small vectors +pub trait VecLike<T> { + fn vec_len(&self) -> uint; + fn vec_push(&mut self, value: T); + + fn vec_mut_slice<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T]; + + #[inline] + fn vec_mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] { + let len = self.vec_len(); + self.vec_mut_slice(start, len) + } +} + +impl<T> VecLike<T> for Vec<T> { + #[inline] + fn vec_len(&self) -> uint { + self.len() + } + + #[inline] + fn vec_push(&mut self, value: T) { + self.push(value); + } + + #[inline] + fn vec_mut_slice<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T] { + self.mut_slice(start, end) + } +} + trait SmallVecPrivate<T> { unsafe fn set_len(&mut self, new_len: uint); unsafe fn set_cap(&mut self, new_cap: uint); @@ -63,8 +92,8 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { fn mut_iter<'a>(&'a mut self) -> SmallVecMutIterator<'a,T> { unsafe { SmallVecMutIterator { - ptr: cast::transmute(self.begin()), - end: cast::transmute(self.end()), + ptr: mem::transmute(self.begin()), + end: mem::transmute(self.end()), lifetime: None, } } @@ -74,9 +103,9 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { /// actually clears out the original array instead of moving it. fn move_iter<'a>(&'a mut self) -> SmallVecMoveIterator<'a,T> { unsafe { - let iter = cast::transmute(self.iter()); + let iter = mem::transmute(self.iter()); let ptr_opt = if self.spilled() { - Some(cast::transmute(self.ptr())) + Some(mem::transmute(self.ptr())) } else { None }; @@ -85,6 +114,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { self.set_len(0); SmallVecMoveIterator { allocation: ptr_opt, + cap: inline_size, iter: iter, lifetime: None, } @@ -97,8 +127,8 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { self.grow(cmp::max(cap * 2, 1)) } unsafe { - let end: &mut T = cast::transmute(self.end()); - mem::move_val_init(end, value); + let end: &mut T = mem::transmute(self.end()); + mem::overwrite(end, value); let len = self.len(); self.set_len(len + 1) } @@ -116,7 +146,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { } unsafe { - let mut value: T = mem::uninit(); + let mut value: T = mem::uninitialized(); let last_index = self.len() - 1; if (last_index as int) < 0 { @@ -124,7 +154,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { } let end_ptr = self.begin().offset(last_index as int); - mem::swap(&mut value, cast::transmute::<*T,&mut T>(end_ptr)); + mem::swap(&mut value, mem::transmute::<*T,&mut T>(end_ptr)); self.set_len(last_index); Some(value) } @@ -132,18 +162,21 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { fn grow(&mut self, new_cap: uint) { unsafe { - let new_alloc: *mut T = cast::transmute(global_heap::malloc_raw(mem::size_of::<T>() * - new_cap)); + let new_alloc: *mut T = mem::transmute(heap::allocate(mem::size_of::<T>() * + new_cap, + mem::min_align_of::<T>())); ptr::copy_nonoverlapping_memory(new_alloc, self.begin(), self.len()); if self.spilled() { if intrinsics::owns_managed::<T>() { local_heap::local_free(self.ptr() as *u8) } else { - global_heap::exchange_free(self.ptr() as *u8) + heap::deallocate(self.mut_ptr() as *mut u8, + mem::size_of::<T>() * self.cap(), + mem::min_align_of::<T>()) } } else { - let mut_begin: *mut T = cast::transmute(self.begin()); + let mut_begin: *mut T = mem::transmute(self.begin()); intrinsics::set_memory(mut_begin, 0, self.len()) } @@ -157,7 +190,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { self.fail_bounds_check(index) } unsafe { - cast::transmute(self.begin().offset(index as int)) + mem::transmute(self.begin().offset(index as int)) } } @@ -166,7 +199,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { self.fail_bounds_check(index) } unsafe { - cast::transmute(self.begin().offset(index as int)) + mem::transmute(self.begin().offset(index as int)) } } @@ -174,7 +207,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { assert!(start <= end); assert!(end <= self.len()); unsafe { - cast::transmute(Slice { + mem::transmute(Slice { data: self.begin().offset(start as int), len: (end - start) }) @@ -194,7 +227,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> { assert!(start <= end); assert!(end <= self.len()); unsafe { - cast::transmute(Slice { + mem::transmute(Slice { data: self.begin().offset(start as int), len: (end - start) }) @@ -226,11 +259,11 @@ impl<'a,T> Iterator<&'a T> for SmallVecIterator<'a,T> { } let old = self.ptr; self.ptr = if mem::size_of::<T>() == 0 { - cast::transmute(self.ptr as uint + 1) + mem::transmute(self.ptr as uint + 1) } else { self.ptr.offset(1) }; - Some(cast::transmute(old)) + Some(mem::transmute(old)) } } } @@ -250,17 +283,18 @@ impl<'a,T> Iterator<&'a mut T> for SmallVecMutIterator<'a,T> { } let old = self.ptr; self.ptr = if mem::size_of::<T>() == 0 { - cast::transmute(self.ptr as uint + 1) + mem::transmute(self.ptr as uint + 1) } else { self.ptr.offset(1) }; - Some(cast::transmute(old)) + Some(mem::transmute(old)) } } } pub struct SmallVecMoveIterator<'a,T> { allocation: Option<*mut u8>, + cap: uint, iter: SmallVecIterator<'static,T>, lifetime: Option<&'a T>, } @@ -273,8 +307,8 @@ impl<'a,T> Iterator<T> for SmallVecMoveIterator<'a,T> { None => None, Some(reference) => { // Zero out the values as we go so they don't get double-freed. - let reference: &mut T = cast::transmute(reference); - Some(mem::replace(reference, mem::init())) + let reference: &mut T = mem::transmute(reference); + Some(mem::replace(reference, mem::zeroed())) } } } @@ -294,7 +328,9 @@ impl<'a,T> Drop for SmallVecMoveIterator<'a,T> { if intrinsics::owns_managed::<T>() { local_heap::local_free(allocation as *u8) } else { - global_heap::exchange_free(allocation as *u8) + heap::deallocate(allocation as *mut u8, + mem::size_of::<T>() * self.cap, + mem::min_align_of::<T>()) } } } @@ -332,10 +368,10 @@ macro_rules! def_small_vector( self.ptr } unsafe fn mut_ptr(&mut self) -> *mut T { - cast::transmute(self.ptr) + mem::transmute(self.ptr) } unsafe fn set_ptr(&mut self, new_ptr: *mut T) { - self.ptr = cast::transmute(new_ptr) + self.ptr = mem::transmute(new_ptr) } } @@ -351,6 +387,23 @@ macro_rules! def_small_vector( } } + impl<T> VecLike<T> for $name<T> { + #[inline] + fn vec_len(&self) -> uint { + self.len() + } + + #[inline] + fn vec_push(&mut self, value: T) { + self.push(value); + } + + #[inline] + fn vec_mut_slice<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T] { + self.mut_slice(start, end) + } + } + impl<T> $name<T> { #[inline] pub fn new() -> $name<T> { @@ -359,7 +412,7 @@ macro_rules! def_small_vector( len: 0, cap: $size, ptr: ptr::null(), - data: mem::init(), + data: mem::zeroed(), } } } @@ -375,59 +428,6 @@ def_small_vector!(SmallVec16, 16) def_small_vector!(SmallVec24, 24) def_small_vector!(SmallVec32, 32) -/// TODO(pcwalton): Remove in favor of `vec_ng` after a Rust upgrade. -pub struct SmallVec0<T> { - len: uint, - cap: uint, - ptr: *mut T, -} - -impl<T> SmallVecPrivate<T> for SmallVec0<T> { - unsafe fn set_len(&mut self, new_len: uint) { - self.len = new_len - } - unsafe fn set_cap(&mut self, new_cap: uint) { - self.cap = new_cap - } - fn data(&self, _: uint) -> *T { - ptr::null() - } - fn mut_data(&mut self, _: uint) -> *mut T { - ptr::mut_null() - } - unsafe fn ptr(&self) -> *T { - cast::transmute(self.ptr) - } - unsafe fn mut_ptr(&mut self) -> *mut T { - self.ptr - } - unsafe fn set_ptr(&mut self, new_ptr: *mut T) { - self.ptr = new_ptr - } -} - -impl<T> SmallVec<T> for SmallVec0<T> { - fn inline_size(&self) -> uint { - 0 - } - fn len(&self) -> uint { - self.len - } - fn cap(&self) -> uint { - self.cap - } -} - -impl<T> SmallVec0<T> { - pub fn new() -> SmallVec0<T> { - SmallVec0 { - len: 0, - cap: 0, - ptr: ptr::mut_null(), - } - } -} - macro_rules! def_small_vector_drop_impl( ($name:ident, $size:expr) => ( #[unsafe_destructor] @@ -440,13 +440,15 @@ macro_rules! def_small_vector_drop_impl( unsafe { let ptr = self.mut_ptr(); for i in range(0, self.len()) { - *ptr.offset(i as int) = mem::uninit(); + *ptr.offset(i as int) = mem::uninitialized(); } if intrinsics::owns_managed::<T>() { local_heap::local_free(self.ptr() as *u8) } else { - global_heap::exchange_free(self.ptr() as *u8) + heap::deallocate(self.mut_ptr() as *mut u8, + mem::size_of::<T>() * self.cap(), + mem::min_align_of::<T>()) } } } @@ -454,7 +456,6 @@ macro_rules! def_small_vector_drop_impl( ) ) -def_small_vector_drop_impl!(SmallVec0, 0) def_small_vector_drop_impl!(SmallVec1, 1) def_small_vector_drop_impl!(SmallVec2, 2) def_small_vector_drop_impl!(SmallVec4, 4) @@ -477,7 +478,6 @@ macro_rules! def_small_vector_clone_impl( ) ) -def_small_vector_clone_impl!(SmallVec0) def_small_vector_clone_impl!(SmallVec1) def_small_vector_clone_impl!(SmallVec2) def_small_vector_clone_impl!(SmallVec4) @@ -488,57 +488,41 @@ def_small_vector_clone_impl!(SmallVec32) #[cfg(test)] pub mod tests { - use smallvec::{SmallVec, SmallVec0, SmallVec2, SmallVec16}; + use smallvec::{SmallVec, SmallVec2, SmallVec16}; // We heap allocate all these strings so that double frees will show up under valgrind. #[test] pub fn test_inline() { let mut v = SmallVec16::new(); - v.push("hello".to_owned()); - v.push("there".to_owned()); - assert_eq!(v.as_slice(), &["hello".to_owned(), "there".to_owned()]); + v.push("hello".to_string()); + v.push("there".to_string()); + assert_eq!(v.as_slice(), &["hello".to_string(), "there".to_string()]); } #[test] pub fn test_spill() { let mut v = SmallVec2::new(); - v.push("hello".to_owned()); - v.push("there".to_owned()); - v.push("burma".to_owned()); - v.push("shave".to_owned()); - assert_eq!(v.as_slice(), &["hello".to_owned(), "there".to_owned(), "burma".to_owned(), "shave".to_owned()]); + v.push("hello".to_string()); + v.push("there".to_string()); + v.push("burma".to_string()); + v.push("shave".to_string()); + assert_eq!(v.as_slice(), &["hello".to_string(), "there".to_string(), "burma".to_string(), "shave".to_string()]); } #[test] pub fn test_double_spill() { let mut v = SmallVec2::new(); - v.push("hello".to_owned()); - v.push("there".to_owned()); - v.push("burma".to_owned()); - v.push("shave".to_owned()); - v.push("hello".to_owned()); - v.push("there".to_owned()); - v.push("burma".to_owned()); - v.push("shave".to_owned()); - assert_eq!(v.as_slice(), &[ - "hello".to_owned(), "there".to_owned(), "burma".to_owned(), "shave".to_owned(), "hello".to_owned(), "there".to_owned(), "burma".to_owned(), "shave".to_owned(), - ]); - } - - #[test] - pub fn test_smallvec0() { - let mut v = SmallVec0::new(); - v.push("hello".to_owned()); - v.push("there".to_owned()); - v.push("burma".to_owned()); - v.push("shave".to_owned()); - v.push("hello".to_owned()); - v.push("there".to_owned()); - v.push("burma".to_owned()); - v.push("shave".to_owned()); + v.push("hello".to_string()); + v.push("there".to_string()); + v.push("burma".to_string()); + v.push("shave".to_string()); + v.push("hello".to_string()); + v.push("there".to_string()); + v.push("burma".to_string()); + v.push("shave".to_string()); assert_eq!(v.as_slice(), &[ - "hello".to_owned(), "there".to_owned(), "burma".to_owned(), "shave".to_owned(), "hello".to_owned(), "there".to_owned(), "burma".to_owned(), "shave".to_owned(), + "hello".to_string(), "there".to_string(), "burma".to_string(), "shave".to_string(), "hello".to_string(), "there".to_string(), "burma".to_string(), "shave".to_string(), ]); } } diff --git a/src/components/util/str.rs b/src/components/util/str.rs index f9e21a97260..28412dd55e7 100644 --- a/src/components/util/str.rs +++ b/src/components/util/str.rs @@ -5,7 +5,7 @@ use std::iter::Filter; use std::str::CharSplits; -pub type DOMString = ~str; +pub type DOMString = String; pub type StaticCharVec = &'static [char]; pub type StaticStringVec = &'static [&'static str]; @@ -13,7 +13,7 @@ pub fn null_str_as_empty(s: &Option<DOMString>) -> DOMString { // We don't use map_default because it would allocate "".to_owned() even for Some. match *s { Some(ref s) => s.clone(), - None => "".to_owned() + None => "".to_string() } } diff --git a/src/components/util/task.rs b/src/components/util/task.rs index f1d3211d4df..b965d555369 100644 --- a/src/components/util/task.rs +++ b/src/components/util/task.rs @@ -16,7 +16,7 @@ pub fn spawn_named<S: IntoMaybeOwned<'static>>(name: S, f: proc():Send) { /// this `TaskBuilder` fails. pub fn send_on_failure<T: Send>(builder: &mut TaskBuilder, msg: T, dest: Sender<T>) { let port = builder.future_result(); - let watched_name = builder.opts.name.as_ref().unwrap().as_slice().to_owned(); + let watched_name = builder.opts.name.as_ref().unwrap().as_slice().to_string(); let name = format!("{:s}Watcher", watched_name); spawn_named(name, proc() { match port.recv() { diff --git a/src/components/util/time.rs b/src/components/util/time.rs index 37247b6f041..ce296628c1b 100644 --- a/src/components/util/time.rs +++ b/src/components/util/time.rs @@ -84,7 +84,7 @@ impl ProfilerCategory { // some categories are subcategories of LayoutPerformCategory // and should be printed to indicate this - pub fn format(self) -> ~str { + pub fn format(self) -> String { let padding = match self { LayoutStyleRecalcCategory | LayoutMainCategory | diff --git a/src/components/util/url.rs b/src/components/util/url.rs index 7c13e124897..ccedb77918f 100644 --- a/src/components/util/url.rs +++ b/src/components/util/url.rs @@ -17,21 +17,21 @@ Create a URL object from a string. Does various helpful browsery things like */ // TODO: about:failure-> -pub fn try_parse_url(str_url: &str, base_url: Option<std_url::Url>) -> Result<std_url::Url, ~str> { - let str_url = str_url.trim_chars(&[' ', '\t', '\n', '\r', '\x0C']).to_owned(); - let schm = std_url::get_scheme(str_url); +pub fn try_parse_url(str_url: &str, base_url: Option<std_url::Url>) -> Result<std_url::Url, String> { + let str_url = str_url.trim_chars(&[' ', '\t', '\n', '\r', '\x0C']).to_string(); + let schm = std_url::get_scheme(str_url.as_slice()); let str_url = match schm { Err(_) => { if base_url.is_none() { // Assume we've been given a file path. If it's absolute just return // it, otherwise make it absolute with the cwd. - if str_url.starts_with("/") { - "file://".to_owned() + str_url + if str_url.as_slice().starts_with("/") { + format!("file://{}", str_url) } else { let mut path = os::getcwd(); path.push(str_url); // FIXME (#1094): not the right way to transform a path - "file://".to_owned() + path.display().to_str() + format!("file://{}", path.display().to_str()) } } else { let base_url = base_url.unwrap(); @@ -41,17 +41,17 @@ pub fn try_parse_url(str_url: &str, base_url: Option<std_url::Url>) -> Result<st new_url.query = vec!(); new_url.fragment = None; - if str_url.starts_with("//") { - new_url.scheme + ":" + str_url - } else if base_url.path.is_empty() || str_url.starts_with("/") { - new_url.path = "/".to_owned(); - new_url.to_str() + str_url.trim_left_chars('/') - } else if str_url.starts_with("#") { - new_url.to_str() + str_url + if str_url.as_slice().starts_with("//") { + format!("{}:{}", new_url.scheme, str_url) + } else if base_url.path.is_empty() || str_url.as_slice().starts_with("/") { + new_url.path = "/".to_string(); + format!("{}{}", new_url, str_url.as_slice().trim_left_chars('/')) + } else if str_url.as_slice().starts_with("#") { + format!("{}{}", new_url, str_url) } else { // relative path - let base_path = base_url.path.trim_right_chars(|c: char| c != '/'); - new_url.path = base_path.to_owned(); - new_url.to_str() + str_url + let base_path = base_url.path.as_slice().trim_right_chars(|c: char| c != '/'); + new_url.path = base_path.to_string(); + format!("{}{}", new_url, str_url) } } }, @@ -66,24 +66,24 @@ pub fn try_parse_url(str_url: &str, base_url: Option<std_url::Url>) -> Result<st let mut path = os::self_exe_path().expect("can't get exe path"); path.push("../src/test/html/failure.html"); // FIXME (#1094): not the right way to transform a path - "file://".to_owned() + path.display().to_str() + format!("file://{}", path.display().to_str()) } // TODO: handle the rest of the about: pages - _ => str_url.to_owned() + _ => str_url.to_string() } }, "data" => { // Drop whitespace within data: URLs, e.g. newlines within a base64 // src="..." block. Whitespace intended as content should be // %-encoded or base64'd. - str_url.chars().filter(|&c| !c.is_whitespace()).collect() + str_url.as_slice().chars().filter(|&c| !c.is_whitespace()).collect() }, - _ => str_url.to_owned() + _ => str_url.to_string() } } }; - std_url::from_str(str_url) + std_url::from_str(str_url.as_slice()) } pub fn parse_url(str_url: &str, base_url: Option<std_url::Url>) -> std_url::Url { @@ -102,10 +102,10 @@ mod parse_url_tests { let file = "local.html"; let url = parse_url(file, None); debug!("url: {:?}", url); - assert!("file" == url.scheme); + assert!("file" == url.scheme.as_slice()); let path = os::getcwd(); // FIXME (#1094): not the right way to transform a path - assert!(url.path.contains(path.display().to_str())); + assert!(url.path.as_slice().contains(path.display().to_str().as_slice())); } #[test] @@ -114,9 +114,9 @@ mod parse_url_tests { let old_url = parse_url(old_str, None); let new_str = "index.html"; let new_url = parse_url(new_str, Some(old_url)); - assert!("http" == new_url.scheme); - assert!("example.com" == new_url.host); - assert!("/index.html" == new_url.path); + assert!("http" == new_url.scheme.as_slice()); + assert!("example.com" == new_url.host.as_slice()); + assert!("/index.html" == new_url.path.as_slice()); } #[test] @@ -125,9 +125,9 @@ mod parse_url_tests { let old_url = parse_url(old_str, None); let new_str = "index.html"; let new_url = parse_url(new_str, Some(old_url)); - assert!("http" == new_url.scheme); - assert!("example.com" == new_url.host); - assert!("/index.html" == new_url.path); + assert!("http" == new_url.scheme.as_slice()); + assert!("example.com" == new_url.host.as_slice()); + assert!("/index.html" == new_url.path.as_slice()); } #[test] @@ -136,9 +136,9 @@ mod parse_url_tests { let old_url = parse_url(old_str, None); let new_str = "crumpet.html"; let new_url = parse_url(new_str, Some(old_url)); - assert!("http" == new_url.scheme); - assert!("example.com" == new_url.host); - assert!("/crumpet.html" == new_url.path); + assert!("http" == new_url.scheme.as_slice()); + assert!("example.com" == new_url.host.as_slice()); + assert!("/crumpet.html" == new_url.path.as_slice()); } #[test] @@ -147,9 +147,9 @@ mod parse_url_tests { let old_url = parse_url(old_str, None); let new_str = "crumpet.html"; let new_url = parse_url(new_str, Some(old_url)); - assert!("http" == new_url.scheme); - assert!("example.com" == new_url.host); - assert!("/snarf/crumpet.html" == new_url.path); + assert!("http" == new_url.scheme.as_slice()); + assert!("example.com" == new_url.host.as_slice()); + assert!("/snarf/crumpet.html" == new_url.path.as_slice()); } #[test] @@ -159,10 +159,10 @@ mod parse_url_tests { let new_str = "#top"; let new_url = parse_url(new_str, Some(old_url)); - assert!("http" == new_url.scheme); - assert!("example.com" == new_url.host); - assert!("/index.html" == new_url.path); - assert!(new_url.fragment == Some("top".to_owned())); + assert!("http" == new_url.scheme.as_slice()); + assert!("example.com" == new_url.host.as_slice()); + assert!("/index.html" == new_url.path.as_slice()); + assert!(new_url.fragment == Some("top".to_string())); } #[test] @@ -174,12 +174,12 @@ mod parse_url_tests { let new_str = "#top"; let new_url = parse_url(new_str, Some(old_url)); - assert!("http" == new_url.scheme); - assert!(new_url.user == Some(UserInfo { user: "foo".to_owned(), pass: Some("bar".to_owned()) })); - assert!("example.com" == new_url.host); - assert!(new_url.port == Some("8080".to_owned())); - assert!("/index.html" == new_url.path); - assert!(new_url.fragment == Some("top".to_owned())); + assert!("http" == new_url.scheme.as_slice()); + assert!(new_url.user == Some(UserInfo { user: "foo".to_string(), pass: Some("bar".to_string()) })); + assert!("example.com" == new_url.host.as_slice()); + assert!(new_url.port == Some("8080".to_string())); + assert!("/index.html" == new_url.path.as_slice()); + assert!(new_url.fragment == Some("top".to_string())); } #[test] @@ -188,9 +188,9 @@ mod parse_url_tests { let old_url = parse_url(old_str, None); let new_str = "//example.com/crumpet.html"; let new_url = parse_url(new_str, Some(old_url)); - assert!("https" == new_url.scheme); - assert!("example.com" == new_url.host); - assert!("/crumpet.html" == new_url.path); + assert!("https" == new_url.scheme.as_slice()); + assert!("example.com" == new_url.host.as_slice()); + assert!("/crumpet.html" == new_url.path.as_slice()); } } diff --git a/src/components/util/util.rs b/src/components/util/util.rs index 5318e3958f6..80c3fd115d4 100644 --- a/src/components/util/util.rs +++ b/src/components/util/util.rs @@ -13,6 +13,8 @@ #[phase(syntax, link)] extern crate log; +extern crate debug; +extern crate alloc; extern crate azure; extern crate collections; extern crate geom; @@ -25,7 +27,7 @@ extern crate std_time = "time"; extern crate std_url = "url"; pub mod cache; -pub mod debug; +pub mod debug_utils; pub mod geometry; pub mod namespace; pub mod opts; diff --git a/src/components/util/workqueue.rs b/src/components/util/workqueue.rs index 7c28abbb821..5caa6ff7ca0 100644 --- a/src/components/util/workqueue.rs +++ b/src/components/util/workqueue.rs @@ -10,7 +10,6 @@ use native; use rand; use rand::{Rng, XorShiftRng}; -use std::cast; use std::mem; use std::sync::atomics::{AtomicUint, SeqCst}; use std::sync::deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; @@ -92,7 +91,7 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> { // FIXME(pcwalton): Nasty workaround for the lack of labeled break/continue // cross-crate. let mut work_unit = unsafe { - mem::uninit() + mem::uninitialized() }; match deque.pop() { Some(work) => work_unit = work, @@ -179,7 +178,7 @@ impl<'a, QueueData, WorkData: Send> WorkerProxy<'a, QueueData, WorkData> { #[inline] pub fn user_data<'a>(&'a self) -> &'a QueueData { unsafe { - cast::transmute(self.queue_data) + mem::transmute(self.queue_data) } } } @@ -205,7 +204,7 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> { let (mut infos, mut threads) = (vec!(), vec!()); for i in range(0, thread_count) { let (worker_chan, worker_port) = channel(); - let mut pool = BufferPool::new(); + let pool = BufferPool::new(); let (worker, thief) = pool.deque(); infos.push(WorkerInfo { chan: worker_chan, diff --git a/src/platform/linux/rust-fontconfig b/src/platform/linux/rust-fontconfig -Subproject 51ea197c6f13ef4bb82910f0c955d5f8b064f00 +Subproject ee502da58190ecdd85d08eb0e11a2393cb0bd9d diff --git a/src/platform/macos/rust-cocoa b/src/platform/macos/rust-cocoa -Subproject 4b4cdd20f386cf4a2aebeee90b6ad35abf15d13 +Subproject c0036e25bbff4cc9f2100b344c37e50a0201a96 diff --git a/src/platform/macos/rust-core-foundation b/src/platform/macos/rust-core-foundation -Subproject 05383390ec26dbacbd380421e3a8640d801bba9 +Subproject fe9455de1723be0b8ce78a60e110e18c739940a diff --git a/src/platform/macos/rust-core-graphics b/src/platform/macos/rust-core-graphics -Subproject 2b6e3e199b997b4b8eed433f53e14f442e25f34 +Subproject 8bb25c2a193f3b47bb5406c78c2d04396c345f2 diff --git a/src/platform/macos/rust-core-text b/src/platform/macos/rust-core-text -Subproject 752d4f0594e60eb7b1fe38621a5cb5c11114d7a +Subproject 187c5852d2c285daa3d8c1a0a1e9c8c034a42ff diff --git a/src/platform/macos/rust-io-surface b/src/platform/macos/rust-io-surface -Subproject ba58fc2d2be6a93143946adfed9453c766ad38d +Subproject a0a42da1b85f431d18630454c5f2879c15771a5 diff --git a/src/support/alert/rust-alert b/src/support/alert/rust-alert -Subproject 6106b6e4c686ee091093a72d4b88fb521ff6fb7 +Subproject 8545e95c2d33d6a9d01ac04b206459d602f9491 diff --git a/src/support/azure/rust-azure b/src/support/azure/rust-azure -Subproject 8b2bbd9ef823be9df3c08a3d6444cb170810813 +Subproject 56beabc7132e9075620d397a38cf335003b846c diff --git a/src/support/css/rust-cssparser b/src/support/css/rust-cssparser -Subproject 83e13e5647cb33ce0a1801a7a0ebc4e0c897f89 +Subproject 01bbc87a189134a71016290ce7c8b77b3b77ffb diff --git a/src/support/encoding/rust-encoding b/src/support/encoding/rust-encoding -Subproject f09d5869d87b95ff11cc8963c259ae7e6c713fc +Subproject d6dc8d0402e317e9f9cc932ddb8502fcfc48438 diff --git a/src/support/geom/rust-geom b/src/support/geom/rust-geom -Subproject ab55c3f4f6edab87fe5802c58866d1e4455232a +Subproject db3eb69799fa629599a729c37d6101e115cec01 diff --git a/src/support/glfw/glfw-rs b/src/support/glfw/glfw-rs -Subproject 549702e27d0e32752dd6f4350950478330b7073 +Subproject 51cdd77e2319c35e1445ffca50c25bf3cf8372c diff --git a/src/support/harfbuzz/rust-harfbuzz b/src/support/harfbuzz/rust-harfbuzz -Subproject b0791864a1f37d52b85f7438e7571b02907f2a5 +Subproject 3763b41bc060731b7644e83f923ec69ca7c0c20 diff --git a/src/support/http/rust-http b/src/support/http/rust-http -Subproject f8762470a6e47c028d6af365dfdd99359dabaa1 +Subproject a02cf0c0b67fe159de9e5ffb8f31e923dd4754c diff --git a/src/support/hubbub/rust-hubbub b/src/support/hubbub/rust-hubbub -Subproject 62afc3d7da5a0f95d4e5c32096d2b701cfcd97a +Subproject 892c6477548e8f6c10b5ca7331d700421278122 diff --git a/src/support/layers/rust-layers b/src/support/layers/rust-layers -Subproject 261bef5849b817df2288f2f7dac5fe8f255a04a +Subproject 2fd4c58480e7c8aa8000a3cbe5d935c59b94eae diff --git a/src/support/opengles/rust-opengles b/src/support/opengles/rust-opengles -Subproject b850bd654acbadc522ed05ab9b5d67971e08588 +Subproject aa2334ece87de0a187373fced1b6dda019b81b0 diff --git a/src/support/png/rust-png b/src/support/png/rust-png -Subproject e242bab18f9354b3430f744b68a09ec0a5e253b +Subproject 0105a21091b89cda0c8480d2240c45dc0d7b385 diff --git a/src/support/sharegl/sharegl b/src/support/sharegl/sharegl -Subproject d0c4801aec9dcde4d4db7a961c1c895ec9f5720 +Subproject 673b4ec2d8aa40c27de31969fa69b8504036024 diff --git a/src/support/spidermonkey/rust-mozjs b/src/support/spidermonkey/rust-mozjs -Subproject d8313b9c8ef2018afd24ab0914a86191630c242 +Subproject 99be3ff35cce83d3b12c284cf7713712cb467a0 diff --git a/src/support/stb-image/rust-stb-image b/src/support/stb-image/rust-stb-image -Subproject e6746ef975e368cc920deec0d61caa74c571186 +Subproject c89ed2f05990ca2826149bf7ff5d4fb2e72f467 diff --git a/src/test/harness/contenttest/contenttest.rs b/src/test/harness/contenttest/contenttest.rs index 325e73dca71..bd57345811d 100644 --- a/src/test/harness/contenttest/contenttest.rs +++ b/src/test/harness/contenttest/contenttest.rs @@ -9,6 +9,7 @@ extern crate std; extern crate getopts; +extern crate regex; extern crate test; use test::{TestOpts, run_tests_console, TestDesc, TestDescAndFn, DynTestFn, DynTestName}; @@ -16,12 +17,13 @@ use getopts::{getopts, reqopt}; use std::{os, str}; use std::io::fs; use std::io::Reader; -use std::io::process::{Process, ProcessConfig, Ignored, CreatePipe, InheritFd, ExitStatus}; +use std::io::process::{Command, Ignored, CreatePipe, InheritFd, ExitStatus}; +use regex::Regex; #[deriving(Clone)] struct Config { - source_dir: ~str, - filter: Option<~str> + source_dir: String, + filter: Option<Regex> } fn main() { @@ -36,7 +38,7 @@ fn main() { } } -fn parse_config(args: Vec<~str>) -> Config { +fn parse_config(args: Vec<String>) -> Config { let args = args.tail(); let opts = vec!(reqopt("s", "source-dir", "source-dir", "source-dir")); let matches = match getopts(args, opts.as_slice()) { @@ -46,11 +48,7 @@ fn parse_config(args: Vec<~str>) -> Config { Config { source_dir: matches.opt_str("source-dir").unwrap(), - filter: if matches.free.is_empty() { - None - } else { - Some(matches.free.as_slice().head().unwrap().clone()) - } + filter: matches.free.as_slice().head().map(|s| Regex::new(s.as_slice()).unwrap()) } } @@ -79,7 +77,7 @@ fn find_tests(config: Config) -> Vec<TestDescAndFn> { return files.iter().map(|file| make_test(file.display().to_str()) ).collect(); } -fn make_test(file: ~str) -> TestDescAndFn { +fn make_test(file: String) -> TestDescAndFn { TestDescAndFn { desc: TestDesc { name: DynTestName(file.clone()), @@ -90,24 +88,22 @@ fn make_test(file: ~str) -> TestDescAndFn { } } -fn run_test(file: ~str) { +fn run_test(file: String) { let path = os::make_absolute(&Path::new(file)); // FIXME (#1094): not the right way to transform a path - let infile = "file://".to_owned() + path.display().to_str(); + let infile = "file://".to_string().append(path.display().to_str().as_slice()); let stdout = CreatePipe(false, true); let stderr = InheritFd(2); - let config = ProcessConfig { - program: "./servo", - args: &["-z".to_owned(), "-f".to_owned(), infile.clone()], - stdin: Ignored, - stdout: stdout, - stderr: stderr, - .. ProcessConfig::new() - }; - let mut prc = match Process::configure(config) { + let mut prc = match Command::new("./servo") + .args(["-z", "-f", infile.as_slice()]) + .stdin(Ignored) + .stdout(stdout) + .stderr(stderr) + .spawn() + { Ok(p) => p, - _ => fail!("Unable to configure process."), + _ => fail!("Unable to spawn process."), }; let mut output = Vec::new(); loop { @@ -125,12 +121,12 @@ fn run_test(file: ~str) { let lines: Vec<&str> = out.unwrap().split('\n').collect(); for &line in lines.iter() { if line.contains("TEST-UNEXPECTED-FAIL") { - fail!(line.to_owned()); + fail!(line.to_string()); } } let retval = prc.wait(); - if retval != ExitStatus(0) { + if retval != Ok(ExitStatus(0)) { fail!("Servo exited with non-zero status {}", retval); } } diff --git a/src/test/harness/reftest/reftest.rs b/src/test/harness/reftest/reftest.rs index 2cc27547750..255b2b55672 100644 --- a/src/test/harness/reftest/reftest.rs +++ b/src/test/harness/reftest/reftest.rs @@ -12,7 +12,7 @@ extern crate std; extern crate test; use std::io; -use std::io::{File, Reader, Process}; +use std::io::{File, Reader, Command}; use std::io::process::ExitStatus; use std::os; use test::{DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn}; @@ -57,14 +57,14 @@ enum ReftestKind { } struct Reftest { - name: ~str, + name: String, kind: ReftestKind, - files: [~str, ..2], + files: [String, ..2], id: uint, - servo_args: Vec<~str>, + servo_args: Vec<String>, } -fn parse_lists(filenames: &[~str], servo_args: &[~str]) -> Vec<TestDescAndFn> { +fn parse_lists(filenames: &[String], servo_args: &[String]) -> Vec<TestDescAndFn> { let mut tests = Vec::new(); let mut next_id = 0; for file in filenames.iter() { @@ -77,7 +77,7 @@ fn parse_lists(filenames: &[~str], servo_args: &[~str]) -> Vec<TestDescAndFn> { _ => fail!("Could not read file"), }; - for line in contents.lines() { + for line in contents.as_slice().lines() { // ignore comments if line.starts_with("#") { continue; @@ -97,11 +97,11 @@ fn parse_lists(filenames: &[~str], servo_args: &[~str]) -> Vec<TestDescAndFn> { }; let src_path = file_path.dir_path(); let src_dir = src_path.display().to_str(); - let file_left = src_dir + "/" + *parts.get(1); - let file_right = src_dir + "/" + *parts.get(2); + let file_left = src_dir.clone().append("/").append(*parts.get(1)); + let file_right = src_dir.append("/").append(*parts.get(2)); let reftest = Reftest { - name: parts.get(1) + " / " + *parts.get(2), + name: parts.get(1).to_string().append(" / ").append(*parts.get(2)), kind: kind, files: [file_left, file_right], id: next_id, @@ -135,13 +135,13 @@ fn capture(reftest: &Reftest, side: uint) -> png::Image { let mut args = reftest.servo_args.clone(); args.push_all_move(vec!("-f".to_owned(), "-o".to_owned(), filename.clone(), reftest.files[side].clone())); - let retval = match Process::status("./servo", args.as_slice()) { + let retval = match Command::new("./servo").args(args.as_slice()).status() { Ok(status) => status, Err(e) => fail!("failed to execute process: {}", e), }; assert!(retval == ExitStatus(0)); - png::load_png(&from_str::<Path>(filename).unwrap()).unwrap() + png::load_png(&from_str::<Path>(filename.as_slice()).unwrap()).unwrap() } fn check_reftest(reftest: Reftest) { @@ -163,7 +163,7 @@ fn check_reftest(reftest: Reftest) { if pixels.iter().any(|&a| a < 255) { let output_str = format!("/tmp/servo-reftest-{:06u}-diff.png", reftest.id); - let output = from_str::<Path>(output_str).unwrap(); + let output = from_str::<Path>(output_str.as_slice()).unwrap(); let img = png::Image { width: left.width, |