Upgrade Rust.

This commit is contained in:
Jack Moffitt 2014-07-21 07:37:24 -06:00
parent 8b6f62c195
commit b91e6f30e0
132 changed files with 764 additions and 738 deletions

2
.gitmodules vendored
View file

@ -70,7 +70,7 @@
url = https://github.com/servo/skia.git url = https://github.com/servo/skia.git
[submodule "src/compiler/rust"] [submodule "src/compiler/rust"]
path = src/compiler/rust path = src/compiler/rust
url = https://github.com/mozilla/rust.git url = https://github.com/servo/rust.git
[submodule "src/support/alert/rust-alert"] [submodule "src/support/alert/rust-alert"]
path = src/support/alert/rust-alert path = src/support/alert/rust-alert
url = https://github.com/servo/rust-alert.git url = https://github.com/servo/rust-alert.git

View file

@ -114,6 +114,13 @@ ifeq ($(CFG_OSTYPE),linux-androideabi)
CFG_RUSTC_FLAGS += --target arm-linux-androideabi -C linker=$(CFG_ANDROID_CROSS_PATH)/bin/arm-linux-androideabi-g++ -C ar=$(CFG_ANDROID_CROSS_PATH)/bin/arm-linux-androideabi-ar CFG_RUSTC_FLAGS += --target arm-linux-androideabi -C linker=$(CFG_ANDROID_CROSS_PATH)/bin/arm-linux-androideabi-g++ -C ar=$(CFG_ANDROID_CROSS_PATH)/bin/arm-linux-androideabi-ar
endif endif
# Set up LD_LIBRARY_PATH os the compiler can find libraries
ifeq ($(CFG_OSTYPE),apple-darwin)
export DYLD_LIBRARY_PATH=$(CFG_RUST_HOME)/lib
else
export LD_LIBRARY_PATH=$(CFG_RUST_HOME)/lib
endif
# Strip off submodule paths to determine "raw" submodule names. # Strip off submodule paths to determine "raw" submodule names.
SUBMODULES=$(shell echo $(CFG_SUBMODULES) | perl -p -e 's![A-Za-z0-9_-]+/!!g') SUBMODULES=$(shell echo $(CFG_SUBMODULES) | perl -p -e 's![A-Za-z0-9_-]+/!!g')

10
configure vendored
View file

@ -424,13 +424,18 @@ then
tar -zxf ${CFG_BUILD_DIR}/rust_snapshot/snapshot-${SNAPSHOT_HASH}.tgz -C ${CFG_BUILD_DIR}/rust_snapshot/ tar -zxf ${CFG_BUILD_DIR}/rust_snapshot/snapshot-${SNAPSHOT_HASH}.tgz -C ${CFG_BUILD_DIR}/rust_snapshot/
cp -f ${CFG_SRC_DIR}/src/compiler/rust-snapshot-hash ${CFG_BUILD_DIR}/src/compiler/rust-snapshot-hash-stamp cp -f ${CFG_SRC_DIR}/src/compiler/rust-snapshot-hash ${CFG_BUILD_DIR}/src/compiler/rust-snapshot-hash-stamp
fi fi
CFG_LOCAL_RUST_ROOT=${CFG_BUILD_DIR}/rust_snapshot/${SNAPSHOT_VERSION}-${DEFAULT_TARGET} CFG_LOCAL_RUST_ROOT=${CFG_BUILD_DIR}rust_snapshot/${SNAPSHOT_VERSION}-${DEFAULT_TARGET}
fi fi
if [ ! -z "$CFG_LOCAL_RUST_ROOT" ] if [ ! -z "$CFG_LOCAL_RUST_ROOT" ]
then then
if [ -f ${CFG_LOCAL_RUST_ROOT}/bin/rustc ] if [ -f ${CFG_LOCAL_RUST_ROOT}/bin/rustc ]
then then
if [ $CFG_OSTYPE = "apple-darwin" ]; then
export DYLD_LIBRARY_PATH=${CFG_LOCAL_RUST_ROOT}/lib
else
export LD_LIBRARY_PATH=${CFG_LOCAL_RUST_ROOT}/lib
fi
LRV=`${CFG_LOCAL_RUST_ROOT}/bin/rustc --version` LRV=`${CFG_LOCAL_RUST_ROOT}/bin/rustc --version`
step_msg "using rustc at: ${CFG_LOCAL_RUST_ROOT} with version: $LRV" step_msg "using rustc at: ${CFG_LOCAL_RUST_ROOT} with version: $LRV"
CFG_RUSTC=${CFG_LOCAL_RUST_ROOT}/bin/rustc CFG_RUSTC=${CFG_LOCAL_RUST_ROOT}/bin/rustc
@ -750,6 +755,9 @@ do
support/phf/rust-phf) support/phf/rust-phf)
ENABLE_DEBUG="" ENABLE_DEBUG=""
;; ;;
support/encoding/rust-encoding)
CONFIGURE_SCRIPT="${CFG_SRC_DIR}src/support/encoding/configure"
;;
support/url/rust-url) support/url/rust-url)
CONFIGURE_SCRIPT="${CFG_SRC_DIR}src/support/url/configure" CONFIGURE_SCRIPT="${CFG_SRC_DIR}src/support/url/configure"
;; ;;

@ -1 +1 @@
Subproject commit 9f8d2205f0518389993a9b5de6646ba8b14e5a12 Subproject commit 5e4a171bd551433e8d58114744c4efbc4bc90ae4

View file

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

View file

@ -1 +1 @@
9f8d2205f0518389993a9b5de6646ba8b14e5a12/rust-0.11.0-pre 5e4a171bd551433e8d58114744c4efbc4bc90ae4/rust-0.12.0-pre

View file

@ -2,9 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#compositing:0.1"] #![crate_name = "compositing"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"] #![comment = "The Servo Parallel Browser Project"]

View file

@ -916,13 +916,13 @@ impl IOCompositor {
.copy_memory(src_slice.slice_to(stride)); .copy_memory(src_slice.slice_to(stride));
} }
} }
let img = png::Image { let mut img = png::Image {
width: width as u32, width: width as u32,
height: height as u32, height: height as u32,
color_type: png::RGB8, color_type: png::RGB8,
pixels: pixels, pixels: pixels,
}; };
let res = png::store_png(&img, &path); let res = png::store_png(&mut img, &path);
assert!(res.is_ok()); assert!(res.is_ok());
debug!("shutting down the constellation after generating an output file"); debug!("shutting down the constellation after generating an output file");

View file

@ -607,7 +607,7 @@ impl<LTF: LayoutTaskFactory> Constellation<LTF> {
} }
fn handle_load_url_msg(&mut self, source_id: PipelineId, url: Url) { fn handle_load_url_msg(&mut self, source_id: PipelineId, url: Url) {
debug!("Constellation: received message to load {:s}", url.to_str()); debug!("Constellation: received message to load {:s}", url.to_string());
// Make sure no pending page would be overridden. // Make sure no pending page would be overridden.
let source_frame = self.current_frame().get_ref().find(source_id).expect( let source_frame = self.current_frame().get_ref().find(source_id).expect(
"Constellation: received a LoadUrlMsg from a pipeline_id associated "Constellation: received a LoadUrlMsg from a pipeline_id associated

View file

@ -121,14 +121,14 @@ impl WindowMethods<Application> for Window {
3 => { 3 => {
let tmp = local_window(); let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent( tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0, 5.0 as f32), TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0.0 as i32, 5.0 as i32))); TypedPoint2D(0i32, 5i32)));
}, },
4 => { 4 => {
let tmp = local_window(); let tmp = local_window();
tmp.event_queue.borrow_mut().push(ScrollWindowEvent( tmp.event_queue.borrow_mut().push(ScrollWindowEvent(
TypedPoint2D(0.0, -5.0 as f32), TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0.0 as i32, -5.0 as i32))); TypedPoint2D(0i32, -5i32)));
}, },
_ => {} _ => {}
} }
@ -229,10 +229,10 @@ impl Window {
42 => self.load_url(), 42 => self.load_url(),
43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)), 43 => self.event_queue.borrow_mut().push(ZoomWindowEvent(1.1)),
45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)), 45 => self.event_queue.borrow_mut().push(ZoomWindowEvent(0.909090909)),
56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0, 5.0 as f32), 56 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, 5.0f32),
TypedPoint2D(0.0 as i32, 5.0 as i32))), TypedPoint2D(0i32, 5i32))),
50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0, -5.0 as f32), 50 => self.event_queue.borrow_mut().push(ScrollWindowEvent(TypedPoint2D(0.0f32, -5.0f32),
TypedPoint2D(0.0 as i32, -5.0 as i32))), TypedPoint2D(0i32, -5i32))),
127 => { 127 => {
if (modifiers & ACTIVE_SHIFT) != 0 { if (modifiers & ACTIVE_SHIFT) != 0 {
self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward)); self.event_queue.borrow_mut().push(NavigationWindowEvent(Forward));

View file

@ -8,20 +8,20 @@ use std::mem;
use types::{cef_browser_settings_t, cef_browser_t, cef_client_t, cef_request_context_t, cef_string_t, cef_window_info_t}; use types::{cef_browser_settings_t, cef_browser_t, cef_client_t, cef_request_context_t, cef_string_t, cef_window_info_t};
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_browser_host_create_browser(_windowInfo: *cef_window_info_t, pub extern "C" fn cef_browser_host_create_browser(_windowInfo: *const cef_window_info_t,
_client: *mut cef_client_t, _client: *mut cef_client_t,
_url: *cef_string_t, _url: *const cef_string_t,
_settings: *cef_browser_settings_t, _settings: *const cef_browser_settings_t,
_request_context: *mut cef_request_context_t) _request_context: *mut cef_request_context_t)
-> c_int { -> c_int {
0 0
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_browser_host_create_browser_sync(_windowInfo: *cef_window_info_t, pub extern "C" fn cef_browser_host_create_browser_sync(_windowInfo: *const cef_window_info_t,
_client: *mut cef_client_t, _client: *mut cef_client_t,
_url: *cef_string_t, _url: *const cef_string_t,
_settings: *cef_browser_settings_t, _settings: *const cef_browser_settings_t,
_request_context: *mut cef_request_context_t) _request_context: *mut cef_request_context_t)
-> *mut cef_browser_t { -> *mut cef_browser_t {
unsafe { unsafe {

View file

@ -26,11 +26,11 @@ fn command_line_new() -> *mut command_line_t {
} }
} }
pub fn command_line_init(argc: c_int, argv: **u8) { pub fn command_line_init(argc: c_int, argv: *const *const u8) {
unsafe { unsafe {
let mut a: Vec<String> = vec!(); let mut a: Vec<String> = vec!();
for i in range(0u, argc as uint) { for i in range(0u, argc as uint) {
a.push(str::raw::from_c_str(*argv.offset(i as int) as *i8)); a.push(str::raw::from_c_str(*argv.offset(i as int) as *const i8));
} }
let cl = command_line_new(); let cl = command_line_new();
(*cl).argc = argc; (*cl).argc = argc;
@ -41,7 +41,7 @@ pub fn command_line_init(argc: c_int, argv: **u8) {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn command_line_get_switch_value(cmd: *mut cef_command_line_t, name: *cef_string_t) -> *mut cef_string_userfree_t { pub extern "C" fn command_line_get_switch_value(cmd: *mut cef_command_line_t, name: *const cef_string_t) -> *mut cef_string_userfree_t {
if cmd.is_null() || name.is_null() { if cmd.is_null() || name.is_null() {
return 0 as *mut cef_string_userfree_t; return 0 as *mut cef_string_userfree_t;
} }
@ -49,8 +49,8 @@ pub extern "C" fn command_line_get_switch_value(cmd: *mut cef_command_line_t, na
//technically cef_string_t can be any type of character size //technically cef_string_t can be any type of character size
//but the default cef callback uses utf16, so I'm jumping on board the SS Copy //but the default cef callback uses utf16, so I'm jumping on board the SS Copy
let cl: *mut command_line_t = mem::transmute(cmd); let cl: *mut command_line_t = mem::transmute(cmd);
let cs: *cef_string_utf16_t = mem::transmute(name); let cs: *const cef_string_utf16_t = mem::transmute(name);
let opt = str::from_utf16(CVec::new((*cs).str, (*cs).length as uint).as_slice()).unwrap(); let opt = String::from_utf16(CVec::new((*cs).str, (*cs).length as uint).as_slice()).unwrap();
//debug!("opt: {}", opt); //debug!("opt: {}", opt);
for s in (*cl).argv.iter() { for s in (*cl).argv.iter() {
let o = s.as_slice().trim_left_chars('-'); let o = s.as_slice().trim_left_chars('-');

View file

@ -15,10 +15,10 @@ use types::{cef_app_t, cef_main_args_t, cef_settings_t};
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_initialize(args: *cef_main_args_t, pub extern "C" fn cef_initialize(args: *const cef_main_args_t,
_settings: *mut cef_settings_t, _settings: *mut cef_settings_t,
application: *mut cef_app_t, application: *mut cef_app_t,
_windows_sandbox_info: *c_void) _windows_sandbox_info: *const c_void)
-> c_int { -> c_int {
if args.is_null() { if args.is_null() {
return 0; return 0;
@ -66,7 +66,7 @@ pub extern "C" fn cef_run_message_loop() {
bubble_inline_sizes_separately: false, bubble_inline_sizes_separately: false,
show_debug_borders: false, show_debug_borders: false,
}; };
native::start(0, 0 as **u8, proc() { native::start(0, 0 as *const *const u8, proc() {
servo::run(opts); servo::run(opts);
}); });
} }
@ -76,7 +76,7 @@ pub extern "C" fn cef_quit_message_loop() {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_execute_process(_args: *cef_main_args_t, pub extern "C" fn cef_execute_process(_args: *const cef_main_args_t,
_app: *mut cef_app_t, _app: *mut cef_app_t,
_windows_sandbox_info: *mut c_void) _windows_sandbox_info: *mut c_void)
-> c_int { -> c_int {

View file

@ -2,8 +2,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#embedding:0.1"] #![crate_name = "embedding"]
#![crate_type = "lib"] #![crate_type = "lib"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![feature(globs, macro_rules, phase, thread_local)] #![feature(globs, macro_rules, phase, thread_local)]

View file

@ -2,6 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
pub fn fptr_is_null(fptr: *u8) -> bool { pub fn fptr_is_null(fptr: *const u8) -> bool {
fptr.is_null() fptr.is_null()
} }

View file

@ -56,7 +56,7 @@ pub extern "C" fn cef_string_utf8_clear(cs: *mut cef_string_utf8_t) {
} }
(*cs).length = 0; (*cs).length = 0;
(*cs).str = 0 as *mut u8; (*cs).str = 0 as *mut u8;
(*cs).dtor = mem::transmute(0 as *u8); (*cs).dtor = mem::transmute(0 as *const u8);
} }
} }
@ -67,7 +67,7 @@ pub extern "C" fn cef_string_userfree_utf8_alloc() -> *mut cef_string_utf8_t {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_string_utf8_set(src: *u8, src_len: size_t, output: *mut cef_string_utf8_t, copy: c_int) -> c_int { pub extern "C" fn cef_string_utf8_set(src: *const u8, src_len: size_t, output: *mut cef_string_utf8_t, copy: c_int) -> c_int {
cef_string_utf8_clear(output); cef_string_utf8_clear(output);
unsafe { unsafe {
if copy != 0 { if copy != 0 {
@ -84,7 +84,7 @@ pub extern "C" fn cef_string_utf8_set(src: *u8, src_len: size_t, output: *mut ce
} else { } else {
(*output).str = mem::transmute(src); (*output).str = mem::transmute(src);
(*output).length = src_len; (*output).length = src_len;
(*output).dtor = mem::transmute(0 as *u8); (*output).dtor = mem::transmute(0 as *const u8);
} }
} }
return 1; return 1;
@ -99,7 +99,7 @@ pub extern "C" fn cef_string_utf16_clear(cs: *mut cef_string_utf16_t) {
} }
(*cs).length = 0; (*cs).length = 0;
(*cs).str = 0 as *mut c_ushort; (*cs).str = 0 as *mut c_ushort;
(*cs).dtor = mem::transmute(0 as *u8); (*cs).dtor = mem::transmute(0 as *const u8);
} }
} }
@ -110,7 +110,7 @@ pub extern "C" fn cef_string_userfree_utf16_alloc() -> *mut cef_string_utf16_t {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_string_utf16_set(src: *c_ushort, src_len: size_t, output: *mut cef_string_utf16_t, copy: c_int) -> c_int { pub extern "C" fn cef_string_utf16_set(src: *const c_ushort, src_len: size_t, output: *mut cef_string_utf16_t, copy: c_int) -> c_int {
cef_string_utf16_clear(output); cef_string_utf16_clear(output);
unsafe { unsafe {
if copy != 0 { if copy != 0 {
@ -127,7 +127,7 @@ pub extern "C" fn cef_string_utf16_set(src: *c_ushort, src_len: size_t, output:
} else { } else {
(*output).str = mem::transmute(src); (*output).str = mem::transmute(src);
(*output).length = src_len; (*output).length = src_len;
(*output).dtor = mem::transmute(0 as *u8); (*output).dtor = mem::transmute(0 as *const u8);
} }
} }
return 1; return 1;
@ -142,7 +142,7 @@ pub extern "C" fn cef_string_wide_clear(cs: *mut cef_string_wide_t) {
} }
(*cs).length = 0; (*cs).length = 0;
(*cs).str = 0 as *mut wchar_t; (*cs).str = 0 as *mut wchar_t;
(*cs).dtor = mem::transmute(0 as *u8); (*cs).dtor = mem::transmute(0 as *const u8);
} }
} }
@ -153,7 +153,7 @@ pub extern "C" fn cef_string_userfree_wide_alloc() -> *mut cef_string_wide_t {
} }
#[no_mangle] #[no_mangle]
pub extern "C" fn cef_string_wide_set(src: *wchar_t, src_len: size_t, output: *mut cef_string_wide_t, copy: c_int) -> c_int { pub extern "C" fn cef_string_wide_set(src: *const wchar_t, src_len: size_t, output: *mut cef_string_wide_t, copy: c_int) -> c_int {
cef_string_wide_clear(output); cef_string_wide_clear(output);
unsafe { unsafe {
if copy != 0 { if copy != 0 {
@ -170,7 +170,7 @@ pub extern "C" fn cef_string_wide_set(src: *wchar_t, src_len: size_t, output: *m
} else { } else {
(*output).str = mem::transmute(src); (*output).str = mem::transmute(src);
(*output).length = src_len; (*output).length = src_len;
(*output).dtor = mem::transmute(0 as *u8); (*output).dtor = mem::transmute(0 as *const u8);
} }
} }
return 1; return 1;

View file

@ -11,23 +11,23 @@ pub type cef_text_input_context_t = c_void;
pub type cef_event_handle_t = c_void; pub type cef_event_handle_t = c_void;
//these all need to be done... //these all need to be done...
pub type cef_binary_value = *c_void; pub type cef_binary_value = *mut c_void;
pub type cef_dictionary_value = *c_void; pub type cef_dictionary_value = *mut c_void;
pub type cef_client_t = c_void; pub type cef_client_t = c_void;
pub type cef_request_t = c_void; pub type cef_request_t = c_void;
pub type cef_response_t = c_void; pub type cef_response_t = c_void;
pub type cef_urlrequest_client_t = c_void; pub type cef_urlrequest_client_t = c_void;
pub type cef_frame = *c_void; pub type cef_frame = *mut c_void;
pub type cef_domnode = *c_void; pub type cef_domnode = *mut c_void;
pub type cef_load_handler = *c_void; pub type cef_load_handler = *mut c_void;
pub type cef_request = *c_void; pub type cef_request = *mut c_void;
pub type cef_navigation_type = *c_void; pub type cef_navigation_type = *mut c_void;
pub type cef_request_context_t = c_void; pub type cef_request_context_t = c_void;
pub type cef_window_info_t = c_void; pub type cef_window_info_t = c_void;
pub type cef_browser_settings_t = c_void; pub type cef_browser_settings_t = c_void;
pub type cef_v8context = *c_void; pub type cef_v8context = *mut c_void;
pub type cef_v8exception = *c_void; pub type cef_v8exception = *mut c_void;
pub type cef_v8stack_trace = *c_void; pub type cef_v8stack_trace = *mut c_void;
pub type cef_window_handle_t = c_void; //FIXME: wtf is this pub type cef_window_handle_t = c_void; //FIXME: wtf is this
pub type cef_string_t = cef_string_utf8; //FIXME: this is #defined... pub type cef_string_t = cef_string_utf8; //FIXME: this is #defined...
@ -60,7 +60,7 @@ pub struct cef_string_wide {
pub type cef_main_args_t = cef_main_args; pub type cef_main_args_t = cef_main_args;
pub struct cef_main_args { pub struct cef_main_args {
pub argc: c_int, pub argc: c_int,
pub argv: **u8 pub argv: *const *const u8
} }
pub type cef_color_t = c_uint; pub type cef_color_t = c_uint;
@ -799,13 +799,13 @@ pub struct cef_command_line {
// The first argument must be the name of the program. This function is only // The first argument must be the name of the program. This function is only
// supported on non-Windows platforms. // supported on non-Windows platforms.
/// ///
pub init_from_argv: extern "C" fn(cmd: *mut cef_command_line, argc: c_int, argv: *u8), pub init_from_argv: extern "C" fn(cmd: *mut cef_command_line, argc: c_int, argv: *const u8),
/// ///
// Initialize the command line with the string returned by calling // Initialize the command line with the string returned by calling
// GetCommandLineW(). This function is only supported on Windows. // GetCommandLineW(). This function is only supported on Windows.
/// ///
pub init_from_string: extern "C" fn(cmd: *mut cef_command_line, command_line: *cef_string_t), pub init_from_string: extern "C" fn(cmd: *mut cef_command_line, command_line: *const cef_string_t),
/// ///
// Reset the command-line switches and arguments but leave the program // Reset the command-line switches and arguments but leave the program
@ -835,7 +835,7 @@ pub struct cef_command_line {
/// ///
// Set the program part of the command line string (the first item). // Set the program part of the command line string (the first item).
/// ///
pub set_program: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t), pub set_program: extern "C" fn(cmd: *mut cef_command_line, name: *const cef_string_t),
/// ///
// Returns true (1) if the command line has switches. // Returns true (1) if the command line has switches.
@ -845,14 +845,14 @@ pub struct cef_command_line {
/// ///
// Returns true (1) if the command line contains the given switch. // Returns true (1) if the command line contains the given switch.
/// ///
pub has_switch: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t) -> c_int, pub has_switch: extern "C" fn(cmd: *mut cef_command_line, name: *const cef_string_t) -> c_int,
/// ///
// Returns the value associated with the given switch. If the switch has no // Returns the value associated with the given switch. If the switch has no
// value or isn't present this function returns the NULL string. // value or isn't present this function returns the NULL string.
/// ///
// The resulting string must be freed by calling cef_string_userfree_free(). // The resulting string must be freed by calling cef_string_userfree_free().
pub get_switch_value: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t) -> *mut cef_string_userfree_t, pub get_switch_value: extern "C" fn(cmd: *mut cef_command_line, name: *const cef_string_t) -> *mut cef_string_userfree_t,
/// ///
// Returns the map of switch names and values. If a switch has no value an // Returns the map of switch names and values. If a switch has no value an
@ -864,12 +864,12 @@ pub struct cef_command_line {
// Add a switch to the end of the command line. If the switch has no value // Add a switch to the end of the command line. If the switch has no value
// pass an NULL value string. // pass an NULL value string.
/// ///
pub append_switch: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t), pub append_switch: extern "C" fn(cmd: *mut cef_command_line, name: *const cef_string_t),
/// ///
// Add a switch with the specified value to the end of the command line. // Add a switch with the specified value to the end of the command line.
/// ///
pub append_switch_with_value: extern "C" fn(cmd: *mut cef_command_line, name: *cef_string_t, value: *cef_string_t), pub append_switch_with_value: extern "C" fn(cmd: *mut cef_command_line, name: *const cef_string_t, value: *const cef_string_t),
/// ///
// True if there are remaining command line arguments. // True if there are remaining command line arguments.
@ -884,13 +884,13 @@ pub struct cef_command_line {
/// ///
// Add an argument to the end of the command line. // Add an argument to the end of the command line.
/// ///
pub append_argument: extern "C" fn(cmd: *mut cef_command_line, argument: *cef_string_t), pub append_argument: extern "C" fn(cmd: *mut cef_command_line, argument: *const cef_string_t),
/// ///
// Insert a command before the current command. Common for debuggers, like // Insert a command before the current command. Common for debuggers, like
// "valgrind" or "gdb --args". // "valgrind" or "gdb --args".
/// ///
pub prepend_wrapper: extern "C" fn(cmd: *mut cef_command_line, wrapper: *cef_string_t), pub prepend_wrapper: extern "C" fn(cmd: *mut cef_command_line, wrapper: *const cef_string_t),
} }
@ -951,7 +951,7 @@ pub struct cef_scheme_registrar {
// if an error occurs this function will return false (0). // if an error occurs this function will return false (0).
/// ///
_add_custom_scheme: extern "C" fn(registrar: *mut cef_scheme_registrar, _add_custom_scheme: extern "C" fn(registrar: *mut cef_scheme_registrar,
scheme_name: *cef_string_t, scheme_name: *const cef_string_t,
is_standard: c_int, is_local: c_int, is_standard: c_int, is_local: c_int,
is_display_isolated: c_int), is_display_isolated: c_int),
} }
@ -985,7 +985,7 @@ pub struct cef_resource_bundle_handler {
// cef_pack_resources.h. // cef_pack_resources.h.
/// ///
pub get_data_resource: extern "C" fn(bundle_handler: *mut cef_resource_bundle_handler, pub get_data_resource: extern "C" fn(bundle_handler: *mut cef_resource_bundle_handler,
resource_id: c_int, data: **mut c_void, data_size: *mut size_t) -> c_int, resource_id: c_int, data: *mut *mut c_void, data_size: *mut size_t) -> c_int,
} }
@ -1112,7 +1112,7 @@ pub struct cef_list_value {
// Sets the value at the specified index as type string. Returns true (1) if // Sets the value at the specified index as type string. Returns true (1) if
// the value was set successfully. // the value was set successfully.
/// ///
pub set_string: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *cef_string_t) -> c_int, pub set_string: extern "C" fn(list_value: *mut cef_list_value, index: c_int, value: *const cef_string_t) -> c_int,
/// ///
// Sets the value at the specified index as type binary. Returns true (1) if // Sets the value at the specified index as type binary. Returns true (1) if
@ -1297,14 +1297,14 @@ pub struct cef_browser_host {
// the UI thread. // the UI thread.
/// ///
pub run_file_dialog: extern "C" fn(browser_host: *mut cef_browser_host, pub run_file_dialog: extern "C" fn(browser_host: *mut cef_browser_host,
mode: cef_file_dialog_mode_t, title: *cef_string_t, mode: cef_file_dialog_mode_t, title: *const cef_string_t,
default_file_name: *cef_string_t, accept_types: *mut cef_string_list_t, default_file_name: *const cef_string_t, accept_types: *mut cef_string_list_t,
callback: *mut cef_run_file_dialog_callback), callback: *mut cef_run_file_dialog_callback),
/// ///
// Download the file at |url| using cef_download_handler_t. // Download the file at |url| using cef_download_handler_t.
/// ///
pub start_download: extern "C" fn(browser_host: *mut cef_browser_host, url: *cef_string_t), pub start_download: extern "C" fn(browser_host: *mut cef_browser_host, url: *const cef_string_t),
/// ///
// Print the current browser contents. // Print the current browser contents.
@ -1318,7 +1318,7 @@ pub struct cef_browser_host {
// be case-sensitive. |findNext| indicates whether this is the first request // be case-sensitive. |findNext| indicates whether this is the first request
// or a follow-up. // or a follow-up.
/// ///
pub find: extern "C" fn(browser_host: *mut cef_browser_host, identifier: c_int, searchText: *cef_string_t, pub find: extern "C" fn(browser_host: *mut cef_browser_host, identifier: c_int, searchText: *const cef_string_t,
forward: c_int, matchCase: c_int, findNext: c_int), forward: c_int, matchCase: c_int, findNext: c_int),
/// ///
@ -1330,9 +1330,9 @@ pub struct cef_browser_host {
// Open developer tools in its own window. // Open developer tools in its own window.
/// ///
pub show_dev_tools: extern "C" fn(browser_host: *mut cef_browser_host, pub show_dev_tools: extern "C" fn(browser_host: *mut cef_browser_host,
windowInfo: *cef_window_info_t, windowInfo: *const cef_window_info_t,
client: *mut cef_client_t, client: *mut cef_client_t,
settings: *cef_browser_settings_t), settings: *const cef_browser_settings_t),
/// ///
// Explicitly close the developer tools window if one exists for this browser // Explicitly close the developer tools window if one exists for this browser
@ -1387,20 +1387,20 @@ pub struct cef_browser_host {
// function is only used when window rendering is disabled. // function is only used when window rendering is disabled.
/// ///
pub invalidate: extern "C" fn(browser_host: *mut cef_browser_host, pub invalidate: extern "C" fn(browser_host: *mut cef_browser_host,
dirtyRect: *cef_rect, t: cef_paint_element_type_t), dirtyRect: *const cef_rect, t: cef_paint_element_type_t),
/// ///
// Send a key event to the browser. // Send a key event to the browser.
/// ///
pub send_key_event: extern "C" fn(browser_host: *mut cef_browser_host, pub send_key_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_key_event), event: *const cef_key_event),
/// ///
// Send a mouse click event to the browser. The |x| and |y| coordinates are // Send a mouse click event to the browser. The |x| and |y| coordinates are
// relative to the upper-left corner of the view. // relative to the upper-left corner of the view.
/// ///
pub send_mouse_click_event: extern "C" fn(browser_host: *mut cef_browser_host, pub send_mouse_click_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, event: *const cef_mouse_event,
t: cef_mouse_button_type_t, t: cef_mouse_button_type_t,
mouseUp: c_int, clickCount: c_int), mouseUp: c_int, clickCount: c_int),
@ -1409,7 +1409,7 @@ pub struct cef_browser_host {
// relative to the upper-left corner of the view. // relative to the upper-left corner of the view.
/// ///
pub send_mouse_move_event: extern "C" fn(browser_host: *mut cef_browser_host, pub send_mouse_move_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, mouseLeave: c_int), event: *const cef_mouse_event, mouseLeave: c_int),
/// ///
// Send a mouse wheel event to the browser. The |x| and |y| coordinates are // Send a mouse wheel event to the browser. The |x| and |y| coordinates are
@ -1419,7 +1419,7 @@ pub struct cef_browser_host {
// cef_render_handler_t::GetScreenPoint should be implemented properly. // cef_render_handler_t::GetScreenPoint should be implemented properly.
/// ///
pub send_mouse_wheel_event: extern "C" fn(browser_host: *mut cef_browser_host, pub send_mouse_wheel_event: extern "C" fn(browser_host: *mut cef_browser_host,
event: *cef_mouse_event, deltaX: c_int, deltaY: c_int), event: *const cef_mouse_event, deltaX: c_int, deltaY: c_int),
/// ///
// Send a focus event to the browser. // Send a focus event to the browser.
@ -1550,7 +1550,7 @@ pub struct cef_browser {
/// ///
// Returns the frame with the specified name, or NULL if not found. // Returns the frame with the specified name, or NULL if not found.
/// ///
pub get_frame: extern "C" fn(browser: *mut cef_browser, name: *cef_string_t) -> *mut cef_frame, pub get_frame: extern "C" fn(browser: *mut cef_browser, name: *const cef_string_t) -> *mut cef_frame,
/// ///
// Returns the number of frames that currently exist. // Returns the number of frames that currently exist.
@ -1711,7 +1711,7 @@ pub struct cef_app {
// modify command-line arguments for non-browser processes as this may result // modify command-line arguments for non-browser processes as this may result
// in undefined behavior including crashes. // in undefined behavior including crashes.
/// ///
pub on_before_command_line_processing: extern "C" fn(app: *mut cef_app_t, process_type: *cef_string_t, command_line: *mut cef_command_line), pub on_before_command_line_processing: extern "C" fn(app: *mut cef_app_t, process_type: *const cef_string_t, command_line: *mut cef_command_line),
/// ///
// Provides an opportunity to register custom schemes. Do not keep a reference // Provides an opportunity to register custom schemes. Do not keep a reference
@ -1818,14 +1818,14 @@ pub struct cef_post_data_element {
/// ///
// The post data element will represent a file. // The post data element will represent a file.
/// ///
pub set_to_file: extern "C" fn(post_data_element: *mut cef_post_data_element, fileName: *cef_string_t), pub set_to_file: extern "C" fn(post_data_element: *mut cef_post_data_element, fileName: *const cef_string_t),
/// ///
// The post data element will represent bytes. The bytes passed in will be // The post data element will represent bytes. The bytes passed in will be
// copied. // copied.
/// ///
pub set_to_bytes: extern "C" fn(post_data_element: *mut cef_post_data_element, pub set_to_bytes: extern "C" fn(post_data_element: *mut cef_post_data_element,
size: size_t, bytes: *c_void), size: size_t, bytes: *const c_void),
/// ///
// Return the type of this post data element. // Return the type of this post data element.
@ -1877,7 +1877,7 @@ pub struct cef_post_data {
// Retrieve the post data elements. // Retrieve the post data elements.
/// ///
pub get_elements: extern "C" fn(post_data: *mut cef_post_data, pub get_elements: extern "C" fn(post_data: *mut cef_post_data,
elements_count: *mut size_t, elements: **mut cef_post_data_element), elements_count: *mut size_t, elements: *mut *mut cef_post_data_element),
/// ///
// Remove the specified post data element. Returns true (1) if the removal // Remove the specified post data element. Returns true (1) if the removal

View file

@ -86,7 +86,7 @@ impl ScaledFontExtensionMethods for ScaledFont {
let azure_pattern = pattern.azure_color_pattern; let azure_pattern = pattern.azure_color_pattern;
assert!(azure_pattern.is_not_null()); assert!(azure_pattern.is_not_null());
let options = struct__AzDrawOptions { let mut options = struct__AzDrawOptions {
mAlpha: 1f64 as AzFloat, mAlpha: 1f64 as AzFloat,
fields: 0x0200 as uint16_t fields: 0x0200 as uint16_t
}; };
@ -115,8 +115,8 @@ impl ScaledFontExtensionMethods for ScaledFont {
let azglyph_buf_len = azglyphs.len(); let azglyph_buf_len = azglyphs.len();
if azglyph_buf_len == 0 { return; } // Otherwise the Quartz backend will assert. if azglyph_buf_len == 0 { return; } // Otherwise the Quartz backend will assert.
let glyphbuf = struct__AzGlyphBuffer { let mut glyphbuf = struct__AzGlyphBuffer {
mGlyphs: azglyphs.as_ptr(), mGlyphs: azglyphs.as_mut_ptr(),
mNumGlyphs: azglyph_buf_len as uint32_t mNumGlyphs: azglyph_buf_len as uint32_t
}; };
@ -124,10 +124,10 @@ impl ScaledFontExtensionMethods for ScaledFont {
// TODO(Issue #64): this call needs to move into azure_hl.rs // TODO(Issue #64): this call needs to move into azure_hl.rs
AzDrawTargetFillGlyphs(target.azure_draw_target, AzDrawTargetFillGlyphs(target.azure_draw_target,
self.get_ref(), self.get_ref(),
&glyphbuf, &mut glyphbuf,
azure_pattern, azure_pattern,
&options, &mut options,
ptr::null()); ptr::mut_null());
} }
} }
} }

View file

@ -54,7 +54,7 @@ impl FontTableTagConversions for FontTableTag {
fn tag_to_str(&self) -> String { fn tag_to_str(&self) -> String {
unsafe { unsafe {
let reversed = str::raw::from_buf_len(mem::transmute(self), 4); let reversed = str::raw::from_buf_len(mem::transmute(self), 4);
return str::from_chars([reversed.as_slice().char_at(3), return String::from_chars([reversed.as_slice().char_at(3),
reversed.as_slice().char_at(2), reversed.as_slice().char_at(2),
reversed.as_slice().char_at(1), reversed.as_slice().char_at(1),
reversed.as_slice().char_at(0)]); reversed.as_slice().char_at(0)]);
@ -63,7 +63,7 @@ impl FontTableTagConversions for FontTableTag {
} }
pub trait FontTableMethods { pub trait FontTableMethods {
fn with_buffer(&self, |*u8, uint|); fn with_buffer(&self, |*const u8, uint|);
} }
#[deriving(Clone)] #[deriving(Clone)]

View file

@ -111,7 +111,7 @@ impl FontCache {
// TODO(Issue #188): look up localized font family names if canonical name not found // TODO(Issue #188): look up localized font family names if canonical name not found
// look up canonical name // look up canonical name
if self.local_families.contains_key(family_name) { if self.local_families.contains_key(family_name) {
debug!("FontList: Found font family with name={:s}", family_name.to_str()); debug!("FontList: Found font family with name={:s}", family_name.to_string());
let s = self.local_families.get_mut(family_name); let s = self.local_families.get_mut(family_name);
if s.templates.len() == 0 { if s.templates.len() == 0 {
@ -130,7 +130,7 @@ impl FontCache {
None None
} else { } else {
debug!("FontList: Couldn't find font family with name={:s}", family_name.to_str()); debug!("FontList: Couldn't find font family with name={:s}", family_name.to_string());
None None
} }
} }

View file

@ -2,12 +2,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#gfx:0.1"] #![crate_name = "gfx"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(globs, macro_rules, phase)] #![feature(globs, macro_rules, phase, unsafe_destructor)]
#![feature(phase)] #![feature(phase)]
#[phase(plugin, link)] #[phase(plugin, link)]

View file

@ -42,7 +42,7 @@ fn fixed_to_float_ft(f: i32) -> f64 {
pub struct FontTable; pub struct FontTable;
impl FontTableMethods for FontTable { impl FontTableMethods for FontTable {
fn with_buffer(&self, _blk: |*u8, uint|) { fn with_buffer(&self, _blk: |*const u8, uint|) {
fail!() fail!()
} }
} }
@ -93,10 +93,10 @@ impl FontHandleMethods for FontHandle {
Err(()) => Err(()) Err(()) => Err(())
}; };
fn create_face_from_buffer(lib: FT_Library, cbuf: *u8, cbuflen: uint, pt_size: Option<f64>) fn create_face_from_buffer(lib: FT_Library, cbuf: *const u8, cbuflen: uint, pt_size: Option<f64>)
-> Result<FT_Face, ()> { -> Result<FT_Face, ()> {
unsafe { unsafe {
let mut face: FT_Face = ptr::null(); let mut face: FT_Face = ptr::mut_null();
let face_index = 0 as FT_Long; let face_index = 0 as FT_Long;
let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long, let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long,
face_index, &mut face); face_index, &mut face);
@ -120,10 +120,10 @@ impl FontHandleMethods for FontHandle {
self.font_data.clone() self.font_data.clone()
} }
fn family_name(&self) -> String { fn family_name(&self) -> String {
unsafe { str::raw::from_c_str((*self.face).family_name) } unsafe { str::raw::from_c_str(&*(*self.face).family_name) }
} }
fn face_name(&self) -> String { fn face_name(&self) -> String {
unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } unsafe { str::raw::from_c_str(&*FT_Get_Postscript_Name(self.face)) }
} }
fn is_italic(&self) -> bool { fn is_italic(&self) -> bool {
unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC != 0 } unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC != 0 }
@ -134,7 +134,7 @@ impl FontHandleMethods for FontHandle {
default_weight default_weight
} else { } else {
unsafe { unsafe {
let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *TT_OS2; let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *mut TT_OS2;
let valid = os2.is_not_null() && (*os2).version != 0xffff; let valid = os2.is_not_null() && (*os2).version != 0xffff;
if valid { if valid {
let weight =(*os2).usWeightClass; let weight =(*os2).usWeightClass;
@ -226,7 +226,7 @@ impl FontHandleMethods for FontHandle {
let mut strikeout_offset = geometry::from_pt(0.0); let mut strikeout_offset = geometry::from_pt(0.0);
let mut x_height = geometry::from_pt(0.0); let mut x_height = geometry::from_pt(0.0);
unsafe { unsafe {
let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *TT_OS2; let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *mut TT_OS2;
let valid = os2.is_not_null() && (*os2).version != 0xffff; let valid = os2.is_not_null() && (*os2).version != 0xffff;
if valid { if valid {
strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as f64); strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as f64);
@ -270,9 +270,9 @@ impl<'a> FontHandle {
} }
} }
fn get_face_rec(&'a self) -> &'a FT_FaceRec { fn get_face_rec(&'a self) -> &'a mut FT_FaceRec {
unsafe { unsafe {
&(*self.face) &mut (*self.face)
} }
} }

View file

@ -17,23 +17,23 @@ use libc;
use libc::{c_void, c_long, size_t, malloc}; use libc::{c_void, c_long, size_t, malloc};
use std::mem; use std::mem;
extern fn ft_alloc(_mem: FT_Memory, size: c_long) -> *c_void { extern fn ft_alloc(_mem: FT_Memory, size: c_long) -> *mut c_void {
unsafe { unsafe {
let ptr = libc::malloc(size as size_t); let ptr = libc::malloc(size as size_t);
ptr as *c_void ptr as *mut c_void
} }
} }
extern fn ft_free(_mem: FT_Memory, block: *c_void) { extern fn ft_free(_mem: FT_Memory, block: *mut c_void) {
unsafe { unsafe {
libc::free(block as *mut c_void); libc::free(block);
} }
} }
extern fn ft_realloc(_mem: FT_Memory, _cur_size: c_long, new_size: c_long, block: *c_void) -> *c_void { extern fn ft_realloc(_mem: FT_Memory, _cur_size: c_long, new_size: c_long, block: *mut c_void) -> *mut c_void {
unsafe { unsafe {
let ptr = libc::realloc(block as *mut c_void, new_size as size_t); let ptr = libc::realloc(block, new_size as size_t);
ptr as *c_void ptr as *mut c_void
} }
} }
@ -61,15 +61,15 @@ impl FontContextHandle {
let ptr = libc::malloc(mem::size_of::<struct_FT_MemoryRec_>() as size_t); let ptr = libc::malloc(mem::size_of::<struct_FT_MemoryRec_>() as size_t);
let allocator: &mut struct_FT_MemoryRec_ = mem::transmute(ptr); let allocator: &mut struct_FT_MemoryRec_ = mem::transmute(ptr);
ptr::write(allocator, struct_FT_MemoryRec_ { ptr::write(allocator, struct_FT_MemoryRec_ {
user: ptr::null(), user: ptr::mut_null(),
alloc: ft_alloc, alloc: ft_alloc,
free: ft_free, free: ft_free,
realloc: ft_realloc, realloc: ft_realloc,
}); });
let ctx: FT_Library = ptr::null(); let mut ctx: FT_Library = ptr::mut_null();
let result = FT_New_Library(ptr as FT_Memory, &ctx); let result = FT_New_Library(ptr as FT_Memory, &mut ctx);
if !result.succeeded() { fail!("Unable to initialize FreeType library"); } if !result.succeeded() { fail!("Unable to initialize FreeType library"); }
FT_Add_Default_Modules(ctx); FT_Add_Default_Modules(ctx);

View file

@ -27,15 +27,15 @@ pub fn get_available_families(callback: |String|) {
let fontSet = FcConfigGetFonts(config, FcSetSystem); let fontSet = FcConfigGetFonts(config, FcSetSystem);
for i in range(0, (*fontSet).nfont as int) { for i in range(0, (*fontSet).nfont as int) {
let font = (*fontSet).fonts.offset(i); let font = (*fontSet).fonts.offset(i);
let family: *FcChar8 = ptr::null(); let mut family: *mut FcChar8 = ptr::mut_null();
let mut v: c_int = 0; let mut v: c_int = 0;
"family".to_c_str().with_ref(|FC_FAMILY| { let mut FC_FAMILY_C = "family".to_c_str();
while FcPatternGetString(*font, FC_FAMILY, v, &family) == FcResultMatch { let FC_FAMILY = FC_FAMILY_C.as_mut_ptr();
let family_name = str::raw::from_c_str(family as *c_char); while FcPatternGetString(*font, FC_FAMILY, v, &mut family) == FcResultMatch {
let family_name = str::raw::from_c_str(family as *const c_char);
callback(family_name); callback(family_name);
v += 1; v += 1;
} }
});
} }
} }
} }
@ -44,26 +44,26 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) {
debug!("getting variations for {}", family_name); debug!("getting variations for {}", family_name);
unsafe { unsafe {
let config = FcConfigGetCurrent(); let config = FcConfigGetCurrent();
let font_set = FcConfigGetFonts(config, FcSetSystem); let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &font_set; let font_set_array_ptr = &mut font_set;
let pattern = FcPatternCreate(); let pattern = FcPatternCreate();
assert!(pattern.is_not_null()); assert!(pattern.is_not_null());
"family".to_c_str().with_ref(|FC_FAMILY| { let mut FC_FAMILY_C = "family".to_c_str();
family_name.to_c_str().with_ref(|family_name| { let FC_FAMILY = FC_FAMILY_C.as_mut_ptr();
let ok = FcPatternAddString(pattern, FC_FAMILY, family_name as *FcChar8); let mut family_name_c = family_name.to_c_str();
let family_name = family_name_c.as_mut_ptr();
let ok = FcPatternAddString(pattern, FC_FAMILY, family_name as *mut FcChar8);
assert!(ok != 0); assert!(ok != 0);
});
});
let object_set = FcObjectSetCreate(); let object_set = FcObjectSetCreate();
assert!(object_set.is_not_null()); assert!(object_set.is_not_null());
"file".to_c_str().with_ref(|FC_FILE| { let mut FC_FILE_C = "file".to_c_str();
let FC_FILE = FC_FILE_C.as_mut_ptr();
FcObjectSetAdd(object_set, FC_FILE); FcObjectSetAdd(object_set, FC_FILE);
}); let mut FC_INDEX_C = "index".to_c_str();
"index".to_c_str().with_ref(|FC_INDEX| { let FC_INDEX = FC_INDEX_C.as_mut_ptr();
FcObjectSetAdd(object_set, FC_INDEX); FcObjectSetAdd(object_set, FC_INDEX);
});
let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set); let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set);
@ -71,22 +71,22 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) {
for i in range(0, (*matches).nfont as int) { for i in range(0, (*matches).nfont as int) {
let font = (*matches).fonts.offset(i); let font = (*matches).fonts.offset(i);
let file = "file".to_c_str().with_ref(|FC_FILE| { let mut FC_FILE_C = "file".to_c_str();
let file: *FcChar8 = ptr::null(); let FC_FILE = FC_FILE_C.as_mut_ptr();
if FcPatternGetString(*font, FC_FILE, 0, &file) == FcResultMatch { let mut file: *mut FcChar8 = ptr::mut_null();
str::raw::from_c_str(file as *libc::c_char) let file = if FcPatternGetString(*font, FC_FILE, 0, &mut file) == FcResultMatch {
str::raw::from_c_str(file as *const libc::c_char)
} else { } else {
fail!(); fail!();
} };
}); let mut FC_INDEX_C = "index".to_c_str();
let index = "index".to_c_str().with_ref(|FC_INDEX| { let FC_INDEX = FC_INDEX_C.as_mut_ptr();
let index: libc::c_int = 0; let mut index: libc::c_int = 0;
if FcPatternGetInteger(*font, FC_INDEX, 0, &index) == FcResultMatch { let index = if FcPatternGetInteger(*font, FC_INDEX, 0, &mut index) == FcResultMatch {
index index
} else { } else {
fail!(); fail!();
} };
});
debug!("variation file: {}", file); debug!("variation file: {}", file);
debug!("variation index: {}", index); debug!("variation index: {}", index);

View file

@ -42,7 +42,7 @@ fn fixed_to_float_ft(f: i32) -> f64 {
pub struct FontTable; pub struct FontTable;
impl FontTableMethods for FontTable { impl FontTableMethods for FontTable {
fn with_buffer(&self, _blk: |*u8, uint|) { fn with_buffer(&self, _blk: |*const u8, uint|) {
fail!() fail!()
} }
} }
@ -93,10 +93,10 @@ impl FontHandleMethods for FontHandle {
Err(()) => Err(()) Err(()) => Err(())
}; };
fn create_face_from_buffer(lib: FT_Library, cbuf: *u8, cbuflen: uint, pt_size: Option<f64>) fn create_face_from_buffer(lib: FT_Library, cbuf: *const u8, cbuflen: uint, pt_size: Option<f64>)
-> Result<FT_Face, ()> { -> Result<FT_Face, ()> {
unsafe { unsafe {
let mut face: FT_Face = ptr::null(); let mut face: FT_Face = ptr::mut_null();
let face_index = 0 as FT_Long; let face_index = 0 as FT_Long;
let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long, let result = FT_New_Memory_Face(lib, cbuf, cbuflen as FT_Long,
face_index, &mut face); face_index, &mut face);
@ -120,10 +120,10 @@ impl FontHandleMethods for FontHandle {
self.font_data.clone() self.font_data.clone()
} }
fn family_name(&self) -> String { fn family_name(&self) -> String {
unsafe { str::raw::from_c_str((*self.face).family_name) } unsafe { str::raw::from_c_str(&*(*self.face).family_name) }
} }
fn face_name(&self) -> String { fn face_name(&self) -> String {
unsafe { str::raw::from_c_str(FT_Get_Postscript_Name(self.face)) } unsafe { str::raw::from_c_str(&*FT_Get_Postscript_Name(self.face)) }
} }
fn is_italic(&self) -> bool { fn is_italic(&self) -> bool {
unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC != 0 } unsafe { (*self.face).style_flags & FT_STYLE_FLAG_ITALIC != 0 }
@ -134,7 +134,7 @@ impl FontHandleMethods for FontHandle {
default_weight default_weight
} else { } else {
unsafe { unsafe {
let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *TT_OS2; let os2 = FT_Get_Sfnt_Table(self.face, ft_sfnt_os2) as *mut TT_OS2;
let valid = os2.is_not_null() && (*os2).version != 0xffff; let valid = os2.is_not_null() && (*os2).version != 0xffff;
if valid { if valid {
let weight =(*os2).usWeightClass; let weight =(*os2).usWeightClass;
@ -174,9 +174,9 @@ impl FontHandleMethods for FontHandle {
fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId) fn glyph_h_kerning(&self, first_glyph: GlyphId, second_glyph: GlyphId)
-> FractionalPixel { -> FractionalPixel {
assert!(self.face.is_not_null()); assert!(self.face.is_not_null());
let delta = struct_FT_Vector_ { x: 0, y: 0 }; let mut delta = struct_FT_Vector_ { x: 0, y: 0 };
unsafe { unsafe {
FT_Get_Kerning(self.face, first_glyph, second_glyph, FT_KERNING_DEFAULT, &delta); FT_Get_Kerning(self.face, first_glyph, second_glyph, FT_KERNING_DEFAULT, &mut delta);
} }
fixed_to_float_ft(delta.x as i32) fixed_to_float_ft(delta.x as i32)
} }
@ -226,7 +226,7 @@ impl FontHandleMethods for FontHandle {
let mut strikeout_offset = geometry::from_pt(0.0); let mut strikeout_offset = geometry::from_pt(0.0);
let mut x_height = geometry::from_pt(0.0); let mut x_height = geometry::from_pt(0.0);
unsafe { unsafe {
let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *TT_OS2; let os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2) as *mut TT_OS2;
let valid = os2.is_not_null() && (*os2).version != 0xffff; let valid = os2.is_not_null() && (*os2).version != 0xffff;
if valid { if valid {
strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as f64); strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as f64);
@ -270,9 +270,9 @@ impl<'a> FontHandle {
} }
} }
fn get_face_rec(&'a self) -> &'a FT_FaceRec { fn get_face_rec(&'a self) -> &'a mut FT_FaceRec {
unsafe { unsafe {
&(*self.face) &mut (*self.face)
} }
} }

View file

@ -17,23 +17,23 @@ use libc;
use libc::{c_void, c_long, size_t, malloc}; use libc::{c_void, c_long, size_t, malloc};
use std::mem; use std::mem;
extern fn ft_alloc(_mem: FT_Memory, size: c_long) -> *c_void { extern fn ft_alloc(_mem: FT_Memory, size: c_long) -> *mut c_void {
unsafe { unsafe {
let ptr = libc::malloc(size as size_t); let ptr = libc::malloc(size as size_t);
ptr as *c_void ptr as *mut c_void
} }
} }
extern fn ft_free(_mem: FT_Memory, block: *c_void) { extern fn ft_free(_mem: FT_Memory, block: *mut c_void) {
unsafe { unsafe {
libc::free(block as *mut c_void); libc::free(block);
} }
} }
extern fn ft_realloc(_mem: FT_Memory, _cur_size: c_long, new_size: c_long, block: *c_void) -> *c_void { extern fn ft_realloc(_mem: FT_Memory, _cur_size: c_long, new_size: c_long, block: *mut c_void) -> *mut c_void {
unsafe { unsafe {
let ptr = libc::realloc(block as *mut c_void, new_size as size_t); let ptr = libc::realloc(block, new_size as size_t);
ptr as *c_void ptr as *mut c_void
} }
} }
@ -61,15 +61,15 @@ impl FontContextHandle {
let ptr = libc::malloc(mem::size_of::<struct_FT_MemoryRec_>() as size_t); let ptr = libc::malloc(mem::size_of::<struct_FT_MemoryRec_>() as size_t);
let allocator: &mut struct_FT_MemoryRec_ = mem::transmute(ptr); let allocator: &mut struct_FT_MemoryRec_ = mem::transmute(ptr);
ptr::write(allocator, struct_FT_MemoryRec_ { ptr::write(allocator, struct_FT_MemoryRec_ {
user: ptr::null(), user: ptr::mut_null(),
alloc: ft_alloc, alloc: ft_alloc,
free: ft_free, free: ft_free,
realloc: ft_realloc, realloc: ft_realloc,
}); });
let ctx: FT_Library = ptr::null(); let mut ctx: FT_Library = ptr::mut_null();
let result = FT_New_Library(ptr as FT_Memory, &ctx); let result = FT_New_Library(ptr as FT_Memory, &mut ctx);
if !result.succeeded() { fail!("Unable to initialize FreeType library"); } if !result.succeeded() { fail!("Unable to initialize FreeType library"); }
FT_Add_Default_Modules(ctx); FT_Add_Default_Modules(ctx);

View file

@ -27,15 +27,15 @@ pub fn get_available_families(callback: |String|) {
let fontSet = FcConfigGetFonts(config, FcSetSystem); let fontSet = FcConfigGetFonts(config, FcSetSystem);
for i in range(0, (*fontSet).nfont as int) { for i in range(0, (*fontSet).nfont as int) {
let font = (*fontSet).fonts.offset(i); let font = (*fontSet).fonts.offset(i);
let family: *FcChar8 = ptr::null(); let mut family: *mut FcChar8 = ptr::mut_null();
let mut v: c_int = 0; let mut v: c_int = 0;
"family".to_c_str().with_ref(|FC_FAMILY| { let mut FC_FAMILY_C = "family".to_c_str();
while FcPatternGetString(*font, FC_FAMILY, v, &family) == FcResultMatch { let FC_FAMILY = FC_FAMILY_C.as_mut_ptr();
let family_name = str::raw::from_c_str(family as *c_char); while FcPatternGetString(*font, FC_FAMILY, v, &mut family) == FcResultMatch {
let family_name = str::raw::from_c_str(family as *const c_char);
callback(family_name); callback(family_name);
v += 1; v += 1;
} }
});
} }
} }
} }
@ -44,26 +44,26 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) {
debug!("getting variations for {}", family_name); debug!("getting variations for {}", family_name);
unsafe { unsafe {
let config = FcConfigGetCurrent(); let config = FcConfigGetCurrent();
let font_set = FcConfigGetFonts(config, FcSetSystem); let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &font_set; let font_set_array_ptr = &mut font_set;
let pattern = FcPatternCreate(); let pattern = FcPatternCreate();
assert!(pattern.is_not_null()); assert!(pattern.is_not_null());
"family".to_c_str().with_ref(|FC_FAMILY| { let mut FC_FAMILY_C = "family".to_c_str();
family_name.to_c_str().with_ref(|family_name| { let FC_FAMILY = FC_FAMILY_C.as_mut_ptr();
let ok = FcPatternAddString(pattern, FC_FAMILY, family_name as *FcChar8); let mut family_name_c = family_name.to_c_str();
let family_name = family_name_c.as_mut_ptr();
let ok = FcPatternAddString(pattern, FC_FAMILY, family_name as *mut FcChar8);
assert!(ok != 0); assert!(ok != 0);
});
});
let object_set = FcObjectSetCreate(); let object_set = FcObjectSetCreate();
assert!(object_set.is_not_null()); assert!(object_set.is_not_null());
"file".to_c_str().with_ref(|FC_FILE| { let mut FC_FILE_C = "file".to_c_str();
let FC_FILE = FC_FILE_C.as_mut_ptr();
FcObjectSetAdd(object_set, FC_FILE); FcObjectSetAdd(object_set, FC_FILE);
}); let mut FC_INDEX_C = "index".to_c_str();
"index".to_c_str().with_ref(|FC_INDEX| { let FC_INDEX = FC_INDEX_C.as_mut_ptr();
FcObjectSetAdd(object_set, FC_INDEX); FcObjectSetAdd(object_set, FC_INDEX);
});
let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set); let matches = FcFontSetList(config, font_set_array_ptr, 1, pattern, object_set);
@ -71,22 +71,22 @@ pub fn get_variations_for_family(family_name: &str, callback: |String|) {
for i in range(0, (*matches).nfont as int) { for i in range(0, (*matches).nfont as int) {
let font = (*matches).fonts.offset(i); let font = (*matches).fonts.offset(i);
let file = "file".to_c_str().with_ref(|FC_FILE| { let mut FC_FILE_C = "file".to_c_str();
let file: *FcChar8 = ptr::null(); let FC_FILE = FC_FILE_C.as_mut_ptr();
if FcPatternGetString(*font, FC_FILE, 0, &file) == FcResultMatch { let mut file: *mut FcChar8 = ptr::mut_null();
str::raw::from_c_str(file as *libc::c_char) let file = if FcPatternGetString(*font, FC_FILE, 0, &mut file) == FcResultMatch {
str::raw::from_c_str(file as *const libc::c_char)
} else { } else {
fail!(); fail!();
} };
}); let mut FC_INDEX_C = "index".to_c_str();
let index = "index".to_c_str().with_ref(|FC_INDEX| { let FC_INDEX = FC_INDEX_C.as_mut_ptr();
let index: libc::c_int = 0; let mut index: libc::c_int = 0;
if FcPatternGetInteger(*font, FC_INDEX, 0, &index) == FcResultMatch { let index = if FcPatternGetInteger(*font, FC_INDEX, 0, &mut index) == FcResultMatch {
index index
} else { } else {
fail!(); fail!();
} };
});
debug!("variation file: {}", file); debug!("variation file: {}", file);
debug!("variation index: {}", index); debug!("variation index: {}", index);

View file

@ -46,7 +46,7 @@ impl FontTable {
} }
impl FontTableMethods for FontTable { impl FontTableMethods for FontTable {
fn with_buffer(&self, blk: |*u8, uint|) { fn with_buffer(&self, blk: |*const u8, uint|) {
blk(self.data.bytes().as_ptr(), self.data.len() as uint); blk(self.data.bytes().as_ptr(), self.data.len() as uint);
} }
} }
@ -108,11 +108,11 @@ impl FontHandleMethods for FontHandle {
fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
let characters: [UniChar, ..1] = [codepoint as UniChar]; let characters: [UniChar, ..1] = [codepoint as UniChar];
let glyphs: [CGGlyph, ..1] = [0 as CGGlyph]; let mut glyphs: [CGGlyph, ..1] = [0 as CGGlyph];
let count: CFIndex = 1; let count: CFIndex = 1;
let result = self.ctfont.get_glyphs_for_characters(&characters[0], let result = self.ctfont.get_glyphs_for_characters(&characters[0],
&glyphs[0], &mut glyphs[0],
count); count);
if !result { if !result {
@ -134,7 +134,7 @@ impl FontHandleMethods for FontHandle {
let glyphs = [glyph as CGGlyph]; let glyphs = [glyph as CGGlyph];
let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation,
&glyphs[0], &glyphs[0],
ptr::null(), ptr::mut_null(),
1); 1);
Some(advance as FractionalPixel) Some(advance as FractionalPixel)
} }

View file

@ -13,7 +13,7 @@ pub fn get_available_families(callback: |String|) {
for strref in family_names.iter() { for strref in family_names.iter() {
let family_name_ref: CFStringRef = unsafe { mem::transmute(strref) }; let family_name_ref: CFStringRef = unsafe { mem::transmute(strref) };
let family_name_cf: CFString = unsafe { TCFType::wrap_under_get_rule(family_name_ref) }; let family_name_cf: CFString = unsafe { TCFType::wrap_under_get_rule(family_name_ref) };
let family_name = family_name_cf.to_str(); let family_name = family_name_cf.to_string();
callback(family_name); callback(family_name);
} }
} }

View file

@ -110,9 +110,11 @@ impl<'a> RenderContext<'a> {
self.draw_target.make_current(); self.draw_target.make_current();
let draw_target_ref = &self.draw_target; let draw_target_ref = &self.draw_target;
let azure_surface = draw_target_ref.create_source_surface_from_data(image.pixels.as_slice(), size, let azure_surface = draw_target_ref.create_source_surface_from_data(image.pixels.as_slice(),
stride as i32, B8G8R8A8); size,
let source_rect = Rect(Point2D(0 as AzFloat, 0 as AzFloat), stride as i32,
B8G8R8A8);
let source_rect = Rect(Point2D(0u as AzFloat, 0u as AzFloat),
Size2D(image.width as AzFloat, image.height as AzFloat)); Size2D(image.width as AzFloat, image.height as AzFloat));
let dest_rect = bounds.to_azure_rect(); let dest_rect = bounds.to_azure_rect();
let draw_surface_options = DrawSurfaceOptions::new(Linear, true); let draw_surface_options = DrawSurfaceOptions::new(Linear, true);
@ -246,9 +248,9 @@ impl<'a> RenderContext<'a> {
color: Color, color: Color,
dash_size: DashSize) { dash_size: DashSize) {
let rect = bounds.to_azure_rect(); let rect = bounds.to_azure_rect();
let draw_opts = DrawOptions::new(1 as AzFloat, 0 as uint16_t); let draw_opts = DrawOptions::new(1u as AzFloat, 0 as uint16_t);
let mut stroke_opts = StrokeOptions::new(0 as AzFloat, 10 as AzFloat); let mut stroke_opts = StrokeOptions::new(0u as AzFloat, 10u as AzFloat);
let mut dash: [AzFloat, ..2] = [0 as AzFloat, 0 as AzFloat]; let mut dash: [AzFloat, ..2] = [0u as AzFloat, 0u as AzFloat];
stroke_opts.set_cap_style(AZ_CAP_BUTT as u8); stroke_opts.set_cap_style(AZ_CAP_BUTT as u8);
@ -262,7 +264,7 @@ impl<'a> RenderContext<'a> {
stroke_opts.line_width = border_width; stroke_opts.line_width = border_width;
dash[0] = border_width * (dash_size as int) as AzFloat; dash[0] = border_width * (dash_size as int) as AzFloat;
dash[1] = border_width * (dash_size as int) as AzFloat; dash[1] = border_width * (dash_size as int) as AzFloat;
stroke_opts.mDashPattern = dash.as_ptr(); stroke_opts.mDashPattern = dash.as_mut_ptr();
stroke_opts.mDashLength = dash.len() as size_t; stroke_opts.mDashLength = dash.len() as size_t;
let (start, end) = match direction { let (start, end) = match direction {

View file

@ -45,7 +45,7 @@ impl GlyphEntry {
let id_mask = id as u32; let id_mask = id as u32;
let Au(advance) = advance; let Au(advance) = advance;
let advance_mask = (advance as u32) << GLYPH_ADVANCE_SHIFT; let advance_mask = (advance as u32) << GLYPH_ADVANCE_SHIFT as uint;
GlyphEntry::new(id_mask | advance_mask | FLAG_IS_SIMPLE_GLYPH) GlyphEntry::new(id_mask | advance_mask | FLAG_IS_SIMPLE_GLYPH)
} }
@ -69,7 +69,7 @@ impl GlyphEntry {
if !starts_ligature { if !starts_ligature {
val |= FLAG_NOT_LIGATURE_GROUP_START; val |= FLAG_NOT_LIGATURE_GROUP_START;
} }
val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT; val |= (glyph_count as u32) << GLYPH_COUNT_SHIFT as uint;
GlyphEntry::new(val) GlyphEntry::new(val)
} }
@ -79,7 +79,7 @@ impl GlyphEntry {
fn missing(glyph_count: int) -> GlyphEntry { fn missing(glyph_count: int) -> GlyphEntry {
assert!(glyph_count <= u16::MAX as int); assert!(glyph_count <= u16::MAX as int);
GlyphEntry::new((glyph_count as u32) << GLYPH_COUNT_SHIFT) GlyphEntry::new((glyph_count as u32) << GLYPH_COUNT_SHIFT as uint)
} }
} }
@ -157,7 +157,7 @@ fn is_simple_glyph_id(id: GlyphId) -> bool {
fn is_simple_advance(advance: Au) -> bool { fn is_simple_advance(advance: Au) -> bool {
let unsignedAu = advance.to_u32().unwrap(); let unsignedAu = advance.to_u32().unwrap();
(unsignedAu & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT)) == unsignedAu (unsignedAu & (GLYPH_ADVANCE_MASK >> GLYPH_ADVANCE_SHIFT as uint)) == unsignedAu
} }
type DetailedGlyphCount = u16; type DetailedGlyphCount = u16;
@ -168,7 +168,7 @@ impl GlyphEntry {
// getter methods // getter methods
#[inline(always)] #[inline(always)]
fn advance(&self) -> Au { fn advance(&self) -> Au {
NumCast::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT).unwrap() NumCast::from((self.value & GLYPH_ADVANCE_MASK) >> GLYPH_ADVANCE_SHIFT as uint).unwrap()
} }
fn id(&self) -> GlyphId { fn id(&self) -> GlyphId {
@ -198,7 +198,7 @@ impl GlyphEntry {
} }
fn can_break_before(&self) -> BreakType { fn can_break_before(&self) -> BreakType {
let flag = ((self.value & FLAG_CAN_BREAK_MASK) >> FLAG_CAN_BREAK_SHIFT) as u8; let flag = ((self.value & FLAG_CAN_BREAK_MASK) >> FLAG_CAN_BREAK_SHIFT as uint) as u8;
break_flag_to_enum(flag) break_flag_to_enum(flag)
} }
@ -222,7 +222,7 @@ impl GlyphEntry {
#[inline(always)] #[inline(always)]
fn set_can_break_before(&self, e: BreakType) -> GlyphEntry { fn set_can_break_before(&self, e: BreakType) -> GlyphEntry {
let flag = (break_enum_to_flag(e) as u32) << FLAG_CAN_BREAK_SHIFT; let flag = (break_enum_to_flag(e) as u32) << FLAG_CAN_BREAK_SHIFT as uint;
GlyphEntry::new(self.value | flag) GlyphEntry::new(self.value | flag)
} }
@ -230,7 +230,7 @@ impl GlyphEntry {
fn glyph_count(&self) -> u16 { fn glyph_count(&self) -> u16 {
assert!(!self.is_simple()); assert!(!self.is_simple());
((self.value & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT) as u16 ((self.value & GLYPH_COUNT_MASK) >> GLYPH_COUNT_SHIFT as uint) as u16
} }
#[inline(always)] #[inline(always)]
@ -279,8 +279,8 @@ struct DetailedGlyphRecord {
} }
impl PartialOrd for DetailedGlyphRecord { impl PartialOrd for DetailedGlyphRecord {
fn lt(&self, other: &DetailedGlyphRecord) -> bool { fn partial_cmp(&self, other: &DetailedGlyphRecord) -> Option<Ordering> {
self.entry_offset < other.entry_offset self.entry_offset.partial_cmp(&other.entry_offset)
} }
} }

View file

@ -42,15 +42,15 @@ use servo_util::range::Range;
use std::mem; use std::mem;
use std::char; use std::char;
use std::cmp; use std::cmp;
use std::ptr::null; use std::ptr;
static NO_GLYPH: i32 = -1; static NO_GLYPH: i32 = -1;
static CONTINUATION_BYTE: i32 = -2; static CONTINUATION_BYTE: i32 = -2;
pub struct ShapedGlyphData { pub struct ShapedGlyphData {
count: int, count: int,
glyph_infos: *hb_glyph_info_t, glyph_infos: *mut hb_glyph_info_t,
pos_infos: *hb_glyph_position_t, pos_infos: *mut hb_glyph_position_t,
} }
pub struct ShapedGlyphEntry { pub struct ShapedGlyphEntry {
@ -60,14 +60,14 @@ pub struct ShapedGlyphEntry {
} }
impl ShapedGlyphData { impl ShapedGlyphData {
pub fn new(buffer: *hb_buffer_t) -> ShapedGlyphData { pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData {
unsafe { unsafe {
let glyph_count = 0; let mut glyph_count = 0;
let glyph_infos = hb_buffer_get_glyph_infos(buffer, &glyph_count); let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mut glyph_count);
let glyph_count = glyph_count as int; let glyph_count = glyph_count as int;
assert!(glyph_infos.is_not_null()); assert!(glyph_infos.is_not_null());
let pos_count = 0; let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &pos_count); let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
let pos_count = pos_count as int; let pos_count = pos_count as int;
assert!(pos_infos.is_not_null()); assert!(pos_infos.is_not_null());
assert!(glyph_count == pos_count); assert!(glyph_count == pos_count);
@ -132,9 +132,9 @@ impl ShapedGlyphData {
} }
pub struct Shaper { pub struct Shaper {
hb_face: *hb_face_t, hb_face: *mut hb_face_t,
hb_font: *hb_font_t, hb_font: *mut hb_font_t,
hb_funcs: *hb_font_funcs_t, hb_funcs: *mut hb_font_funcs_t,
} }
#[unsafe_destructor] #[unsafe_destructor]
@ -158,10 +158,10 @@ impl Shaper {
unsafe { unsafe {
// Indirection for Rust Issue #6248, dynamic freeze scope artifically extended // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended
let font_ptr = font as *mut Font; let font_ptr = font as *mut Font;
let hb_face: *hb_face_t = hb_face_create_for_tables(get_font_table_func, let hb_face: *mut hb_face_t = hb_face_create_for_tables(get_font_table_func,
font_ptr as *c_void, font_ptr as *mut c_void,
None); None);
let hb_font: *hb_font_t = hb_font_create(hb_face); let hb_font: *mut hb_font_t = hb_font_create(hb_face);
// Set points-per-em. if zero, performs no hinting in that direction. // Set points-per-em. if zero, performs no hinting in that direction.
let pt_size = font.pt_size; let pt_size = font.pt_size;
@ -174,11 +174,11 @@ impl Shaper {
// configure static function callbacks. // configure static function callbacks.
// NB. This funcs structure could be reused globally, as it never changes. // NB. This funcs structure could be reused globally, as it never changes.
let hb_funcs: *hb_font_funcs_t = hb_font_funcs_create(); let hb_funcs: *mut hb_font_funcs_t = hb_font_funcs_create();
hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, null(), None); hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, ptr::mut_null(), None);
hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, null(), None); hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, ptr::mut_null(), None);
hb_font_funcs_set_glyph_h_kerning_func(hb_funcs, glyph_h_kerning_func, null(), null()); hb_font_funcs_set_glyph_h_kerning_func(hb_funcs, glyph_h_kerning_func, ptr::mut_null(), ptr::mut_null());
hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *c_void, None); hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *mut c_void, None);
Shaper { Shaper {
hb_face: hb_face, hb_face: hb_face,
@ -202,17 +202,16 @@ impl ShaperMethods for Shaper {
/// font. /// font.
fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) { fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) {
unsafe { unsafe {
let hb_buffer: *hb_buffer_t = hb_buffer_create(); let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR); hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR);
// Using as_imm_buf because it never does a copy - we don't need the trailing null
hb_buffer_add_utf8(hb_buffer, hb_buffer_add_utf8(hb_buffer,
text.as_ptr() as *c_char, text.as_ptr() as *const c_char,
text.len() as c_int, text.len() as c_int,
0, 0,
text.len() as c_int); text.len() as c_int);
hb_shape(self.hb_font, hb_buffer, null(), 0); hb_shape(self.hb_font, hb_buffer, ptr::mut_null(), 0);
self.save_glyph_results(text, glyphs, hb_buffer); self.save_glyph_results(text, glyphs, hb_buffer);
hb_buffer_destroy(hb_buffer); hb_buffer_destroy(hb_buffer);
} }
@ -220,7 +219,7 @@ impl ShaperMethods for Shaper {
} }
impl Shaper { impl Shaper {
fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *hb_buffer_t) { fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *mut hb_buffer_t) {
let glyph_data = ShapedGlyphData::new(buffer); let glyph_data = ShapedGlyphData::new(buffer);
let glyph_count = glyph_data.len(); let glyph_count = glyph_data.len();
let byte_max = text.len() as int; let byte_max = text.len() as int;
@ -454,14 +453,14 @@ impl Shaper {
} }
/// Callbacks from Harfbuzz when font map and glyph advance lookup needed. /// Callbacks from Harfbuzz when font map and glyph advance lookup needed.
extern fn glyph_func(_: *hb_font_t, extern fn glyph_func(_: *mut hb_font_t,
font_data: *c_void, font_data: *mut c_void,
unicode: hb_codepoint_t, unicode: hb_codepoint_t,
_: hb_codepoint_t, _: hb_codepoint_t,
glyph: *mut hb_codepoint_t, glyph: *mut hb_codepoint_t,
_: *c_void) _: *mut c_void)
-> hb_bool_t { -> hb_bool_t {
let font: *Font = font_data as *Font; let font: *const Font = font_data as *const Font;
assert!(font.is_not_null()); assert!(font.is_not_null());
unsafe { unsafe {
@ -475,10 +474,10 @@ extern fn glyph_func(_: *hb_font_t,
} }
} }
extern fn glyph_h_advance_func(_: *hb_font_t, extern fn glyph_h_advance_func(_: *mut hb_font_t,
font_data: *c_void, font_data: *mut c_void,
glyph: hb_codepoint_t, glyph: hb_codepoint_t,
_: *c_void) _: *mut c_void)
-> hb_position_t { -> hb_position_t {
let font: *mut Font = font_data as *mut Font; let font: *mut Font = font_data as *mut Font;
assert!(font.is_not_null()); assert!(font.is_not_null());
@ -489,11 +488,11 @@ extern fn glyph_h_advance_func(_: *hb_font_t,
} }
} }
extern fn glyph_h_kerning_func(_: *hb_font_t, extern fn glyph_h_kerning_func(_: *mut hb_font_t,
font_data: *c_void, font_data: *mut c_void,
first_glyph: hb_codepoint_t, first_glyph: hb_codepoint_t,
second_glyph: hb_codepoint_t, second_glyph: hb_codepoint_t,
_: *c_void) _: *mut c_void)
-> hb_position_t { -> hb_position_t {
let font: *mut Font = font_data as *mut Font; let font: *mut Font = font_data as *mut Font;
assert!(font.is_not_null()); assert!(font.is_not_null());
@ -505,21 +504,21 @@ extern fn glyph_h_kerning_func(_: *hb_font_t,
} }
// Callback to get a font table out of a font. // Callback to get a font table out of a font.
extern fn get_font_table_func(_: *hb_face_t, tag: hb_tag_t, user_data: *c_void) -> *hb_blob_t { extern fn get_font_table_func(_: *mut hb_face_t, tag: hb_tag_t, user_data: *mut c_void) -> *mut hb_blob_t {
unsafe { unsafe {
let font: *Font = user_data as *Font; let font: *const Font = user_data as *const Font;
assert!(font.is_not_null()); assert!(font.is_not_null());
// TODO(Issue #197): reuse font table data, which will change the unsound trickery here. // TODO(Issue #197): reuse font table data, which will change the unsound trickery here.
match (*font).get_table_for_tag(tag as FontTableTag) { match (*font).get_table_for_tag(tag as FontTableTag) {
None => null(), None => ptr::mut_null(),
Some(ref font_table) => { Some(ref font_table) => {
let skinny_font_table_ptr: *FontTable = font_table; // private context let skinny_font_table_ptr: *const FontTable = font_table; // private context
let mut blob: *hb_blob_t = null(); let mut blob: *mut hb_blob_t = ptr::mut_null();
(*skinny_font_table_ptr).with_buffer(|buf: *u8, len: uint| { (*skinny_font_table_ptr).with_buffer(|buf: *const u8, len: uint| {
// HarfBuzz calls `destroy_blob_func` when the buffer is no longer needed. // HarfBuzz calls `destroy_blob_func` when the buffer is no longer needed.
blob = hb_blob_create(buf as *c_char, blob = hb_blob_create(buf as *const c_char,
len as c_uint, len as c_uint,
HB_MEMORY_MODE_READONLY, HB_MEMORY_MODE_READONLY,
mem::transmute(skinny_font_table_ptr), mem::transmute(skinny_font_table_ptr),
@ -537,6 +536,6 @@ extern fn get_font_table_func(_: *hb_face_t, tag: hb_tag_t, user_data: *c_void)
// In particular, we'll need to cast to a boxed, rather than owned, FontTable. // In particular, we'll need to cast to a boxed, rather than owned, FontTable.
// even better, should cache the harfbuzz blobs directly instead of recreating a lot. // even better, should cache the harfbuzz blobs directly instead of recreating a lot.
extern fn destroy_blob_func(_: *c_void) { extern fn destroy_blob_func(_: *mut c_void) {
// TODO: Previous code here was broken. Rewrite. // TODO: Previous code here was broken. Rewrite.
} }

View file

@ -110,19 +110,19 @@ pub fn transform_text(text: &str, mode: CompressionMode,
} }
pub fn float_to_fixed(before: int, f: f64) -> i32 { pub fn float_to_fixed(before: int, f: f64) -> i32 {
(1i32 << before) * (f as i32) (1i32 << before as uint) * (f as i32)
} }
pub fn fixed_to_float(before: int, f: i32) -> f64 { pub fn fixed_to_float(before: int, f: i32) -> f64 {
f as f64 * 1.0f64 / ((1i32 << before) as f64) f as f64 * 1.0f64 / ((1i32 << before as uint) as f64)
} }
pub fn fixed_to_rounded_int(before: int, f: i32) -> int { pub fn fixed_to_rounded_int(before: int, f: i32) -> int {
let half = 1i32 << (before-1); let half = 1i32 << (before-1) as uint;
if f > 0i32 { if f > 0i32 {
((half + f) >> before) as int ((half + f) >> before as uint) as int
} else { } else {
-((half - f) >> before) as int -((half - f) >> before as uint) as int
} }
} }

View file

@ -209,7 +209,7 @@ impl<'a> FlowConstructor<'a> {
fn font_context<'a>(&'a mut self) -> &'a mut FontContext { fn font_context<'a>(&'a mut self) -> &'a mut FontContext {
match self.font_context { match self.font_context {
Some(ref mut font_context) => { Some(ref mut font_context) => {
let font_context: &mut FontContext = *font_context; let font_context: &mut FontContext = &mut **font_context;
font_context font_context
} }
None => self.layout_context.font_context(), None => self.layout_context.font_context(),

View file

@ -73,7 +73,7 @@ pub struct LayoutContext {
/// The CSS selector stylist. /// The CSS selector stylist.
/// ///
/// FIXME(#2604): Make this no longer an unsafe pointer once we have fast `RWArc`s. /// FIXME(#2604): Make this no longer an unsafe pointer once we have fast `RWArc`s.
pub stylist: *Stylist, pub stylist: *const Stylist,
/// The root node at which we're starting the layout. /// The root node at which we're starting the layout.
pub reflow_root: OpaqueNode, pub reflow_root: OpaqueNode,

View file

@ -224,7 +224,7 @@ impl StyleSharingCandidate {
parent_style: parent_style.take_unwrap(), parent_style: parent_style.take_unwrap(),
local_name: element.get_local_name().clone(), local_name: element.get_local_name().clone(),
class: element.get_attr(&Null, "class") class: element.get_attr(&Null, "class")
.map(|string| string.to_str()), .map(|string| string.to_string()),
}) })
} }

View file

@ -63,7 +63,7 @@ use style::computed_values::{clear, position, text_align};
/// ///
/// Note that virtual methods have a cost; we should not overuse them in Servo. Consider adding /// Note that virtual methods have a cost; we should not overuse them in Servo. Consider adding
/// methods to `ImmutableFlowUtils` or `MutableFlowUtils` before adding more methods here. /// methods to `ImmutableFlowUtils` or `MutableFlowUtils` before adding more methods here.
pub trait Flow: fmt::Show + ToStr + Share { pub trait Flow: fmt::Show + ToString + Share {
// RTTI // RTTI
// //
// TODO(pcwalton): Use Rust's RTTI, once that works. // TODO(pcwalton): Use Rust's RTTI, once that works.
@ -486,13 +486,13 @@ impl FlowFlags {
#[inline] #[inline]
pub fn text_align(self) -> text_align::T { pub fn text_align(self) -> text_align::T {
let FlowFlags(ff) = self; let FlowFlags(ff) = self;
FromPrimitive::from_u8((ff & TEXT_ALIGN_BITMASK) >> TEXT_ALIGN_SHIFT).unwrap() FromPrimitive::from_u8((ff & TEXT_ALIGN_BITMASK) >> TEXT_ALIGN_SHIFT as uint).unwrap()
} }
#[inline] #[inline]
pub fn set_text_align(&mut self, value: text_align::T) { pub fn set_text_align(&mut self, value: text_align::T) {
let FlowFlags(ff) = *self; let FlowFlags(ff) = *self;
*self = FlowFlags((ff & !TEXT_ALIGN_BITMASK) | ((value as u8) << TEXT_ALIGN_SHIFT)) *self = FlowFlags((ff & !TEXT_ALIGN_BITMASK) | ((value as u8) << TEXT_ALIGN_SHIFT as uint))
} }
#[inline] #[inline]
@ -908,7 +908,7 @@ impl<'a> ImmutableFlowUtils for &'a Flow {
for _ in range(0, level) { for _ in range(0, level) {
indent.push_str("| ") indent.push_str("| ")
} }
debug!("{}+ {}", indent, self.to_str()); debug!("{}+ {}", indent, self.to_string());
for kid in imm_child_iter(self) { for kid in imm_child_iter(self) {
kid.dump_with_level(level + 1) kid.dump_with_level(level + 1)
} }

View file

@ -16,7 +16,7 @@ pub type Link = Option<FlowRef>;
#[allow(raw_pointer_deriving)] #[allow(raw_pointer_deriving)]
#[deriving(Clone)] #[deriving(Clone)]
pub struct Rawlink { pub struct Rawlink {
vtable: *(), vtable: *const (),
obj: *mut (), obj: *mut (),
} }

View file

@ -15,8 +15,8 @@ use std::sync::atomics::SeqCst;
#[unsafe_no_drop_flag] #[unsafe_no_drop_flag]
pub struct FlowRef { pub struct FlowRef {
vtable: *u8, vtable: *const u8,
ptr: *u8, ptr: *const u8,
} }
impl FlowRef { impl FlowRef {

View file

@ -392,7 +392,7 @@ impl Fragment {
/// Returns a debug ID of this fragment. This ID should not be considered stable across multiple /// Returns a debug ID of this fragment. This ID should not be considered stable across multiple
/// layouts or fragment manipulations. /// layouts or fragment manipulations.
pub fn debug_id(&self) -> uint { pub fn debug_id(&self) -> uint {
self as *Fragment as uint self as *const Fragment as uint
} }
/// Transforms this fragment into another fragment of the given type, with the given size, preserving all /// Transforms this fragment into another fragment of the given type, with the given size, preserving all

View file

@ -865,15 +865,20 @@ impl InlineFragments {
pub fn strip_ignorable_whitespace_from_start(&mut self) { pub fn strip_ignorable_whitespace_from_start(&mut self) {
if self.is_empty() { return }; // Fast path if self.is_empty() { return }; // Fast path
let new_fragments = mem::replace(&mut self.fragments, vec![]) // FIXME (rust#16151): This can be reverted back to using skip_while once
.move_iter() // the upstream bug is fixed.
.skip_while(|fragment| { let mut fragments = mem::replace(&mut self.fragments, vec![]).move_iter();
let is_whitespace_only = fragment.is_whitespace_only(); let mut new_fragments = Vec::new();
if is_whitespace_only { let mut skipping = true;
for fragment in fragments {
if skipping && fragment.is_whitespace_only() {
debug!("stripping ignorable whitespace from start"); debug!("stripping ignorable whitespace from start");
continue
}
skipping = false;
new_fragments.push(fragment);
} }
is_whitespace_only
}).collect();
self.fixup(new_fragments); self.fixup(new_fragments);
} }

View file

@ -2,15 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#layout:0.1"] #![crate_name = "layout"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"] #![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"] #![license = "MPL"]
#![feature(globs, macro_rules, phase, thread_local)] #![feature(globs, macro_rules, phase, thread_local, unsafe_destructor)]
#[phase(plugin, link)] #[phase(plugin, link)]
extern crate log; extern crate log;

View file

@ -53,12 +53,11 @@ use servo_util::opts::Opts;
use servo_util::smallvec::{SmallVec, SmallVec1}; use servo_util::smallvec::{SmallVec, SmallVec1};
use servo_util::time::{TimeProfilerChan, profile}; use servo_util::time::{TimeProfilerChan, profile};
use servo_util::time; use servo_util::time;
use servo_util::task::send_on_failure; use servo_util::task::spawn_named_with_send_on_failure;
use servo_util::workqueue::WorkQueue; use servo_util::workqueue::WorkQueue;
use std::comm::{channel, Sender, Receiver}; use std::comm::{channel, Sender, Receiver};
use std::mem; use std::mem;
use std::ptr; use std::ptr;
use std::task::TaskBuilder;
use style::{AuthorOrigin, Stylesheet, Stylist}; use style::{AuthorOrigin, Stylesheet, Stylist};
use sync::{Arc, Mutex}; use sync::{Arc, Mutex};
use url::Url; use url::Url;
@ -288,10 +287,8 @@ impl LayoutTaskFactory for LayoutTask {
opts: Opts, opts: Opts,
time_profiler_chan: TimeProfilerChan, time_profiler_chan: TimeProfilerChan,
shutdown_chan: Sender<()>) { shutdown_chan: Sender<()>) {
let mut builder = TaskBuilder::new().named("LayoutTask");
let ConstellationChan(con_chan) = constellation_chan.clone(); let ConstellationChan(con_chan) = constellation_chan.clone();
send_on_failure(&mut builder, FailureMsg(failure_msg), con_chan); spawn_named_with_send_on_failure("LayoutTask", proc() {
builder.spawn(proc() {
{ // Ensures layout task is destroyed before we send shutdown message { // Ensures layout task is destroyed before we send shutdown message
let mut layout = LayoutTask::new(id, let mut layout = LayoutTask::new(id,
port, port,
@ -306,7 +303,7 @@ impl LayoutTaskFactory for LayoutTask {
layout.start(); layout.start();
} }
shutdown_chan.send(()); shutdown_chan.send(());
}); }, FailureMsg(failure_msg), con_chan);
} }
} }

View file

@ -42,7 +42,7 @@ fn null_unsafe_flow() -> UnsafeFlow {
(0, 0) (0, 0)
} }
pub fn owned_flow_to_unsafe_flow(flow: *FlowRef) -> UnsafeFlow { pub fn owned_flow_to_unsafe_flow(flow: *const FlowRef) -> UnsafeFlow {
unsafe { unsafe {
mem::transmute_copy(&*flow) mem::transmute_copy(&*flow)
} }
@ -268,7 +268,7 @@ fn recalc_style_for_node(unsafe_layout_node: UnsafeLayoutNode,
} }
// Prepare for flow construction by counting the node's children and storing that count. // Prepare for flow construction by counting the node's children and storing that count.
let mut child_count = 0; let mut child_count = 0u;
for _ in node.children() { for _ in node.children() {
child_count += 1; child_count += 1;
} }
@ -320,7 +320,7 @@ fn construct_flows(mut unsafe_layout_node: UnsafeLayoutNode,
// Reset the count of children for the next traversal. // Reset the count of children for the next traversal.
// //
// FIXME(pcwalton): Use children().len() when the implementation of that is efficient. // FIXME(pcwalton): Use children().len() when the implementation of that is efficient.
let mut child_count = 0; let mut child_count = 0u;
for _ in node.children() { for _ in node.children() {
child_count += 1 child_count += 1
} }
@ -401,7 +401,7 @@ fn compute_absolute_position(unsafe_flow: UnsafeFlow,
// Count the number of absolutely-positioned children, so that we can subtract it from // Count the number of absolutely-positioned children, so that we can subtract it from
// from `children_and_absolute_descendant_count` to get the number of real children. // from `children_and_absolute_descendant_count` to get the number of real children.
let mut absolutely_positioned_child_count = 0; let mut absolutely_positioned_child_count = 0u;
for kid in flow::child_iter(flow.get_mut()) { for kid in flow::child_iter(flow.get_mut()) {
if kid.is_absolutely_positioned() { if kid.is_absolutely_positioned() {
absolutely_positioned_child_count += 1; absolutely_positioned_child_count += 1;

View file

@ -67,7 +67,7 @@ pub struct LayoutDataWrapper {
/// A trait that allows access to the layout data of a DOM node. /// A trait that allows access to the layout data of a DOM node.
pub trait LayoutDataAccess { pub trait LayoutDataAccess {
/// Borrows the layout data without checks. /// Borrows the layout data without checks.
unsafe fn borrow_layout_data_unchecked(&self) -> *Option<LayoutDataWrapper>; unsafe fn borrow_layout_data_unchecked(&self) -> *const Option<LayoutDataWrapper>;
/// Borrows the layout data immutably. Fails on a conflicting borrow. /// Borrows the layout data immutably. Fails on a conflicting borrow.
fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>>; fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>>;
/// Borrows the layout data mutably. Fails on a conflicting borrow. /// Borrows the layout data mutably. Fails on a conflicting borrow.
@ -76,7 +76,7 @@ pub trait LayoutDataAccess {
impl<'ln> LayoutDataAccess for LayoutNode<'ln> { impl<'ln> LayoutDataAccess for LayoutNode<'ln> {
#[inline(always)] #[inline(always)]
unsafe fn borrow_layout_data_unchecked(&self) -> *Option<LayoutDataWrapper> { unsafe fn borrow_layout_data_unchecked(&self) -> *const Option<LayoutDataWrapper> {
mem::transmute(self.get().layout_data.borrow_unchecked()) mem::transmute(self.get().layout_data.borrow_unchecked())
} }

View file

@ -2,9 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#layout_traits:0.1"] #![crate_name = "layout_traits"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"] #![comment = "The Servo Parallel Browser Project"]

View file

@ -2,10 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#macros:0.1"] #![crate_name = "macros"]
#![crate_type = "lib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![crate_type = "dylib"]
#![feature(macro_rules)] #![feature(macro_rules)]
@ -44,10 +42,10 @@ macro_rules! lazy_init(
impl Deref<$T> for $N { impl Deref<$T> for $N {
fn deref<'a>(&'a self) -> &'a $T { fn deref<'a>(&'a self) -> &'a $T {
unsafe { unsafe {
static mut s: *$T = 0 as *$T; static mut s: *const $T = 0 as *const $T;
static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT; static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT;
ONCE.doit(|| { ONCE.doit(|| {
s = ::std::mem::transmute::<Box<$T>, *$T>(box () ($e)); s = ::std::mem::transmute::<Box<$T>, *const $T>(box () ($e));
}); });
&*s &*s
} }

View file

@ -2,7 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo"] #![crate_name = "servo"]
#![comment = "The Servo Parallel Browser Project"] #![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"] #![license = "MPL"]
@ -52,7 +52,6 @@ use servo_util::opts;
#[cfg(not(test))] #[cfg(not(test))]
use url::{Url, UrlParser}; use url::{Url, UrlParser};
#[cfg(not(test))] #[cfg(not(test))]
use std::os; use std::os;
#[cfg(not(test), target_os="android")] #[cfg(not(test), target_os="android")]
@ -65,7 +64,7 @@ use rustrt::task::TaskOpts;
#[cfg(not(test), target_os="macos")] #[cfg(not(test), target_os="macos")]
#[start] #[start]
#[allow(dead_code)] #[allow(dead_code)]
fn start(argc: int, argv: **u8) -> int { fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, proc() { native::start(argc, argv, proc() {
opts::from_cmdline_args(os::args().as_slice()).map(run); opts::from_cmdline_args(os::args().as_slice()).map(run);
}) })
@ -74,12 +73,12 @@ fn start(argc: int, argv: **u8) -> int {
#[cfg(not(test), target_os="android")] #[cfg(not(test), target_os="android")]
#[no_mangle] #[no_mangle]
#[allow(dead_code)] #[allow(dead_code)]
pub extern "C" fn android_start(argc: int, argv: **u8) -> int { pub extern "C" fn android_start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, proc() { native::start(argc, argv, proc() {
let mut args: Vec<String> = vec!(); let mut args: Vec<String> = vec!();
for i in range(0u, argc as uint) { for i in range(0u, argc as uint) {
unsafe { unsafe {
args.push(str::raw::from_c_str(*argv.offset(i as int) as *i8)); args.push(str::raw::from_c_str(*argv.offset(i as int) as *const i8));
} }
} }

View file

@ -2,9 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#msg:0.1"] #![crate_name = "msg"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
extern crate azure; extern crate azure;

View file

@ -120,19 +120,19 @@ fn empty_invalid() {
#[test] #[test]
fn plain() { fn plain() {
assert_parse("data:,hello%20world", None, None, Some(bytes!("hello world").iter().map(|&x| x).collect())); assert_parse("data:,hello%20world", None, None, Some(b"hello world".iter().map(|&x| x).collect()));
} }
#[test] #[test]
fn plain_ct() { fn plain_ct() {
assert_parse("data:text/plain,hello", assert_parse("data:text/plain,hello",
Some(("text".to_string(), "plain".to_string())), None, Some(bytes!("hello").iter().map(|&x| x).collect())); Some(("text".to_string(), "plain".to_string())), None, Some(b"hello".iter().map(|&x| x).collect()));
} }
#[test] #[test]
fn plain_charset() { fn plain_charset() {
assert_parse("data:text/plain;charset=latin1,hello", assert_parse("data:text/plain;charset=latin1,hello",
Some(("text".to_string(), "plain".to_string())), Some("latin1".to_string()), Some(bytes!("hello").iter().map(|&x| x).collect())); Some(("text".to_string(), "plain".to_string())), Some("latin1".to_string()), Some(b"hello".iter().map(|&x| x).collect()));
} }
#[test] #[test]

View file

@ -97,7 +97,7 @@ fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
}; };
// Dump headers, but only do the iteration if info!() is enabled. // Dump headers, but only do the iteration if info!() is enabled.
info!("got HTTP response {:s}, headers:", response.status.to_str()); info!("got HTTP response {:s}, headers:", response.status.to_string());
info!("{:?}", info!("{:?}",
for header in response.headers.iter() { for header in response.headers.iter() {
info!(" - {:s}: {:s}", header.header_name(), header.header_value()); info!(" - {:s}: {:s}", header.header_name(), header.header_value());

View file

@ -695,7 +695,7 @@ mod tests {
// Wait until our mock resource task has sent the image to the image cache // Wait until our mock resource task has sent the image to the image cache
join_port.recv(); join_port.recv();
for _ in range(0,2) { for _ in range(0u32, 2u32) {
let (response_chan, response_port) = comm::channel(); let (response_chan, response_port) = comm::channel();
image_cache_task.send(GetImage(url.clone(), response_chan)); image_cache_task.send(GetImage(url.clone(), response_chan));
match response_port.recv() { match response_port.recv() {

View file

@ -2,9 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#net:0.1"] #![crate_name = "net"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(default_type_params, globs, managed_boxes, phase)] #![feature(default_type_params, globs, managed_boxes, phase)]

View file

@ -97,7 +97,8 @@ impl CallbackInterface {
pub fn GetCallableProperty(&self, cx: *mut JSContext, name: &str) -> Result<JSVal, ()> { pub fn GetCallableProperty(&self, cx: *mut JSContext, name: &str) -> Result<JSVal, ()> {
let mut callable = UndefinedValue(); let mut callable = UndefinedValue();
unsafe { unsafe {
if name.to_c_str().with_ref(|name| JS_GetProperty(cx, self.callback(), name, &mut callable)) == 0 { let name = name.to_c_str();
if JS_GetProperty(cx, self.callback(), name.as_ptr(), &mut callable) == 0 {
return Err(()); return Err(());
} }

View file

@ -374,7 +374,7 @@ class CGMethodCall(CGThing):
class FakeCastableDescriptor(): class FakeCastableDescriptor():
def __init__(self, descriptor): def __init__(self, descriptor):
self.nativeType = "*%s" % descriptor.concreteType self.nativeType = "*const %s" % descriptor.concreteType
self.name = descriptor.name self.name = descriptor.name
class FakeInterface: class FakeInterface:
def inheritanceDepth(self): def inheritanceDepth(self):
@ -1161,7 +1161,7 @@ class MethodDefiner(PropertyDefiner):
jitinfo = ("&%s_methodinfo" % m["name"]) jitinfo = ("&%s_methodinfo" % m["name"])
accessor = "genericMethod" accessor = "genericMethod"
else: else:
jitinfo = "0 as *JSJitInfo" jitinfo = "0 as *const JSJitInfo"
accessor = m.get("nativeName", m["name"]) accessor = m.get("nativeName", m["name"])
return (m["name"], accessor, jitinfo, m["length"], m["flags"]) return (m["name"], accessor, jitinfo, m["length"], m["flags"])
@ -1172,8 +1172,8 @@ class MethodDefiner(PropertyDefiner):
decls = ''.join([stringDecl(m) for m in array]) decls = ''.join([stringDecl(m) for m in array])
return decls + self.generatePrefableArray( return decls + self.generatePrefableArray(
array, name, array, name,
' JSFunctionSpec {name: &%s_name as *u8 as *libc::c_char, call: JSNativeWrapper {op: Some(%s), info: %s}, nargs: %s, flags: %s as u16, selfHostedName: 0 as *libc::c_char }', ' JSFunctionSpec {name: &%s_name as *const u8 as *const libc::c_char, call: JSNativeWrapper {op: Some(%s), info: %s}, nargs: %s, flags: %s as u16, selfHostedName: 0 as *const libc::c_char }',
' JSFunctionSpec {name: 0 as *libc::c_char, call: JSNativeWrapper {op: None, info: 0 as *JSJitInfo}, nargs: 0, flags: 0, selfHostedName: 0 as *libc::c_char }', ' JSFunctionSpec {name: 0 as *const libc::c_char, call: JSNativeWrapper {op: None, info: 0 as *const JSJitInfo}, nargs: 0, flags: 0, selfHostedName: 0 as *const libc::c_char }',
'JSFunctionSpec', 'JSFunctionSpec',
specData) specData)
@ -1206,13 +1206,13 @@ class AttrDefiner(PropertyDefiner):
accessor = "genericGetter" accessor = "genericGetter"
jitinfo = "&%s_getterinfo" % attr.identifier.name jitinfo = "&%s_getterinfo" % attr.identifier.name
return ("JSPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *JSJitInfo}" return ("JSPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *const JSJitInfo}"
% {"info" : jitinfo, % {"info" : jitinfo,
"native" : accessor}) "native" : accessor})
def setter(attr): def setter(attr):
if attr.readonly: if attr.readonly:
return "JSStrictPropertyOpWrapper {op: None, info: 0 as *JSJitInfo}" return "JSStrictPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo}"
if self.static: if self.static:
accessor = 'set_' + attr.identifier.name accessor = 'set_' + attr.identifier.name
@ -1224,7 +1224,7 @@ class AttrDefiner(PropertyDefiner):
accessor = "genericSetter" accessor = "genericSetter"
jitinfo = "&%s_setterinfo" % attr.identifier.name jitinfo = "&%s_setterinfo" % attr.identifier.name
return ("JSStrictPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *JSJitInfo}" return ("JSStrictPropertyOpWrapper {op: Some(%(native)s), info: %(info)s as *const JSJitInfo}"
% {"info" : jitinfo, % {"info" : jitinfo,
"native" : accessor}) "native" : accessor})
@ -1241,8 +1241,8 @@ class AttrDefiner(PropertyDefiner):
return decls + self.generatePrefableArray( return decls + self.generatePrefableArray(
array, name, array, name,
' JSPropertySpec { name: &%s_name as *u8 as *libc::c_char, tinyid: 0, flags: ((%s) & 0xFF) as u8, getter: %s, setter: %s }', ' JSPropertySpec { name: &%s_name as *const u8 as *const libc::c_char, tinyid: 0, flags: ((%s) & 0xFF) as u8, getter: %s, setter: %s }',
' JSPropertySpec { name: 0 as *libc::c_char, tinyid: 0, flags: 0, getter: JSPropertyOpWrapper {op: None, info: 0 as *JSJitInfo}, setter: JSStrictPropertyOpWrapper {op: None, info: 0 as *JSJitInfo} }', ' JSPropertySpec { name: 0 as *const libc::c_char, tinyid: 0, flags: 0, getter: JSPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo}, setter: JSStrictPropertyOpWrapper {op: None, info: 0 as *const JSJitInfo} }',
'JSPropertySpec', 'JSPropertySpec',
specData) specData)
@ -1413,8 +1413,8 @@ class CGDOMJSClass(CGThing):
static Class_name: [u8, ..%i] = %s; static Class_name: [u8, ..%i] = %s;
static Class: DOMJSClass = DOMJSClass { static Class: DOMJSClass = DOMJSClass {
base: js::Class { base: js::Class {
name: &Class_name as *u8 as *libc::c_char, name: &Class_name as *const u8 as *const libc::c_char,
flags: JSCLASS_IS_DOMJSCLASS | %s | (((%s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT), //JSCLASS_HAS_RESERVED_SLOTS(%s), flags: JSCLASS_IS_DOMJSCLASS | %s | (((%s) & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint), //JSCLASS_HAS_RESERVED_SLOTS(%s),
addProperty: Some(JS_PropertyStub), addProperty: Some(JS_PropertyStub),
delProperty: Some(JS_PropertyStub), delProperty: Some(JS_PropertyStub),
getProperty: Some(JS_PropertyStub), getProperty: Some(JS_PropertyStub),
@ -1430,48 +1430,48 @@ static Class: DOMJSClass = DOMJSClass {
trace: %s, trace: %s,
ext: js::ClassExtension { ext: js::ClassExtension {
equality: 0 as *u8, equality: 0 as *const u8,
outerObject: %s, outerObject: %s,
innerObject: None, innerObject: None,
iteratorObject: 0 as *u8, iteratorObject: 0 as *const u8,
unused: 0 as *u8, unused: 0 as *const u8,
isWrappedNative: 0 as *u8, isWrappedNative: 0 as *const u8,
}, },
ops: js::ObjectOps { ops: js::ObjectOps {
lookupGeneric: 0 as *u8, lookupGeneric: 0 as *const u8,
lookupProperty: 0 as *u8, lookupProperty: 0 as *const u8,
lookupElement: 0 as *u8, lookupElement: 0 as *const u8,
lookupSpecial: 0 as *u8, lookupSpecial: 0 as *const u8,
defineGeneric: 0 as *u8, defineGeneric: 0 as *const u8,
defineProperty: 0 as *u8, defineProperty: 0 as *const u8,
defineElement: 0 as *u8, defineElement: 0 as *const u8,
defineSpecial: 0 as *u8, defineSpecial: 0 as *const u8,
getGeneric: 0 as *u8, getGeneric: 0 as *const u8,
getProperty: 0 as *u8, getProperty: 0 as *const u8,
getElement: 0 as *u8, getElement: 0 as *const u8,
getElementIfPresent: 0 as *u8, getElementIfPresent: 0 as *const u8,
getSpecial: 0 as *u8, getSpecial: 0 as *const u8,
setGeneric: 0 as *u8, setGeneric: 0 as *const u8,
setProperty: 0 as *u8, setProperty: 0 as *const u8,
setElement: 0 as *u8, setElement: 0 as *const u8,
setSpecial: 0 as *u8, setSpecial: 0 as *const u8,
getGenericAttributes: 0 as *u8, getGenericAttributes: 0 as *const u8,
getPropertyAttributes: 0 as *u8, getPropertyAttributes: 0 as *const u8,
getElementAttributes: 0 as *u8, getElementAttributes: 0 as *const u8,
getSpecialAttributes: 0 as *u8, getSpecialAttributes: 0 as *const u8,
setGenericAttributes: 0 as *u8, setGenericAttributes: 0 as *const u8,
setPropertyAttributes: 0 as *u8, setPropertyAttributes: 0 as *const u8,
setElementAttributes: 0 as *u8, setElementAttributes: 0 as *const u8,
setSpecialAttributes: 0 as *u8, setSpecialAttributes: 0 as *const u8,
deleteProperty: 0 as *u8, deleteProperty: 0 as *const u8,
deleteElement: 0 as *u8, deleteElement: 0 as *const u8,
deleteSpecial: 0 as *u8, deleteSpecial: 0 as *const u8,
enumerate: 0 as *u8, enumerate: 0 as *const u8,
typeOf: 0 as *u8, typeOf: 0 as *const u8,
thisObject: %s, thisObject: %s,
clear: 0 as *u8, clear: 0 as *const u8,
}, },
}, },
dom_class: %s dom_class: %s
@ -1496,8 +1496,8 @@ class CGPrototypeJSClass(CGThing):
return """ return """
static PrototypeClassName__: [u8, ..%s] = %s; static PrototypeClassName__: [u8, ..%s] = %s;
static PrototypeClass: JSClass = JSClass { static PrototypeClass: JSClass = JSClass {
name: &PrototypeClassName__ as *u8 as *libc::c_char, name: &PrototypeClassName__ as *const u8 as *const libc::c_char,
flags: (1 & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT, //JSCLASS_HAS_RESERVED_SLOTS(1) flags: (1 & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT as uint, //JSCLASS_HAS_RESERVED_SLOTS(1)
addProperty: Some(JS_PropertyStub), addProperty: Some(JS_PropertyStub),
delProperty: Some(JS_PropertyStub), delProperty: Some(JS_PropertyStub),
getProperty: Some(JS_PropertyStub), getProperty: Some(JS_PropertyStub),
@ -1524,7 +1524,7 @@ class CGInterfaceObjectJSClass(CGThing):
def define(self): def define(self):
if True: if True:
return "" return ""
ctorname = "0 as *u8" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME ctorname = "0 as *const u8" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME
hasinstance = HASINSTANCE_HOOK_NAME hasinstance = HASINSTANCE_HOOK_NAME
return """ return """
static InterfaceObjectClass: JSClass = { static InterfaceObjectClass: JSClass = {
@ -1536,12 +1536,12 @@ static InterfaceObjectClass: JSClass = {
JS_EnumerateStub, JS_EnumerateStub,
JS_ResolveStub, JS_ResolveStub,
JS_ConvertStub, JS_ConvertStub,
0 as *u8, 0 as *const u8,
0 as *u8, 0 as *const u8,
%s, %s,
%s, %s,
%s, %s,
0 as *u8, 0 as *const u8,
JSCLASS_NO_INTERNAL_MEMBERS JSCLASS_NO_INTERNAL_MEMBERS
}; };
""" % (str_to_const_array("Function"), ctorname, hasinstance, ctorname) """ % (str_to_const_array("Function"), ctorname, hasinstance, ctorname)
@ -1766,7 +1766,7 @@ def CreateBindingJSObject(descriptor, parent=None):
assert not descriptor.createGlobal assert not descriptor.createGlobal
create += """ create += """
let handler = RegisterBindings::proxy_handlers[PrototypeList::proxies::%s as uint]; let handler = RegisterBindings::proxy_handlers[PrototypeList::proxies::%s as uint];
let mut private = PrivateValue(squirrel_away_unique(aObject) as *libc::c_void); let mut private = PrivateValue(squirrel_away_unique(aObject) as *const libc::c_void);
let obj = with_compartment(aCx, proto, || { let obj = with_compartment(aCx, proto, || {
NewProxyObject(aCx, handler, NewProxyObject(aCx, handler,
&private, &private,
@ -1778,15 +1778,15 @@ assert!(obj.is_not_null());
""" % (descriptor.name, parent) """ % (descriptor.name, parent)
else: else:
if descriptor.createGlobal: if descriptor.createGlobal:
create += "let obj = CreateDOMGlobal(aCx, &Class.base as *js::Class as *JSClass);\n" create += "let obj = CreateDOMGlobal(aCx, &Class.base as *const js::Class as *const JSClass);\n"
else: else:
create += ("let obj = with_compartment(aCx, proto, || {\n" create += ("let obj = with_compartment(aCx, proto, || {\n"
" JS_NewObject(aCx, &Class.base as *js::Class as *JSClass, proto, %s)\n" " JS_NewObject(aCx, &Class.base as *const js::Class as *const JSClass, &*proto, &*%s)\n"
"});\n" % parent) "});\n" % parent)
create += """assert!(obj.is_not_null()); create += """assert!(obj.is_not_null());
JS_SetReservedSlot(obj, DOM_OBJECT_SLOT as u32, JS_SetReservedSlot(obj, DOM_OBJECT_SLOT as u32,
PrivateValue(squirrel_away_unique(aObject) as *libc::c_void)); PrivateValue(squirrel_away_unique(aObject) as *const libc::c_void));
""" """
return create return create
@ -2049,7 +2049,7 @@ class CGDefineProxyHandler(CGAbstractMethod):
""" """
def __init__(self, descriptor): def __init__(self, descriptor):
assert descriptor.proxy assert descriptor.proxy
CGAbstractMethod.__init__(self, descriptor, 'DefineProxyHandler', '*libc::c_void', [], pub=True) CGAbstractMethod.__init__(self, descriptor, 'DefineProxyHandler', '*const libc::c_void', [], pub=True)
def define(self): def define(self):
return CGAbstractMethod.define(self) return CGAbstractMethod.define(self)
@ -2088,7 +2088,7 @@ let traps = ProxyTraps {
trace: Some(%s) trace: Some(%s)
}; };
CreateProxyHandler(&traps, &Class as *_ as *_) CreateProxyHandler(&traps, &Class as *const _ as *const _)
""" % (FINALIZE_HOOK_NAME, """ % (FINALIZE_HOOK_NAME,
TRACE_HOOK_NAME) TRACE_HOOK_NAME)
return CGGeneric(body) return CGGeneric(body)
@ -2440,8 +2440,8 @@ class CGGenericMethod(CGAbstractBindingMethod):
def generate_code(self): def generate_code(self):
return CGGeneric( return CGGeneric(
"let _info: *JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n" "let _info: *const JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n"
"return CallJitMethodOp(_info, cx, obj, this.unsafe_get() as *libc::c_void, argc, vp);") "return CallJitMethodOp(_info, cx, obj, this.unsafe_get() as *mut libc::c_void, argc, vp);")
class CGSpecializedMethod(CGAbstractExternMethod): class CGSpecializedMethod(CGAbstractExternMethod):
""" """
@ -2452,7 +2452,7 @@ class CGSpecializedMethod(CGAbstractExternMethod):
self.method = method self.method = method
name = method.identifier.name name = method.identifier.name
args = [Argument('*mut JSContext', 'cx'), Argument('JSHandleObject', '_obj'), args = [Argument('*mut JSContext', 'cx'), Argument('JSHandleObject', '_obj'),
Argument('*%s' % descriptor.concreteType, 'this'), Argument('*const %s' % descriptor.concreteType, 'this'),
Argument('libc::c_uint', 'argc'), Argument('*mut JSVal', 'vp')] Argument('libc::c_uint', 'argc'), Argument('*mut JSVal', 'vp')]
CGAbstractExternMethod.__init__(self, descriptor, name, 'JSBool', args) CGAbstractExternMethod.__init__(self, descriptor, name, 'JSBool', args)
@ -2504,8 +2504,8 @@ class CGGenericGetter(CGAbstractBindingMethod):
def generate_code(self): def generate_code(self):
return CGGeneric( return CGGeneric(
"let info: *JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n" "let info: *const JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n"
"return CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *libc::c_void, vp);\n") "return CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *mut libc::c_void, vp);\n")
class CGSpecializedGetter(CGAbstractExternMethod): class CGSpecializedGetter(CGAbstractExternMethod):
""" """
@ -2517,7 +2517,7 @@ class CGSpecializedGetter(CGAbstractExternMethod):
name = 'get_' + attr.identifier.name name = 'get_' + attr.identifier.name
args = [ Argument('*mut JSContext', 'cx'), args = [ Argument('*mut JSContext', 'cx'),
Argument('JSHandleObject', '_obj'), Argument('JSHandleObject', '_obj'),
Argument('*%s' % descriptor.concreteType, 'this'), Argument('*const %s' % descriptor.concreteType, 'this'),
Argument('*mut JSVal', 'vp') ] Argument('*mut JSVal', 'vp') ]
CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args) CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args)
@ -2579,8 +2579,8 @@ class CGGenericSetter(CGAbstractBindingMethod):
return CGGeneric( return CGGeneric(
"let mut undef = UndefinedValue();\n" "let mut undef = UndefinedValue();\n"
"let argv: *mut JSVal = if argc != 0 { JS_ARGV(cx, vp) } else { &mut undef as *mut JSVal };\n" "let argv: *mut JSVal = if argc != 0 { JS_ARGV(cx, vp) } else { &mut undef as *mut JSVal };\n"
"let info: *JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n" "let info: *const JSJitInfo = RUST_FUNCTION_VALUE_TO_JITINFO(JS_CALLEE(cx, vp));\n"
"if CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *libc::c_void, argv) == 0 {\n" "if CallJitPropertyOp(info, cx, obj, this.unsafe_get() as *mut libc::c_void, argv) == 0 {\n"
" return 0;\n" " return 0;\n"
"}\n" "}\n"
"*vp = UndefinedValue();\n" "*vp = UndefinedValue();\n"
@ -2596,7 +2596,7 @@ class CGSpecializedSetter(CGAbstractExternMethod):
name = 'set_' + attr.identifier.name name = 'set_' + attr.identifier.name
args = [ Argument('*mut JSContext', 'cx'), args = [ Argument('*mut JSContext', 'cx'),
Argument('JSHandleObject', '_obj'), Argument('JSHandleObject', '_obj'),
Argument('*%s' % descriptor.concreteType, 'this'), Argument('*const %s' % descriptor.concreteType, 'this'),
Argument('*mut JSVal', 'argv')] Argument('*mut JSVal', 'argv')]
CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args) CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args)
@ -2651,7 +2651,7 @@ class CGMemberJITInfo(CGThing):
failstr = "true" if infallible else "false" failstr = "true" if infallible else "false"
return ("\n" return ("\n"
"static %s: JSJitInfo = JSJitInfo {\n" "static %s: JSJitInfo = JSJitInfo {\n"
" op: %s as *u8,\n" " op: %s as *const u8,\n"
" protoID: %s,\n" " protoID: %s,\n"
" depth: %s,\n" " depth: %s,\n"
" isInfallible: %s, /* False in setters. */\n" " isInfallible: %s, /* False in setters. */\n"
@ -3535,14 +3535,14 @@ class CGProxyNamedSetter(CGProxySpecialOperation):
class CGProxyUnwrap(CGAbstractMethod): class CGProxyUnwrap(CGAbstractMethod):
def __init__(self, descriptor): def __init__(self, descriptor):
args = [Argument('*mut JSObject', 'obj')] args = [Argument('*mut JSObject', 'obj')]
CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", '*' + descriptor.concreteType, args, alwaysInline=True) CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy", '*const ' + descriptor.concreteType, args, alwaysInline=True)
def definition_body(self): def definition_body(self):
return CGGeneric("""/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) { return CGGeneric("""/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) {
obj = js::UnwrapObject(obj); obj = js::UnwrapObject(obj);
}*/ }*/
//MOZ_ASSERT(IsProxy(obj)); //MOZ_ASSERT(IsProxy(obj));
let box_ = GetProxyPrivate(obj).to_private() as *%s; let box_ = GetProxyPrivate(obj).to_private() as *const %s;
return box_;""" % self.descriptor.concreteType) return box_;""" % self.descriptor.concreteType)
class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod): class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
@ -3646,7 +3646,7 @@ class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod):
def __init__(self, descriptor): def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('*mut JSObject', 'proxy'), args = [Argument('*mut JSContext', 'cx'), Argument('*mut JSObject', 'proxy'),
Argument('jsid', 'id'), Argument('jsid', 'id'),
Argument('*JSPropertyDescriptor', 'desc')] Argument('*const JSPropertyDescriptor', 'desc')]
CGAbstractExternMethod.__init__(self, descriptor, "defineProperty", "JSBool", args) CGAbstractExternMethod.__init__(self, descriptor, "defineProperty", "JSBool", args)
self.descriptor = descriptor self.descriptor = descriptor
def getBody(self): def getBody(self):
@ -3850,9 +3850,8 @@ class CGDOMJSProxyHandler_obj_toString(CGAbstractExternMethod):
JSString* jsresult; JSString* jsresult;
return xpc_qsStringToJsstring(cx, result, &jsresult) ? jsresult : NULL;""" return xpc_qsStringToJsstring(cx, result, &jsresult) ? jsresult : NULL;"""
return """"%s".to_c_str().with_ref(|s| { return """let s = "%s".to_c_str();
_obj_toString(cx, s) _obj_toString(cx, s.as_ptr())""" % self.descriptor.name
})""" % self.descriptor.name
def definition_body(self): def definition_body(self):
return CGGeneric(self.getBody()) return CGGeneric(self.getBody())
@ -3868,7 +3867,7 @@ class CGAbstractClassHook(CGAbstractExternMethod):
def definition_body_prologue(self): def definition_body_prologue(self):
return CGGeneric("""\ return CGGeneric("""\
let this: *%s = unwrap::<%s>(obj); let this: *const %s = unwrap::<%s>(obj);
""" % (self.descriptor.concreteType, self.descriptor.concreteType)) """ % (self.descriptor.concreteType, self.descriptor.concreteType))
def definition_body(self): def definition_body(self):
@ -4400,7 +4399,7 @@ class CGRegisterProxyHandlers(CGThing):
descriptors = config.getDescriptors(proxy=True) descriptors = config.getDescriptors(proxy=True)
length = len(descriptors) length = len(descriptors)
self.root = CGList([ self.root = CGList([
CGGeneric("pub static mut proxy_handlers: [*libc::c_void, ..%d] = [0 as *libc::c_void, ..%d];" % (length, length)), CGGeneric("pub static mut proxy_handlers: [*const libc::c_void, ..%d] = [0 as *const libc::c_void, ..%d];" % (length, length)),
CGRegisterProxyHandlersMethod(descriptors), CGRegisterProxyHandlersMethod(descriptors),
], "\n") ], "\n")

View file

@ -227,7 +227,7 @@ impl FromJSValConvertible<()> for f64 {
impl ToJSValConvertible for DOMString { impl ToJSValConvertible for DOMString {
fn to_jsval(&self, cx: *mut JSContext) -> JSVal { fn to_jsval(&self, cx: *mut JSContext) -> JSVal {
unsafe { unsafe {
let string_utf16 = self.to_utf16(); let string_utf16: Vec<u16> = self.as_slice().utf16_units().collect();
let jsstr = JS_NewUCStringCopyN(cx, string_utf16.as_ptr(), string_utf16.len() as libc::size_t); let jsstr = JS_NewUCStringCopyN(cx, string_utf16.as_ptr(), string_utf16.len() as libc::size_t);
if jsstr.is_null() { if jsstr.is_null() {
fail!("JS_NewUCStringCopyN failed"); fail!("JS_NewUCStringCopyN failed");
@ -272,7 +272,7 @@ impl ToJSValConvertible for ByteString {
fn to_jsval(&self, cx: *mut JSContext) -> JSVal { fn to_jsval(&self, cx: *mut JSContext) -> JSVal {
unsafe { unsafe {
let slice = self.as_slice(); let slice = self.as_slice();
let jsstr = JS_NewStringCopyN(cx, slice.as_ptr() as *libc::c_char, let jsstr = JS_NewStringCopyN(cx, slice.as_ptr() as *const libc::c_char,
slice.len() as libc::size_t); slice.len() as libc::size_t);
if jsstr.is_null() { if jsstr.is_null() {
fail!("JS_NewStringCopyN failed"); fail!("JS_NewStringCopyN failed");

View file

@ -91,24 +91,24 @@ static ERROR_FORMAT_STRING_STRING: [libc::c_char, ..4] = [
/// Format string struct used to throw `TypeError`s. /// Format string struct used to throw `TypeError`s.
static ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString { static ERROR_FORMAT_STRING: JSErrorFormatString = JSErrorFormatString {
format: &ERROR_FORMAT_STRING_STRING as *libc::c_char, format: &ERROR_FORMAT_STRING_STRING as *const libc::c_char,
argCount: 1, argCount: 1,
exnType: JSEXN_TYPEERR as i16, exnType: JSEXN_TYPEERR as i16,
}; };
/// Callback used to throw `TypeError`s. /// Callback used to throw `TypeError`s.
extern fn get_error_message(_user_ref: *mut libc::c_void, extern fn get_error_message(_user_ref: *mut libc::c_void,
_locale: *libc::c_char, _locale: *const libc::c_char,
error_number: libc::c_uint) -> *JSErrorFormatString error_number: libc::c_uint) -> *const JSErrorFormatString
{ {
assert_eq!(error_number, 0); assert_eq!(error_number, 0);
&ERROR_FORMAT_STRING as *JSErrorFormatString &ERROR_FORMAT_STRING as *const JSErrorFormatString
} }
/// Throw a `TypeError` with the given message. /// Throw a `TypeError` with the given message.
pub fn throw_type_error(cx: *mut JSContext, error: &str) { pub fn throw_type_error(cx: *mut JSContext, error: &str) {
let error = error.to_c_str(); let error = error.to_c_str();
error.with_ref(|error| unsafe { unsafe {
JS_ReportErrorNumber(cx, Some(get_error_message), ptr::mut_null(), 0, error); JS_ReportErrorNumber(cx, Some(get_error_message), ptr::mut_null(), 0, error.as_ptr());
}); }
} }

View file

@ -106,7 +106,7 @@ impl<T: Reflectable> Temporary<T> {
/// A rooted, JS-owned value. Must only be used as a field in other JS-owned types. /// A rooted, JS-owned value. Must only be used as a field in other JS-owned types.
pub struct JS<T> { pub struct JS<T> {
ptr: *T ptr: *const T
} }
impl<T> PartialEq for JS<T> { impl<T> PartialEq for JS<T> {
@ -129,7 +129,7 @@ impl JS<Node> {
pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> JS<Node> { pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> JS<Node> {
let TrustedNodeAddress(addr) = inner; let TrustedNodeAddress(addr) = inner;
JS { JS {
ptr: addr as *Node ptr: addr as *const Node
} }
} }
} }
@ -138,14 +138,14 @@ impl JS<XMLHttpRequest> {
pub unsafe fn from_trusted_xhr_address(inner: TrustedXHRAddress) -> JS<XMLHttpRequest> { pub unsafe fn from_trusted_xhr_address(inner: TrustedXHRAddress) -> JS<XMLHttpRequest> {
let TrustedXHRAddress(addr) = inner; let TrustedXHRAddress(addr) = inner;
JS { JS {
ptr: addr as *XMLHttpRequest ptr: addr as *const XMLHttpRequest
} }
} }
} }
impl<T: Reflectable> JS<T> { impl<T: Reflectable> JS<T> {
/// Create a new JS-owned value wrapped from a raw Rust pointer. /// Create a new JS-owned value wrapped from a raw Rust pointer.
pub unsafe fn from_raw(raw: *T) -> JS<T> { pub unsafe fn from_raw(raw: *const T) -> JS<T> {
JS { JS {
ptr: raw ptr: raw
} }
@ -442,7 +442,7 @@ impl<'a, T: Reflectable> Deref<T> for JSRef<'a, T> {
/// Encapsulates a reference to something that is guaranteed to be alive. This is freely copyable. /// Encapsulates a reference to something that is guaranteed to be alive. This is freely copyable.
pub struct JSRef<'a, T> { pub struct JSRef<'a, T> {
ptr: *T, ptr: *const T,
chain: ContravariantLifetime<'a>, chain: ContravariantLifetime<'a>,
} }

View file

@ -49,13 +49,13 @@ pub extern fn getPropertyDescriptor(cx: *mut JSContext, proxy: *mut JSObject, id
} }
pub fn defineProperty_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, pub fn defineProperty_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
desc: *JSPropertyDescriptor) -> JSBool { desc: *mut JSPropertyDescriptor) -> JSBool {
static JSMSG_GETTER_ONLY: libc::c_uint = 160; static JSMSG_GETTER_ONLY: libc::c_uint = 160;
unsafe { unsafe {
//FIXME: Workaround for https://github.com/mozilla/rust/issues/13385 //FIXME: Workaround for https://github.com/mozilla/rust/issues/13385
let setter: *libc::c_void = mem::transmute((*desc).setter); let setter: *const libc::c_void = mem::transmute((*desc).setter);
let setter_stub: *libc::c_void = mem::transmute(JS_StrictPropertyStub); let setter_stub: *const libc::c_void = mem::transmute(JS_StrictPropertyStub);
if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub { if ((*desc).attrs & JSPROP_GETTER) != 0 && setter == setter_stub {
return JS_ReportErrorFlagsAndNumber(cx, return JS_ReportErrorFlagsAndNumber(cx,
JSREPORT_WARNING | JSREPORT_STRICT | JSREPORT_WARNING | JSREPORT_STRICT |
@ -75,7 +75,7 @@ pub fn defineProperty_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
} }
pub extern fn defineProperty(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, pub extern fn defineProperty(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
desc: *JSPropertyDescriptor) -> JSBool { desc: *mut JSPropertyDescriptor) -> JSBool {
defineProperty_(cx, proxy, id, desc) defineProperty_(cx, proxy, id, desc)
} }
@ -97,7 +97,7 @@ pub extern fn delete_(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
} }
} }
pub fn _obj_toString(cx: *mut JSContext, className: *libc::c_char) -> *mut JSString { pub fn _obj_toString(cx: *mut JSContext, className: *const libc::c_char) -> *mut JSString {
unsafe { unsafe {
let name = str::raw::from_c_str(className); let name = str::raw::from_c_str(className);
let nchars = "[object ]".len() + name.len(); let nchars = "[object ]".len() + name.len();
@ -137,7 +137,7 @@ pub fn EnsureExpandoObject(cx: *mut JSContext, obj: *mut JSObject) -> *mut JSObj
assert!(is_dom_proxy(obj)); assert!(is_dom_proxy(obj));
let mut expando = GetExpandoObject(obj); let mut expando = GetExpandoObject(obj);
if expando.is_null() { if expando.is_null() {
expando = JS_NewObjectWithGivenProto(cx, ptr::null(), expando = JS_NewObjectWithGivenProto(cx, ptr::mut_null(),
ptr::mut_null(), ptr::mut_null(),
GetObjectParent(obj)); GetObjectParent(obj));
if expando.is_null() { if expando.is_null() {

View file

@ -73,13 +73,12 @@ pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
} }
unsafe { unsafe {
description.to_c_str().with_ref(|name| { let name = description.to_c_str();
(*tracer).debugPrinter = None; (*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1; (*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name as *libc::c_void; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing value {:s}", description); debug!("tracing value {:s}", description);
JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind()); JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
});
} }
} }
@ -91,13 +90,12 @@ pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Ref
/// Trace a `JSObject`. /// Trace a `JSObject`.
pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) { pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
unsafe { unsafe {
description.to_c_str().with_ref(|name| { let name = description.to_c_str();
(*tracer).debugPrinter = None; (*tracer).debugPrinter = None;
(*tracer).debugPrintIndex = -1; (*tracer).debugPrintIndex = -1;
(*tracer).debugPrintArg = name as *libc::c_void; (*tracer).debugPrintArg = name.as_ptr() as *const libc::c_void;
debug!("tracing {:s}", description); debug!("tracing {:s}", description);
JS_CallTracer(tracer, obj as *mut libc::c_void, JSTRACE_OBJECT); JS_CallTracer(tracer, obj as *mut libc::c_void, JSTRACE_OBJECT);
});
} }
} }
@ -185,23 +183,3 @@ impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<JSVal> {
Ok(()) Ok(())
} }
} }
/// for a field which contains DOMType
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for Cell<JS<T>> {
fn encode(&self, s: &mut S) -> Result<(), E> {
self.get().encode(s)
}
}
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for Cell<Option<JS<T>>> {
fn encode(&self, s: &mut S) -> Result<(), E> {
self.get().encode(s)
}
}
/// for a field which contains non-POD type contains DOMType
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for RefCell<Vec<JS<T>>> {
fn encode(&self, s: &mut S) -> Result<(), E> {
self.borrow().encode(s)
}
}

View file

@ -20,9 +20,7 @@ use std::cell::Cell;
use std::mem; use std::mem;
use std::cmp::PartialEq; use std::cmp::PartialEq;
use std::ptr; use std::ptr;
use std::ptr::null;
use std::slice; use std::slice;
use std::str;
use js::glue::{js_IsObjectProxyClass, js_IsFunctionProxyClass, IsProxyHandlerFamily}; use js::glue::{js_IsObjectProxyClass, js_IsFunctionProxyClass, IsProxyHandlerFamily};
use js::glue::{GetGlobalForObjectCrossCompartment, UnwrapObject, GetProxyHandlerExtra}; use js::glue::{GetGlobalForObjectCrossCompartment, UnwrapObject, GetProxyHandlerExtra};
use js::glue::{IsWrapper, RUST_JSID_TO_STRING, RUST_JSID_IS_INT}; use js::glue::{IsWrapper, RUST_JSID_TO_STRING, RUST_JSID_IS_INT};
@ -54,7 +52,7 @@ use js;
#[allow(raw_pointer_deriving)] #[allow(raw_pointer_deriving)]
#[deriving(Encodable)] #[deriving(Encodable)]
pub struct GlobalStaticData { pub struct GlobalStaticData {
pub windowproxy_handler: Untraceable<*libc::c_void>, pub windowproxy_handler: Untraceable<*const libc::c_void>,
} }
pub fn GlobalStaticData() -> GlobalStaticData { pub fn GlobalStaticData() -> GlobalStaticData {
@ -64,7 +62,7 @@ pub fn GlobalStaticData() -> GlobalStaticData {
} }
/// Returns whether the given `clasp` is one for a DOM object. /// Returns whether the given `clasp` is one for a DOM object.
fn is_dom_class(clasp: *JSClass) -> bool { fn is_dom_class(clasp: *const JSClass) -> bool {
unsafe { unsafe {
((*clasp).flags & js::JSCLASS_IS_DOMJSCLASS) != 0 ((*clasp).flags & js::JSCLASS_IS_DOMJSCLASS) != 0
} }
@ -84,7 +82,7 @@ pub fn is_dom_proxy(obj: *mut JSObject) -> bool {
/// Fails if `obj` is not a DOM object. /// Fails if `obj` is not a DOM object.
pub unsafe fn dom_object_slot(obj: *mut JSObject) -> u32 { pub unsafe fn dom_object_slot(obj: *mut JSObject) -> u32 {
let clasp = JS_GetClass(obj); let clasp = JS_GetClass(obj);
if is_dom_class(clasp) { if is_dom_class(&*clasp) {
DOM_OBJECT_SLOT as u32 DOM_OBJECT_SLOT as u32
} else { } else {
assert!(is_dom_proxy(obj)); assert!(is_dom_proxy(obj));
@ -93,23 +91,23 @@ pub unsafe fn dom_object_slot(obj: *mut JSObject) -> u32 {
} }
/// Get the DOM object from the given reflector. /// Get the DOM object from the given reflector.
pub unsafe fn unwrap<T>(obj: *mut JSObject) -> *T { pub unsafe fn unwrap<T>(obj: *mut JSObject) -> *const T {
let slot = dom_object_slot(obj); let slot = dom_object_slot(obj);
let val = JS_GetReservedSlot(obj, slot); let val = JS_GetReservedSlot(obj, slot);
val.to_private() as *T val.to_private() as *const T
} }
/// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object. /// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object.
pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<DOMClass, ()> { pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<DOMClass, ()> {
let clasp = JS_GetClass(obj); let clasp = JS_GetClass(obj);
if is_dom_class(clasp) { if is_dom_class(&*clasp) {
debug!("plain old dom object"); debug!("plain old dom object");
let domjsclass: *DOMJSClass = clasp as *DOMJSClass; let domjsclass: *const DOMJSClass = clasp as *const DOMJSClass;
return Ok((*domjsclass).dom_class); return Ok((*domjsclass).dom_class);
} }
if is_dom_proxy(obj) { if is_dom_proxy(obj) {
debug!("proxy dom object"); debug!("proxy dom object");
let dom_class: *DOMClass = GetProxyHandlerExtra(obj) as *DOMClass; let dom_class: *const DOMClass = GetProxyHandlerExtra(obj) as *const DOMClass;
return Ok(*dom_class); return Ok(*dom_class);
} }
debug!("not a dom object"); debug!("not a dom object");
@ -129,7 +127,7 @@ pub fn unwrap_jsmanaged<T: Reflectable>(mut obj: *mut JSObject,
let dom_class = get_dom_class(obj).or_else(|_| { let dom_class = get_dom_class(obj).or_else(|_| {
if IsWrapper(obj) == 1 { if IsWrapper(obj) == 1 {
debug!("found wrapper"); debug!("found wrapper");
obj = UnwrapObject(obj, /* stopAtOuter = */ 0, ptr::null()); obj = UnwrapObject(obj, /* stopAtOuter = */ 0, ptr::mut_null());
if obj.is_null() { if obj.is_null() {
debug!("unwrapping security wrapper failed"); debug!("unwrapping security wrapper failed");
Err(()) Err(())
@ -157,7 +155,7 @@ pub fn unwrap_jsmanaged<T: Reflectable>(mut obj: *mut JSObject,
} }
/// Leak the given pointer. /// Leak the given pointer.
pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *T { pub unsafe fn squirrel_away_unique<T>(x: Box<T>) -> *const T {
mem::transmute(x) mem::transmute(x)
} }
@ -168,7 +166,7 @@ pub fn jsstring_to_str(cx: *mut JSContext, s: *mut JSString) -> DOMString {
let mut length = 0; let mut length = 0;
let chars = JS_GetStringCharsAndLength(cx, s, &mut length); let chars = JS_GetStringCharsAndLength(cx, s, &mut length);
slice::raw::buf_as_slice(chars, length as uint, |char_vec| { slice::raw::buf_as_slice(chars, length as uint, |char_vec| {
str::from_utf16(char_vec).unwrap() String::from_utf16(char_vec).unwrap()
}) })
} }
} }
@ -265,23 +263,22 @@ pub fn CreateInterfaceObjects2(cx: *mut JSContext, global: *mut JSObject, receiv
protoProto: *mut JSObject, protoProto: *mut JSObject,
protoClass: &'static JSClass, protoClass: &'static JSClass,
constructor: Option<(NonNullJSNative, &'static str, u32)>, constructor: Option<(NonNullJSNative, &'static str, u32)>,
domClass: *DOMClass, domClass: *const DOMClass,
members: &'static NativeProperties) -> *mut JSObject { members: &'static NativeProperties) -> *mut JSObject {
let proto = CreateInterfacePrototypeObject(cx, global, protoProto, let proto = CreateInterfacePrototypeObject(cx, global, protoProto,
protoClass, members); protoClass, members);
unsafe { unsafe {
JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT, JS_SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT,
PrivateValue(domClass as *libc::c_void)); PrivateValue(domClass as *const libc::c_void));
} }
match constructor { match constructor {
Some((native, name, nargs)) => { Some((native, name, nargs)) => {
name.to_c_str().with_ref(|s| { let s = name.to_c_str();
CreateInterfaceObject(cx, global, receiver, CreateInterfaceObject(cx, global, receiver,
native, nargs, proto, native, nargs, proto,
members, s) members, s.as_ptr())
})
}, },
None => (), None => (),
} }
@ -295,7 +292,7 @@ fn CreateInterfaceObject(cx: *mut JSContext, global: *mut JSObject, receiver: *m
constructorNative: NonNullJSNative, constructorNative: NonNullJSNative,
ctorNargs: u32, proto: *mut JSObject, ctorNargs: u32, proto: *mut JSObject,
members: &'static NativeProperties, members: &'static NativeProperties,
name: *libc::c_char) { name: *const libc::c_char) {
unsafe { unsafe {
let fun = JS_NewFunction(cx, Some(constructorNative), ctorNargs, let fun = JS_NewFunction(cx, Some(constructorNative), ctorNargs,
JSFUN_CONSTRUCTOR, global, name); JSFUN_CONSTRUCTOR, global, name);
@ -347,7 +344,7 @@ fn DefineConstants(cx: *mut JSContext, obj: *mut JSObject, constants: &'static [
VoidVal => UndefinedValue(), VoidVal => UndefinedValue(),
}; };
unsafe { unsafe {
assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *libc::c_char, assert!(JS_DefineProperty(cx, obj, spec.name.as_ptr() as *const libc::c_char,
jsval, None, None, jsval, None, None,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_READONLY |
JSPROP_PERMANENT) != 0); JSPROP_PERMANENT) != 0);
@ -380,7 +377,7 @@ fn CreateInterfacePrototypeObject(cx: *mut JSContext, global: *mut JSObject,
protoClass: &'static JSClass, protoClass: &'static JSClass,
members: &'static NativeProperties) -> *mut JSObject { members: &'static NativeProperties) -> *mut JSObject {
unsafe { unsafe {
let ourProto = JS_NewObjectWithUniqueType(cx, protoClass, parentProto, global); let ourProto = JS_NewObjectWithUniqueType(cx, protoClass, &*parentProto, &*global);
assert!(ourProto.is_not_null()); assert!(ourProto.is_not_null());
match members.methods { match members.methods {
@ -418,7 +415,7 @@ pub fn initialize_global(global: *mut JSObject) {
let box_ = squirrel_away_unique(protoArray); let box_ = squirrel_away_unique(protoArray);
JS_SetReservedSlot(global, JS_SetReservedSlot(global,
DOM_PROTOTYPE_SLOT, DOM_PROTOTYPE_SLOT,
PrivateValue(box_ as *libc::c_void)); PrivateValue(box_ as *const libc::c_void));
} }
} }
@ -462,7 +459,7 @@ impl Reflector {
/// Used by Temporary values to root the reflector, as required by the JSAPI rooting /// Used by Temporary values to root the reflector, as required by the JSAPI rooting
/// APIs. /// APIs.
pub fn rootable(&self) -> *mut *mut JSObject { pub fn rootable(&self) -> *mut *mut JSObject {
&self.object as *Cell<*mut JSObject> &self.object as *const Cell<*mut JSObject>
as *mut Cell<*mut JSObject> as *mut Cell<*mut JSObject>
as *mut *mut JSObject as *mut *mut JSObject
} }
@ -544,7 +541,7 @@ pub fn FindEnumStringIndex(cx: *mut JSContext,
Ok(values.iter().position(|value| { Ok(values.iter().position(|value| {
value.len() == length as uint && value.len() == length as uint &&
range(0, length as uint).all(|j| { range(0, length as uint).all(|j| {
value[j] as u16 == *chars.offset(j as int) value.as_bytes()[j] as u16 == *chars.offset(j as int)
}) })
})) }))
} }
@ -560,17 +557,13 @@ pub fn get_dictionary_property(cx: *mut JSContext,
fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, fn has_property(cx: *mut JSContext, object: *mut JSObject, property: &CString,
found: &mut JSBool) -> bool { found: &mut JSBool) -> bool {
unsafe { unsafe {
property.with_ref(|s| { JS_HasProperty(cx, object, property.as_ptr(), found) != 0
JS_HasProperty(cx, object, s, found) != 0
})
} }
} }
fn get_property(cx: *mut JSContext, object: *mut JSObject, property: &CString, fn get_property(cx: *mut JSContext, object: *mut JSObject, property: &CString,
value: &mut JSVal) -> bool { value: &mut JSVal) -> bool {
unsafe { unsafe {
property.with_ref(|s| { JS_GetProperty(cx, object, property.as_ptr(), value) != 0
JS_GetProperty(cx, object, s, value) != 0
})
} }
} }
@ -610,7 +603,7 @@ pub fn IsConvertibleToCallbackInterface(cx: *mut JSContext, obj: *mut JSObject)
} }
/// Create a DOM global object with the given class. /// Create a DOM global object with the given class.
pub fn CreateDOMGlobal(cx: *mut JSContext, class: *JSClass) -> *mut JSObject { pub fn CreateDOMGlobal(cx: *mut JSContext, class: *const JSClass) -> *mut JSObject {
unsafe { unsafe {
let obj = JS_NewGlobalObject(cx, class, ptr::mut_null()); let obj = JS_NewGlobalObject(cx, class, ptr::mut_null());
if obj.is_null() { if obj.is_null() {

View file

@ -85,20 +85,20 @@ static proxy_handler: ProxyTraps = ProxyTraps {
getPropertyDescriptor: None, getPropertyDescriptor: None,
getOwnPropertyDescriptor: None, getOwnPropertyDescriptor: None,
defineProperty: None, defineProperty: None,
getOwnPropertyNames: 0 as *u8, getOwnPropertyNames: 0 as *const u8,
delete_: None, delete_: None,
enumerate: 0 as *u8, enumerate: 0 as *const u8,
has: None, has: None,
hasOwn: None, hasOwn: None,
get: None, get: None,
set: None, set: None,
keys: 0 as *u8, keys: 0 as *const u8,
iterate: None, iterate: None,
call: None, call: None,
construct: None, construct: None,
nativeCall: 0 as *u8, nativeCall: 0 as *const u8,
hasInstance: None, hasInstance: None,
typeOf: None, typeOf: None,
objectClassIs: None, objectClassIs: None,
@ -113,7 +113,7 @@ static proxy_handler: ProxyTraps = ProxyTraps {
trace: None trace: None
}; };
pub fn new_window_proxy_handler() -> *c_void { pub fn new_window_proxy_handler() -> *const c_void {
unsafe { unsafe {
CreateWrapperProxyHandler(&proxy_handler) CreateWrapperProxyHandler(&proxy_handler)
} }

View file

@ -15,26 +15,26 @@ use servo_util::str::DOMString;
#[repr(uint)] #[repr(uint)]
#[deriving(Show, Encodable)] #[deriving(Show, Encodable)]
pub enum DOMErrorName { pub enum DOMErrorName {
IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR, IndexSizeError = DOMExceptionConstants::INDEX_SIZE_ERR as uint,
HierarchyRequestError = DOMExceptionConstants::HIERARCHY_REQUEST_ERR, HierarchyRequestError = DOMExceptionConstants::HIERARCHY_REQUEST_ERR as uint,
WrongDocumentError = DOMExceptionConstants::WRONG_DOCUMENT_ERR, WrongDocumentError = DOMExceptionConstants::WRONG_DOCUMENT_ERR as uint,
InvalidCharacterError = DOMExceptionConstants::INVALID_CHARACTER_ERR, InvalidCharacterError = DOMExceptionConstants::INVALID_CHARACTER_ERR as uint,
NoModificationAllowedError = DOMExceptionConstants::NO_MODIFICATION_ALLOWED_ERR, NoModificationAllowedError = DOMExceptionConstants::NO_MODIFICATION_ALLOWED_ERR as uint,
NotFoundError = DOMExceptionConstants::NOT_FOUND_ERR, NotFoundError = DOMExceptionConstants::NOT_FOUND_ERR as uint,
NotSupportedError = DOMExceptionConstants::NOT_SUPPORTED_ERR, NotSupportedError = DOMExceptionConstants::NOT_SUPPORTED_ERR as uint,
InvalidStateError = DOMExceptionConstants::INVALID_STATE_ERR, InvalidStateError = DOMExceptionConstants::INVALID_STATE_ERR as uint,
SyntaxError = DOMExceptionConstants::SYNTAX_ERR, SyntaxError = DOMExceptionConstants::SYNTAX_ERR as uint,
InvalidModificationError = DOMExceptionConstants::INVALID_MODIFICATION_ERR, InvalidModificationError = DOMExceptionConstants::INVALID_MODIFICATION_ERR as uint,
NamespaceError = DOMExceptionConstants::NAMESPACE_ERR, NamespaceError = DOMExceptionConstants::NAMESPACE_ERR as uint,
InvalidAccessError = DOMExceptionConstants::INVALID_ACCESS_ERR, InvalidAccessError = DOMExceptionConstants::INVALID_ACCESS_ERR as uint,
SecurityError = DOMExceptionConstants::SECURITY_ERR, SecurityError = DOMExceptionConstants::SECURITY_ERR as uint,
NetworkError = DOMExceptionConstants::NETWORK_ERR, NetworkError = DOMExceptionConstants::NETWORK_ERR as uint,
AbortError = DOMExceptionConstants::ABORT_ERR, AbortError = DOMExceptionConstants::ABORT_ERR as uint,
URLMismatchError = DOMExceptionConstants::URL_MISMATCH_ERR, URLMismatchError = DOMExceptionConstants::URL_MISMATCH_ERR as uint,
QuotaExceededError = DOMExceptionConstants::QUOTA_EXCEEDED_ERR, QuotaExceededError = DOMExceptionConstants::QUOTA_EXCEEDED_ERR as uint,
TimeoutError = DOMExceptionConstants::TIMEOUT_ERR, TimeoutError = DOMExceptionConstants::TIMEOUT_ERR as uint,
InvalidNodeTypeError = DOMExceptionConstants::INVALID_NODE_TYPE_ERR, InvalidNodeTypeError = DOMExceptionConstants::INVALID_NODE_TYPE_ERR as uint,
DataCloneError = DOMExceptionConstants::DATA_CLONE_ERR, DataCloneError = DOMExceptionConstants::DATA_CLONE_ERR as uint,
EncodingError EncodingError
} }
@ -100,7 +100,7 @@ impl<'a> DOMExceptionMethods for JSRef<'a, DOMException> {
// http://dom.spec.whatwg.org/#error-names-0 // http://dom.spec.whatwg.org/#error-names-0
fn Name(&self) -> DOMString { fn Name(&self) -> DOMString {
self.code.to_str() self.code.to_string()
} }
// http://dom.spec.whatwg.org/#error-names-0 // http://dom.spec.whatwg.org/#error-names-0

View file

@ -176,7 +176,7 @@ impl RawLayoutElementHelpers for Element {
unsafe fn get_attr_val_for_layout(&self, namespace: &Namespace, name: &str) unsafe fn get_attr_val_for_layout(&self, namespace: &Namespace, name: &str)
-> Option<&'static str> { -> Option<&'static str> {
// cast to point to T in RefCell<T> directly // cast to point to T in RefCell<T> directly
let attrs: *Vec<JS<Attr>> = mem::transmute(&self.attrs); let attrs: *const Vec<JS<Attr>> = mem::transmute(&self.attrs);
(*attrs).iter().find(|attr: & &JS<Attr>| { (*attrs).iter().find(|attr: & &JS<Attr>| {
let attr = attr.unsafe_get(); let attr = attr.unsafe_get();
name == (*attr).local_name.as_slice() && (*attr).namespace == *namespace name == (*attr).local_name.as_slice() && (*attr).namespace == *namespace
@ -190,7 +190,7 @@ impl RawLayoutElementHelpers for Element {
unsafe fn get_attr_atom_for_layout(&self, namespace: &Namespace, name: &str) unsafe fn get_attr_atom_for_layout(&self, namespace: &Namespace, name: &str)
-> Option<Atom> { -> Option<Atom> {
// cast to point to T in RefCell<T> directly // cast to point to T in RefCell<T> directly
let attrs: *Vec<JS<Attr>> = mem::transmute(&self.attrs); let attrs: *const Vec<JS<Attr>> = mem::transmute(&self.attrs);
(*attrs).iter().find(|attr: & &JS<Attr>| { (*attrs).iter().find(|attr: & &JS<Attr>| {
let attr = attr.unsafe_get(); let attr = attr.unsafe_get();
name == (*attr).local_name.as_slice() && (*attr).namespace == *namespace name == (*attr).local_name.as_slice() && (*attr).namespace == *namespace
@ -427,7 +427,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
} }
fn set_uint_attribute(&self, name: &str, value: u32) { fn set_uint_attribute(&self, name: &str, value: u32) {
assert!(name == name.to_ascii_lower().as_slice()); assert!(name == name.to_ascii_lower().as_slice());
self.set_attribute(name, UIntAttrValue(value.to_str(), value)); self.set_attribute(name, UIntAttrValue(value.to_string(), value));
} }
} }
@ -791,9 +791,9 @@ pub fn get_attribute_parts<'a>(name: &'a str) -> (Option<&'a str>, &'a str) {
} }
impl<'a> VirtualMethods for JSRef<'a, Element> { impl<'a> VirtualMethods for JSRef<'a, Element> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let node: &JSRef<Node> = NodeCast::from_ref(self); let node: &JSRef<Node> = NodeCast::from_ref(self);
Some(node as &VirtualMethods+) Some(node as &VirtualMethods)
} }
fn after_set_attr(&self, name: DOMString, value: DOMString) { fn after_set_attr(&self, name: DOMString, value: DOMString) {

View file

@ -29,10 +29,10 @@ pub enum Event_ {
#[deriving(Encodable)] #[deriving(Encodable)]
pub enum EventPhase { pub enum EventPhase {
PhaseNone = EventConstants::NONE, PhaseNone = EventConstants::NONE as int,
PhaseCapturing = EventConstants::CAPTURING_PHASE, PhaseCapturing = EventConstants::CAPTURING_PHASE as int,
PhaseAtTarget = EventConstants::AT_TARGET, PhaseAtTarget = EventConstants::AT_TARGET as int,
PhaseBubbling = EventConstants::BUBBLING_PHASE, PhaseBubbling = EventConstants::BUBBLING_PHASE as int,
} }
#[deriving(PartialEq, Encodable)] #[deriving(PartialEq, Encodable)]

View file

@ -179,18 +179,20 @@ impl<'a> EventTargetHelpers for JSRef<'a, EventTarget> {
let nargs = 1; //XXXjdm not true for onerror let nargs = 1; //XXXjdm not true for onerror
static arg_name: [c_char, ..6] = static arg_name: [c_char, ..6] =
['e' as c_char, 'v' as c_char, 'e' as c_char, 'n' as c_char, 't' as c_char, 0]; ['e' as c_char, 'v' as c_char, 'e' as c_char, 'n' as c_char, 't' as c_char, 0];
static arg_names: [*c_char, ..1] = [&arg_name as *c_char]; static arg_names: [*const c_char, ..1] = [&arg_name as *const c_char];
let source = source.to_utf16(); let source: Vec<u16> = source.as_slice().utf16_units().collect();
let handler = name.with_ref(|name| { let handler = unsafe {
url.with_ref(|url| { JS_CompileUCFunction(cx,
unsafe { ptr::mut_null(),
JS_CompileUCFunction(cx, ptr::mut_null(), name, name.as_ptr(),
nargs, &arg_names as **i8 as *mut *i8, nargs,
source.as_ptr(), source.len() as size_t, url, lineno) &arg_names as *const *const i8 as *mut *const i8,
} source.as_ptr(),
}) source.len() as size_t,
}); url.as_ptr(),
lineno)
};
if handler.is_null() { if handler.is_null() {
report_pending_exception(cx, self.reflector().get_jsobject()); report_pending_exception(cx, self.reflector().get_jsobject());
return; return;
@ -279,7 +281,7 @@ impl Reflectable for EventTarget {
} }
impl<'a> VirtualMethods for JSRef<'a, EventTarget> { impl<'a> VirtualMethods for JSRef<'a, EventTarget> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
None None
} }
} }

View file

@ -67,9 +67,9 @@ impl<'a> PrivateHTMLAnchorElementHelpers for JSRef<'a, HTMLAnchorElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLAnchorElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLAnchorElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods+) Some(htmlelement as &VirtualMethods)
} }
fn handle_event(&self, event: &JSRef<Event>) { fn handle_event(&self, event: &JSRef<Event>) {

View file

@ -55,9 +55,9 @@ impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let element: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let element: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(element as &VirtualMethods+) Some(element as &VirtualMethods)
} }
fn after_set_attr(&self, name: DOMString, value: DOMString) { fn after_set_attr(&self, name: DOMString, value: DOMString) {

View file

@ -93,9 +93,9 @@ impl<'a> HTMLCanvasElementMethods for JSRef<'a, HTMLCanvasElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLCanvasElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLCanvasElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let element: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let element: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(element as &VirtualMethods+) Some(element as &VirtualMethods)
} }
fn before_remove_attr(&self, name: DOMString, value: DOMString) { fn before_remove_attr(&self, name: DOMString, value: DOMString) {

View file

@ -87,9 +87,9 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let element: &JSRef<Element> = ElementCast::from_ref(self); let element: &JSRef<Element> = ElementCast::from_ref(self);
Some(element as &VirtualMethods+) Some(element as &VirtualMethods)
} }
fn after_set_attr(&self, name: DOMString, value: DOMString) { fn after_set_attr(&self, name: DOMString, value: DOMString) {

View file

@ -158,9 +158,9 @@ impl<'a> HTMLIFrameElementMethods for JSRef<'a, HTMLIFrameElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLIFrameElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLIFrameElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods+) Some(htmlelement as &VirtualMethods)
} }
fn after_set_attr(&self, name: DOMString, value: DOMString) { fn after_set_attr(&self, name: DOMString, value: DOMString) {

View file

@ -129,7 +129,7 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
fn SetIsMap(&self, is_map: bool) { fn SetIsMap(&self, is_map: bool) {
let element: &JSRef<Element> = ElementCast::from_ref(self); let element: &JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("isMap", is_map.to_str()) element.set_string_attribute("isMap", is_map.to_string())
} }
fn Width(&self) -> u32 { fn Width(&self) -> u32 {
@ -216,9 +216,9 @@ impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods+) Some(htmlelement as &VirtualMethods)
} }
fn after_set_attr(&self, name: DOMString, value: DOMString) { fn after_set_attr(&self, name: DOMString, value: DOMString) {

View file

@ -86,9 +86,9 @@ impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods+) Some(htmlelement as &VirtualMethods)
} }
fn after_set_attr(&self, name: DOMString, value: DOMString) { fn after_set_attr(&self, name: DOMString, value: DOMString) {

View file

@ -61,9 +61,9 @@ impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
} }
impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> { impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods+) Some(htmlelement as &VirtualMethods)
} }
fn child_inserted(&self, child: &JSRef<Node>) { fn child_inserted(&self, child: &JSRef<Node>) {

View file

@ -164,7 +164,7 @@ pub struct SharedLayoutData {
pub struct LayoutData { pub struct LayoutData {
chan: Option<LayoutChan>, chan: Option<LayoutChan>,
_shared_data: SharedLayoutData, _shared_data: SharedLayoutData,
_data: *(), _data: *const (),
} }
pub struct LayoutDataRef { pub struct LayoutDataRef {
@ -197,7 +197,7 @@ impl LayoutDataRef {
/// happen if you try to mutate the layout data while this is held. This is the only thread- /// happen if you try to mutate the layout data while this is held. This is the only thread-
/// safe layout data accessor. /// safe layout data accessor.
#[inline] #[inline]
pub unsafe fn borrow_unchecked(&self) -> *Option<LayoutData> { pub unsafe fn borrow_unchecked(&self) -> *const Option<LayoutData> {
mem::transmute(&self.data_cell) mem::transmute(&self.data_cell)
} }
@ -538,7 +538,7 @@ impl<'a> NodeHelpers for JSRef<'a, Node> {
} }
fn to_trusted_node_address(&self) -> TrustedNodeAddress { fn to_trusted_node_address(&self) -> TrustedNodeAddress {
TrustedNodeAddress(self.deref() as *Node as *libc::c_void) TrustedNodeAddress(self.deref() as *const Node as *const libc::c_void)
} }
fn get_bounding_content_box(&self) -> Rect<Au> { fn get_bounding_content_box(&self) -> Rect<Au> {
@ -665,7 +665,7 @@ pub fn from_untrusted_node_address(runtime: *mut JSRuntime, candidate: Untrusted
if object.is_null() { if object.is_null() {
fail!("Attempted to create a `JS<Node>` from an invalid pointer!") fail!("Attempted to create a `JS<Node>` from an invalid pointer!")
} }
let boxed_node: *Node = utils::unwrap(object); let boxed_node: *const Node = utils::unwrap(object);
Temporary::new(JS::from_raw(boxed_node)) Temporary::new(JS::from_raw(boxed_node))
} }
} }
@ -905,7 +905,7 @@ pub enum CloneChildrenFlag {
DoNotCloneChildren DoNotCloneChildren
} }
fn as_uintptr<T>(t: &T) -> uintptr_t { t as *T as uintptr_t } fn as_uintptr<T>(t: &T) -> uintptr_t { t as *const T as uintptr_t }
impl Node { impl Node {
pub fn reflect_node<N: Reflectable+NodeBase> pub fn reflect_node<N: Reflectable+NodeBase>
@ -1918,9 +1918,9 @@ pub fn window_from_node<T: NodeBase>(derived: &JSRef<T>) -> Temporary<Window> {
} }
impl<'a> VirtualMethods for JSRef<'a, Node> { impl<'a> VirtualMethods for JSRef<'a, Node> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(self); let eventtarget: &JSRef<EventTarget> = EventTargetCast::from_ref(self);
Some(eventtarget as &VirtualMethods+) Some(eventtarget as &VirtualMethods)
} }
} }

View file

@ -18,7 +18,7 @@ use encoding::types::{Encoding, EncodeReplace};
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::hashmap::HashMap; use std::collections::hashmap::HashMap;
use std::num::ToStrRadix; use std::fmt::radix;
use std::ascii::OwnedStrAsciiExt; use std::ascii::OwnedStrAsciiExt;
#[deriving(Encodable)] #[deriving(Encodable)]
@ -115,7 +115,9 @@ impl URLSearchParamsHelpers for URLSearchParams {
a => { a => {
// http://url.spec.whatwg.org/#percent-encode // http://url.spec.whatwg.org/#percent-encode
let mut encoded = vec!(0x25); // % let mut encoded = vec!(0x25); // %
encoded.push_all(a.to_str_radix(16).into_ascii_upper().as_bytes()); let s = format!("{}", radix(a, 16)).into_ascii_upper();
let bytes = s.as_bytes();
encoded.push_all(bytes);
encoded encoded
} }
}; };

View file

@ -35,7 +35,7 @@ use servo_util::str::DOMString;
pub trait VirtualMethods { pub trait VirtualMethods {
/// Returns self as the superclass of the implementation for this trait, /// Returns self as the superclass of the implementation for this trait,
/// if any. /// if any.
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+>; fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods>;
/// Called when changing or adding attributes, after the attribute's value /// Called when changing or adding attributes, after the attribute's value
/// has been updated. /// has been updated.
@ -105,46 +105,46 @@ pub trait VirtualMethods {
/// method call on the trait object will invoke the corresponding method on the /// method call on the trait object will invoke the corresponding method on the
/// concrete type, propagating up the parent hierarchy unless otherwise /// concrete type, propagating up the parent hierarchy unless otherwise
/// interrupted. /// interrupted.
pub fn vtable_for<'a>(node: &'a JSRef<Node>) -> &'a VirtualMethods+ { pub fn vtable_for<'a>(node: &'a JSRef<Node>) -> &'a VirtualMethods {
match node.type_id() { match node.type_id() {
ElementNodeTypeId(HTMLAnchorElementTypeId) => { ElementNodeTypeId(HTMLAnchorElementTypeId) => {
let element: &JSRef<HTMLAnchorElement> = HTMLAnchorElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLAnchorElement> = HTMLAnchorElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(HTMLBodyElementTypeId) => { ElementNodeTypeId(HTMLBodyElementTypeId) => {
let element: &JSRef<HTMLBodyElement> = HTMLBodyElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLBodyElement> = HTMLBodyElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(HTMLCanvasElementTypeId) => { ElementNodeTypeId(HTMLCanvasElementTypeId) => {
let element: &JSRef<HTMLCanvasElement> = HTMLCanvasElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLCanvasElement> = HTMLCanvasElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(HTMLImageElementTypeId) => { ElementNodeTypeId(HTMLImageElementTypeId) => {
let element: &JSRef<HTMLImageElement> = HTMLImageElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLImageElement> = HTMLImageElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(HTMLIFrameElementTypeId) => { ElementNodeTypeId(HTMLIFrameElementTypeId) => {
let element: &JSRef<HTMLIFrameElement> = HTMLIFrameElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLIFrameElement> = HTMLIFrameElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(HTMLObjectElementTypeId) => { ElementNodeTypeId(HTMLObjectElementTypeId) => {
let element: &JSRef<HTMLObjectElement> = HTMLObjectElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLObjectElement> = HTMLObjectElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(HTMLStyleElementTypeId) => { ElementNodeTypeId(HTMLStyleElementTypeId) => {
let element: &JSRef<HTMLStyleElement> = HTMLStyleElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLStyleElement> = HTMLStyleElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(ElementTypeId) => { ElementNodeTypeId(ElementTypeId) => {
let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap(); let element: &JSRef<Element> = ElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
ElementNodeTypeId(_) => { ElementNodeTypeId(_) => {
let element: &JSRef<HTMLElement> = HTMLElementCast::to_ref(node).unwrap(); let element: &JSRef<HTMLElement> = HTMLElementCast::to_ref(node).unwrap();
element as &VirtualMethods+ element as &VirtualMethods
} }
_ => { _ => {
node as &VirtualMethods+ node as &VirtualMethods
} }
} }
} }

View file

@ -71,11 +71,11 @@ pub enum XMLHttpRequestId {
#[deriving(PartialEq, Encodable)] #[deriving(PartialEq, Encodable)]
enum XMLHttpRequestState { enum XMLHttpRequestState {
Unsent = 0u16, Unsent = 0,
Opened = 1u16, Opened = 1,
HeadersReceived = 2u16, HeadersReceived = 2,
Loading = 3u16, Loading = 3,
XHRDone = 4u16, // So as not to conflict with the ProgressMsg `Done` XHRDone = 4, // So as not to conflict with the ProgressMsg `Done`
} }
pub enum XHRProgress { pub enum XHRProgress {
@ -632,7 +632,8 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
}, },
_ if self.ready_state.deref().get() != XHRDone => NullValue(), _ if self.ready_state.deref().get() != XHRDone => NullValue(),
Json => { Json => {
let decoded = UTF_8.decode(self.response.deref().borrow().as_slice(), DecodeReplace).unwrap().to_string().to_utf16(); let decoded = UTF_8.decode(self.response.deref().borrow().as_slice(), DecodeReplace).unwrap().to_string();
let decoded: Vec<u16> = decoded.as_slice().utf16_units().collect();
let mut vp = UndefinedValue(); let mut vp = UndefinedValue();
unsafe { unsafe {
if JS_ParseJSON(cx, decoded.as_ptr(), decoded.len() as u32, &mut vp) == 0 { if JS_ParseJSON(cx, decoded.as_ptr(), decoded.len() as u32, &mut vp) == 0 {
@ -679,7 +680,7 @@ impl XMLHttpRequestDerived for EventTarget {
} }
} }
pub struct TrustedXHRAddress(pub *c_void); pub struct TrustedXHRAddress(pub *const c_void);
impl TrustedXHRAddress { impl TrustedXHRAddress {
pub fn release_once(self) { pub fn release_once(self) {
@ -713,7 +714,7 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
} }
let pinned_count = self.pinned_count.deref().get(); let pinned_count = self.pinned_count.deref().get();
self.pinned_count.deref().set(pinned_count + 1); self.pinned_count.deref().set(pinned_count + 1);
TrustedXHRAddress(self.deref() as *XMLHttpRequest as *libc::c_void) TrustedXHRAddress(self.deref() as *const XMLHttpRequest as *const libc::c_void)
} }
fn release_once(&self) { fn release_once(&self) {

View file

@ -555,7 +555,7 @@ pub fn parse_html(page: &Page,
} }
fn build_parser(node: hubbub::NodeDataPtr) -> hubbub::Parser { fn build_parser(node: hubbub::NodeDataPtr) -> hubbub::Parser {
let mut parser = hubbub::Parser("UTF-8", false); let mut parser = hubbub::Parser::new("UTF-8", false);
parser.set_document_node(node); parser.set_document_node(node);
parser.enable_scripting(true); parser.enable_scripting(true);
parser.enable_styling(true); parser.enable_styling(true);

View file

@ -65,12 +65,12 @@ pub enum LayoutQuery {
/// The address of a node known to be valid. These must only be sent from content -> layout, /// The address of a node known to be valid. These must only be sent from content -> layout,
/// because we do not trust layout. /// because we do not trust layout.
pub struct TrustedNodeAddress(pub *c_void); pub struct TrustedNodeAddress(pub *const c_void);
impl<S: Encoder<E>, E> Encodable<S, E> for TrustedNodeAddress { impl<S: Encoder<E>, E> Encodable<S, E> for TrustedNodeAddress {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
let TrustedNodeAddress(addr) = *self; let TrustedNodeAddress(addr) = *self;
let node = addr as *Node; let node = addr as *const Node;
unsafe { unsafe {
JS::from_raw(node).encode(s) JS::from_raw(node).encode(s)
} }
@ -79,7 +79,7 @@ impl<S: Encoder<E>, E> Encodable<S, E> for TrustedNodeAddress {
/// The address of a node. Layout sends these back. They must be validated via /// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout. /// `from_untrusted_node_address` before they can be used, because we do not trust layout.
pub type UntrustedNodeAddress = *c_void; pub type UntrustedNodeAddress = *const c_void;
pub struct ContentBoxResponse(pub Rect<Au>); pub struct ContentBoxResponse(pub Rect<Au>);
pub struct ContentBoxesResponse(pub Vec<Rect<Au>>); pub struct ContentBoxesResponse(pub Vec<Rect<Au>>);

View file

@ -2,15 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#script:0.1"] #![crate_name = "script"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"] #![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"] #![license = "MPL"]
#![feature(globs, macro_rules, struct_variant, phase)] #![feature(globs, macro_rules, struct_variant, phase, unsafe_destructor)]
#![feature(phase)] #![feature(phase)]

View file

@ -45,17 +45,16 @@ use servo_msg::constellation_msg;
use servo_net::image_cache_task::ImageCacheTask; use servo_net::image_cache_task::ImageCacheTask;
use servo_net::resource_task::ResourceTask; use servo_net::resource_task::ResourceTask;
use servo_util::geometry::to_frac_px; use servo_util::geometry::to_frac_px;
use servo_util::task::send_on_failure; use servo_util::task::spawn_named_with_send_on_failure;
use std::cell::RefCell; use std::cell::RefCell;
use std::comm::{channel, Sender, Receiver}; use std::comm::{channel, Sender, Receiver};
use std::mem::replace; use std::mem::replace;
use std::rc::Rc; use std::rc::Rc;
use std::task::TaskBuilder;
use url::Url; use url::Url;
use serialize::{Encoder, Encodable}; use serialize::{Encoder, Encodable};
local_data_key!(pub StackRoots: *RootCollection) local_data_key!(pub StackRoots: *const RootCollection)
/// Messages used to control the script task. /// Messages used to control the script task.
pub enum ScriptMsg { pub enum ScriptMsg {
@ -116,7 +115,7 @@ pub struct StackRootTLS;
impl StackRootTLS { impl StackRootTLS {
pub fn new(roots: &RootCollection) -> StackRootTLS { pub fn new(roots: &RootCollection) -> StackRootTLS {
StackRoots.replace(Some(roots as *RootCollection)); StackRoots.replace(Some(roots as *const RootCollection));
StackRootTLS StackRootTLS
} }
} }
@ -287,10 +286,8 @@ impl ScriptTask {
resource_task: ResourceTask, resource_task: ResourceTask,
image_cache_task: ImageCacheTask, image_cache_task: ImageCacheTask,
window_size: WindowSizeData) { window_size: WindowSizeData) {
let mut builder = TaskBuilder::new().named("ScriptTask");
let ConstellationChan(const_chan) = constellation_chan.clone(); let ConstellationChan(const_chan) = constellation_chan.clone();
send_on_failure(&mut builder, FailureMsg(failure_msg), const_chan); spawn_named_with_send_on_failure("ScriptTask", proc() {
builder.spawn(proc() {
let script_task = ScriptTask::new(id, let script_task = ScriptTask::new(id,
compositor as Box<ScriptListener>, compositor as Box<ScriptListener>,
layout_chan, layout_chan,
@ -305,7 +302,7 @@ impl ScriptTask {
// This must always be the very last operation performed before the task completes // This must always be the very last operation performed before the task completes
failsafe.neuter(); failsafe.neuter();
}); }, FailureMsg(failure_msg), const_chan);
} }
/// Handle incoming control messages. /// Handle incoming control messages.

View file

@ -28,7 +28,7 @@ pub enum StylesheetOrigin {
} }
/// The definition of whitespace per CSS Selectors Level 3 § 4. /// The definition of whitespace per CSS Selectors Level 3 § 4.
static SELECTOR_WHITESPACE: &'static [char] = &'static [' ', '\t', '\n', '\r', '\x0C']; static SELECTOR_WHITESPACE: &'static [char] = &[' ', '\t', '\n', '\r', '\x0C'];
/// A newtype struct used to perform lowercase ASCII comparisons without allocating a whole new /// A newtype struct used to perform lowercase ASCII comparisons without allocating a whole new
/// string. /// string.
@ -344,9 +344,9 @@ impl Stylist {
// Take apart the StyleRule into individual Rules and insert // Take apart the StyleRule into individual Rules and insert
// them into the SelectorMap of that priority. // them into the SelectorMap of that priority.
macro_rules! append( macro_rules! append(
($priority: ident) => { ($style_rule: ident, $priority: ident) => {
if style_rule.declarations.$priority.len() > 0 { if $style_rule.declarations.$priority.len() > 0 {
for selector in style_rule.selectors.iter() { for selector in $style_rule.selectors.iter() {
let map = match selector.pseudo_element { let map = match selector.pseudo_element {
None => &mut element_map, None => &mut element_map,
Some(Before) => &mut before_map, Some(Before) => &mut before_map,
@ -356,7 +356,7 @@ impl Stylist {
selector: selector.compound_selectors.clone(), selector: selector.compound_selectors.clone(),
property: MatchedProperty { property: MatchedProperty {
specificity: selector.specificity, specificity: selector.specificity,
declarations: style_rule.declarations.$priority.clone(), declarations: $style_rule.declarations.$priority.clone(),
source_order: rules_source_order, source_order: rules_source_order,
}, },
}); });
@ -367,8 +367,8 @@ impl Stylist {
let device = &Device { media_type: Screen }; // TODO, use Print when printing let device = &Device { media_type: Screen }; // TODO, use Print when printing
iter_style_rules(stylesheet.rules.as_slice(), device, |style_rule| { iter_style_rules(stylesheet.rules.as_slice(), device, |style_rule| {
append!(normal); append!(style_rule, normal);
append!(important); append!(style_rule, important);
rules_source_order += 1; rules_source_order += 1;
}); });
self.rules_source_order = rules_source_order; self.rules_source_order = rules_source_order;
@ -511,10 +511,10 @@ impl Eq for MatchedProperty {}
impl PartialOrd for MatchedProperty { impl PartialOrd for MatchedProperty {
#[inline] #[inline]
fn lt(&self, other: &MatchedProperty) -> bool { fn partial_cmp(&self, other: &MatchedProperty) -> Option<Ordering> {
let this_rank = (self.specificity, self.source_order); let this_rank = (self.specificity, self.source_order);
let other_rank = (other.specificity, other.source_order); let other_rank = (other.specificity, other.source_order);
this_rank < other_rank this_rank.partial_cmp(&other_rank)
} }
} }

View file

@ -2,9 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#style:0.1"] #![crate_name = "style"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"] #![comment = "The Servo Parallel Browser Project"]

View file

@ -58,7 +58,7 @@ impl<K: Clone + PartialEq, V: Clone> Cache<K,V> for MonoCache<K,V> {
#[test] #[test]
fn test_monocache() { fn test_monocache() {
let mut cache = MonoCache::new(10); let mut cache: MonoCache<uint,Cell<&str>> = MonoCache::new(10);
let one = Cell::new("one"); let one = Cell::new("one");
let two = Cell::new("two"); let two = Cell::new("two");
cache.insert(1, one); cache.insert(1, one);
@ -105,7 +105,7 @@ impl<K: Clone + PartialEq + Eq + Hash, V: Clone> Cache<K,V> for HashCache<K,V> {
#[test] #[test]
fn test_hashcache() { fn test_hashcache() {
let mut cache = HashCache::new(); let mut cache: HashCache<uint, Cell<&str>> = HashCache::new();
let one = Cell::new("one"); let one = Cell::new("one");
let two = Cell::new("two"); let two = Cell::new("two");
@ -252,7 +252,7 @@ fn test_lru_cache() {
let four = Cell::new("four"); let four = Cell::new("four");
// Test normal insertion. // Test normal insertion.
let mut cache = LRUCache::new(2); // (_, _) (cache is empty) let mut cache: LRUCache<uint,Cell<&str>> = LRUCache::new(2); // (_, _) (cache is empty)
cache.insert(1, one); // (1, _) cache.insert(1, one); // (1, _)
cache.insert(2, two); // (1, 2) cache.insert(2, two); // (1, 2)
cache.insert(3, three); // (2, 3) cache.insert(3, three); // (2, 3)

View file

@ -10,23 +10,23 @@ use std::slice::raw::buf_as_slice;
fn hexdump_slice(buf: &[u8]) { fn hexdump_slice(buf: &[u8]) {
let mut stderr = io::stderr(); let mut stderr = io::stderr();
stderr.write(bytes!(" ")).unwrap(); stderr.write(b" ").unwrap();
for (i, &v) in buf.iter().enumerate() { for (i, &v) in buf.iter().enumerate() {
let output = format!("{:02X} ", v as uint); let output = format!("{:02X} ", v as uint);
stderr.write(output.as_bytes()).unwrap(); stderr.write(output.as_bytes()).unwrap();
match i % 16 { match i % 16 {
15 => { stderr.write(bytes!("\n ")).unwrap(); }, 15 => { stderr.write(b"\n ").unwrap(); },
7 => { stderr.write(bytes!(" ")).unwrap(); }, 7 => { stderr.write(b" ").unwrap(); },
_ => () _ => ()
} }
stderr.flush().unwrap(); stderr.flush().unwrap();
} }
stderr.write(bytes!("\n")).unwrap(); stderr.write(b"\n").unwrap();
} }
pub fn hexdump<T>(obj: &T) { pub fn hexdump<T>(obj: &T) {
unsafe { unsafe {
let buf: *u8 = mem::transmute(obj); let buf: *const u8 = mem::transmute(obj);
debug!("dumping at {:p}", buf); debug!("dumping at {:p}", buf);
buf_as_slice(buf, size_of::<T>(), hexdump_slice); buf_as_slice(buf, size_of::<T>(), hexdump_slice);
} }

View file

@ -973,7 +973,7 @@ fn modes() -> [WritingMode, ..10] {
#[test] #[test]
fn test_size_round_trip() { fn test_size_round_trip() {
let physical = Size2D(1, 2); let physical = Size2D(1u32, 2u32);
for &mode in modes().iter() { for &mode in modes().iter() {
let logical = LogicalSize::from_physical(mode, physical); let logical = LogicalSize::from_physical(mode, physical);
assert!(logical.to_physical(mode) == physical); assert!(logical.to_physical(mode) == physical);
@ -984,7 +984,7 @@ fn test_size_round_trip() {
#[test] #[test]
fn test_point_round_trip() { fn test_point_round_trip() {
let physical = Point2D(1, 2); let physical = Point2D(1u32, 2u32);
let container = Size2D(100, 200); let container = Size2D(100, 200);
for &mode in modes().iter() { for &mode in modes().iter() {
let logical = LogicalPoint::from_physical(mode, physical, container); let logical = LogicalPoint::from_physical(mode, physical, container);
@ -996,7 +996,7 @@ fn test_point_round_trip() {
#[test] #[test]
fn test_margin_round_trip() { fn test_margin_round_trip() {
let physical = SideOffsets2D::new(1, 2, 3, 4); let physical = SideOffsets2D::new(1u32, 2u32, 3u32, 4u32);
for &mode in modes().iter() { for &mode in modes().iter() {
let logical = LogicalMargin::from_physical(mode, physical); let logical = LogicalMargin::from_physical(mode, physical);
assert!(logical.to_physical(mode) == physical); assert!(logical.to_physical(mode) == physical);
@ -1009,7 +1009,7 @@ fn test_margin_round_trip() {
#[test] #[test]
fn test_rect_round_trip() { fn test_rect_round_trip() {
let physical = Rect(Point2D(1, 2), Size2D(3, 4)); let physical = Rect(Point2D(1u32, 2u32), Size2D(3u32, 4u32));
let container = Size2D(100, 200); let container = Size2D(100, 200);
for &mode in modes().iter() { for &mode in modes().iter() {
let logical = LogicalRect::from_physical(mode, physical, container); let logical = LogicalRect::from_physical(mode, physical, container);

View file

@ -143,7 +143,7 @@ impl MemoryProfiler {
} }
extern { extern {
fn je_mallctl(name: *c_char, oldp: *mut c_void, oldlenp: *mut size_t, fn je_mallctl(name: *const c_char, oldp: *mut c_void, oldlenp: *mut size_t,
newp: *mut c_void, newlen: size_t) -> c_int; newp: *mut c_void, newlen: size_t) -> c_int;
} }
@ -167,7 +167,7 @@ macro_rules! option_try(
#[cfg(target_os="linux")] #[cfg(target_os="linux")]
fn get_proc_self_statm_field(field: uint) -> Option<u64> { fn get_proc_self_statm_field(field: uint) -> Option<u64> {
let mut f = File::open(&Path::new("/proc/self/statm")); let mut f = File::open(&Path::new("/proc/self/statm"));
match f.read_to_str() { match f.read_to_string() {
Ok(contents) => { Ok(contents) => {
let s = option_try!(contents.as_slice().words().nth(field)); let s = option_try!(contents.as_slice().words().nth(field));
let npages: u64 = option_try!(from_str(s)); let npages: u64 = option_try!(from_str(s));

View file

@ -85,7 +85,7 @@ fn args_fail(msg: &str) {
} }
pub fn from_cmdline_args(args: &[String]) -> Option<Opts> { pub fn from_cmdline_args(args: &[String]) -> Option<Opts> {
let app_name = args[0].to_str(); let app_name = args[0].to_string();
let args = args.tail(); let args = args.tail();
let opts = vec!( let opts = vec!(

View file

@ -50,9 +50,9 @@ impl<T> VecLike<T> for Vec<T> {
trait SmallVecPrivate<T> { trait SmallVecPrivate<T> {
unsafe fn set_len(&mut self, new_len: uint); unsafe fn set_len(&mut self, new_len: uint);
unsafe fn set_cap(&mut self, new_cap: uint); unsafe fn set_cap(&mut self, new_cap: uint);
fn data(&self, index: uint) -> *T; fn data(&self, index: uint) -> *const T;
fn mut_data(&mut self, index: uint) -> *mut T; fn mut_data(&mut self, index: uint) -> *mut T;
unsafe fn ptr(&self) -> *T; unsafe fn ptr(&self) -> *const T;
unsafe fn mut_ptr(&mut self) -> *mut T; unsafe fn mut_ptr(&mut self) -> *mut T;
unsafe fn set_ptr(&mut self, new_ptr: *mut T); unsafe fn set_ptr(&mut self, new_ptr: *mut T);
} }
@ -66,7 +66,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> {
self.cap() > self.inline_size() self.cap() > self.inline_size()
} }
fn begin(&self) -> *T { fn begin(&self) -> *const T {
unsafe { unsafe {
if self.spilled() { if self.spilled() {
self.ptr() self.ptr()
@ -76,7 +76,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> {
} }
} }
fn end(&self) -> *T { fn end(&self) -> *const T {
unsafe { unsafe {
self.begin().offset(self.len() as int) self.begin().offset(self.len() as int)
} }
@ -155,7 +155,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> {
} }
let end_ptr = self.begin().offset(last_index as int); let end_ptr = self.begin().offset(last_index as int);
mem::swap(&mut value, mem::transmute::<*T,&mut T>(end_ptr)); mem::swap(&mut value, mem::transmute::<*const T,&mut T>(end_ptr));
self.set_len(last_index); self.set_len(last_index);
Some(value) Some(value)
} }
@ -170,7 +170,7 @@ pub trait SmallVec<T> : SmallVecPrivate<T> {
if self.spilled() { if self.spilled() {
if intrinsics::owns_managed::<T>() { if intrinsics::owns_managed::<T>() {
local_heap::local_free(self.ptr() as *u8) local_heap::local_free(self.ptr() as *mut u8)
} else { } else {
heap::deallocate(self.mut_ptr() as *mut u8, heap::deallocate(self.mut_ptr() as *mut u8,
mem::size_of::<T>() * self.cap(), mem::size_of::<T>() * self.cap(),
@ -246,8 +246,8 @@ pub trait SmallVec<T> : SmallVecPrivate<T> {
} }
pub struct SmallVecIterator<'a,T> { pub struct SmallVecIterator<'a,T> {
ptr: *T, ptr: *const T,
end: *T, end: *const T,
lifetime: ContravariantLifetime<'a> lifetime: ContravariantLifetime<'a>
} }
@ -327,7 +327,7 @@ impl<'a,T> Drop for SmallVecMoveIterator<'a,T> {
Some(allocation) => { Some(allocation) => {
unsafe { unsafe {
if intrinsics::owns_managed::<T>() { if intrinsics::owns_managed::<T>() {
local_heap::local_free(allocation as *u8) local_heap::local_free(allocation as *mut u8)
} else { } else {
heap::deallocate(allocation as *mut u8, heap::deallocate(allocation as *mut u8,
mem::size_of::<T>() * self.cap, mem::size_of::<T>() * self.cap,
@ -346,7 +346,7 @@ macro_rules! def_small_vector(
pub struct $name<T> { pub struct $name<T> {
len: uint, len: uint,
cap: uint, cap: uint,
ptr: *T, ptr: *const T,
data: [T, ..$size], data: [T, ..$size],
} }
@ -357,15 +357,15 @@ macro_rules! def_small_vector(
unsafe fn set_cap(&mut self, new_cap: uint) { unsafe fn set_cap(&mut self, new_cap: uint) {
self.cap = new_cap self.cap = new_cap
} }
fn data(&self, index: uint) -> *T { fn data(&self, index: uint) -> *const T {
let ptr: *T = &self.data[index]; let ptr: *const T = &self.data[index];
ptr ptr
} }
fn mut_data(&mut self, index: uint) -> *mut T { fn mut_data(&mut self, index: uint) -> *mut T {
let ptr: *mut T = &mut self.data[index]; let ptr: *mut T = &mut self.data[index];
ptr ptr
} }
unsafe fn ptr(&self) -> *T { unsafe fn ptr(&self) -> *const T {
self.ptr self.ptr
} }
unsafe fn mut_ptr(&mut self) -> *mut T { unsafe fn mut_ptr(&mut self) -> *mut T {
@ -445,7 +445,7 @@ macro_rules! def_small_vector_drop_impl(
} }
if intrinsics::owns_managed::<T>() { if intrinsics::owns_managed::<T>() {
local_heap::local_free(self.ptr() as *u8) local_heap::local_free(self.ptr() as *mut u8)
} else { } else {
heap::deallocate(self.mut_ptr() as *mut u8, heap::deallocate(self.mut_ptr() as *mut u8,
mem::size_of::<T>() * self.cap(), mem::size_of::<T>() * self.cap(),

View file

@ -87,7 +87,7 @@ pub mod test {
#[test] #[test]
pub fn random() { pub fn random() {
let mut rng = rand::task_rng(); let mut rng = rand::task_rng();
for _ in range(0, 50000) { for _ in range(0u32, 50000u32) {
let len: uint = rng.gen(); let len: uint = rng.gen();
let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect(); let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect();
sort::quicksort(v.as_mut_slice()); sort::quicksort(v.as_mut_slice());

View file

@ -14,17 +14,21 @@ pub fn spawn_named<S: IntoMaybeOwned<'static>>(name: S, f: proc():Send) {
/// Arrange to send a particular message to a channel if the task built by /// Arrange to send a particular message to a channel if the task built by
/// this `TaskBuilder` fails. /// this `TaskBuilder` fails.
pub fn send_on_failure<T: Send>(builder: &mut TaskBuilder, msg: T, dest: Sender<T>) { pub fn spawn_named_with_send_on_failure<T: Send>(name: &str,
let port = builder.future_result(); f: proc(): Send,
let watched_name = builder.opts.name.as_ref().unwrap().as_slice().to_string(); msg: T,
let name = format!("{:s}Watcher", watched_name); dest: Sender<T>) {
spawn_named(name, proc() { let name = name.to_string();
match port.recv() { let future_result = TaskBuilder::new().named(name.clone()).try_future(f);
let watch_name = format!("{:s}Watcher", name);
spawn_named(watch_name, proc() {
match future_result.unwrap() {
Ok(()) => (), Ok(()) => (),
Err(..) => { Err(..) => {
debug!("{:s} failed, notifying constellation", watched_name); debug!("{:s} failed, notifying constellation", name);
dest.send(msg); dest.send(msg);
} }
} }
}) });
} }

View file

@ -2,12 +2,11 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![crate_id = "github.com/mozilla/servo#util:0.1"] #![crate_name = "util"]
#![crate_type = "lib"]
#![crate_type = "dylib"]
#![crate_type = "rlib"] #![crate_type = "rlib"]
#![feature(macro_rules)]
#![feature(macro_rules,unsafe_destructor)]
#![feature(phase)] #![feature(phase)]
#[phase(plugin, link)] #[phase(plugin, link)]

View file

@ -91,12 +91,12 @@ fn test_match<T: PartialEq>(b: &T, a: Option<&T>) -> bool {
#[test] #[test]
fn should_find_all_elements() { fn should_find_all_elements() {
let arr_odd = [1, 2, 4, 6, 7, 8, 9]; let arr_odd = [1u32, 2, 4, 6, 7, 8, 9];
let arr_even = [1, 2, 5, 6, 7, 8, 9, 42]; let arr_even = [1u32, 2, 5, 6, 7, 8, 9, 42];
let arr_double = [1, 1, 2, 2, 6, 8, 22]; let arr_double = [1u32, 1, 2, 2, 6, 8, 22];
let arr_one = [234986325]; let arr_one = [234986325u32];
let arr_two = [3044, 8393]; let arr_two = [3044u32, 8393];
let arr_three = [12, 23, 34]; let arr_three = [12u32, 23, 34];
test_find_all_elems(arr_odd); test_find_all_elems(arr_odd);
test_find_all_elems(arr_even); test_find_all_elems(arr_even);
@ -108,12 +108,12 @@ fn should_find_all_elements() {
#[test] #[test]
fn should_not_find_missing_elements() { fn should_not_find_missing_elements() {
let arr_odd = [1, 2, 4, 6, 7, 8, 9]; let arr_odd = [1u32, 2, 4, 6, 7, 8, 9];
let arr_even = [1, 2, 5, 6, 7, 8, 9, 42]; let arr_even = [1u32, 2, 5, 6, 7, 8, 9, 42];
let arr_double = [1, 1, 2, 2, 6, 8, 22]; let arr_double = [1u32, 1, 2, 2, 6, 8, 22];
let arr_one = [234986325]; let arr_one = [234986325u32];
let arr_two = [3044, 8393]; let arr_two = [3044u32, 8393];
let arr_three = [12, 23, 34]; let arr_three = [12u32, 23, 34];
test_miss_all_elems(arr_odd, [-22, 0, 3, 5, 34938, 10, 11, 12]); test_miss_all_elems(arr_odd, [-22, 0, 3, 5, 34938, 10, 11, 12]);
test_miss_all_elems(arr_even, [-1, 0, 3, 34938, 10, 11, 12]); test_miss_all_elems(arr_even, [-1, 0, 3, 34938, 10, 11, 12]);

View file

@ -7,13 +7,13 @@
//! Data associated with queues is simply a pair of unsigned integers. It is expected that a //! Data associated with queues is simply a pair of unsigned integers. It is expected that a
//! higher-level API on top of this could allow safe fork-join parallelism. //! higher-level API on top of this could allow safe fork-join parallelism.
use native; use native::task::NativeTaskBuilder;
use rand::{Rng, XorShiftRng}; use rand::{Rng, XorShiftRng};
use std::mem; use std::mem;
use std::rand::weak_rng; use std::rand::weak_rng;
use std::sync::atomics::{AtomicUint, SeqCst}; use std::sync::atomics::{AtomicUint, SeqCst};
use std::sync::deque::{Abort, BufferPool, Data, Empty, Stealer, Worker}; use std::sync::deque::{Abort, BufferPool, Data, Empty, Stealer, Worker};
use rustrt::task::TaskOpts; use std::task::TaskBuilder;
/// A unit of work. /// A unit of work.
/// ///
@ -31,7 +31,7 @@ pub struct WorkUnit<QueueData, WorkData> {
/// Messages from the supervisor to the worker. /// Messages from the supervisor to the worker.
enum WorkerMsg<QueueData, WorkData> { enum WorkerMsg<QueueData, WorkData> {
/// Tells the worker to start work. /// Tells the worker to start work.
StartMsg(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUint, *QueueData), StartMsg(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUint, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `StartMsg`. /// Tells the worker to stop. It can be restarted again with a `StartMsg`.
StopMsg, StopMsg,
/// Tells the worker thread to terminate. /// Tells the worker thread to terminate.
@ -159,7 +159,7 @@ impl<QueueData: Send, WorkData: Send> WorkerThread<QueueData, WorkData> {
pub struct WorkerProxy<'a, QueueData, WorkData> { pub struct WorkerProxy<'a, QueueData, WorkData> {
worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>, worker: &'a mut Worker<WorkUnit<QueueData, WorkData>>,
ref_count: *mut AtomicUint, ref_count: *mut AtomicUint,
queue_data: *QueueData, queue_data: *const QueueData,
} }
impl<'a, QueueData, WorkData: Send> WorkerProxy<'a, QueueData, WorkData> { impl<'a, QueueData, WorkData: Send> WorkerProxy<'a, QueueData, WorkData> {
@ -230,9 +230,7 @@ impl<QueueData: Send, WorkData: Send> WorkQueue<QueueData, WorkData> {
// Spawn threads. // Spawn threads.
for thread in threads.move_iter() { for thread in threads.move_iter() {
let mut opts = TaskOpts::new(); TaskBuilder::new().named(task_name).native().spawn(proc() {
opts.name = Some(task_name.into_maybe_owned());
native::task::spawn_opts(opts, proc() {
let mut thread = thread; let mut thread = thread;
thread.start() thread.start()
}) })

@ -1 +1 @@
Subproject commit 73a79ced1973870b316e529a985d943241b7917d Subproject commit b9d18985e71e85f0a4281203408de83c610bc929

@ -1 +1 @@
Subproject commit ee502da58190ecdd85d08eb0e11a2393cb0bd9dd Subproject commit d09217164ed148784232598d40497fdc1a81f972

@ -1 +1 @@
Subproject commit 4fbb9c38fc06d3116f44f4da36dd378d73f71b58 Subproject commit 54a26d982610165caaf8a0b4fed123358205210b

@ -1 +1 @@
Subproject commit f9b4c468cdd580ef8a5aabab11807fdbaf434afd Subproject commit ac87a88dabbea73d706e2ff8502952c43ad2bc4c

@ -1 +1 @@
Subproject commit 9516a94b8b02e30e17a0eb52e4aaae9430064f42 Subproject commit 140df9dfb16cbeabbbb7059d39f9c439bd3821eb

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