diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..9249f8e7a --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,5 @@ +[alias] +# Neon defines mutually exclusive feature flags which prevents using `cargo clippy --all-features` +# The following aliases simplify linting the entire workspace +clippy-legacy = "clippy --all-targets --no-default-features -p neon -p neon-runtime -p neon-build -p neon-macros -p tests -p static_tests --features event-handler-api,proc-macros,try-catch-api,legacy-runtime -- -A clippy::missing_safety_doc" +clippy-napi = "clippy --all-targets --no-default-features -p neon -p neon-runtime -p neon-build -p neon-macros -p electron-tests -p napi-tests --features proc-macros,try-catch-api,napi-experimental -- -A clippy::missing_safety_doc" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 000000000..3dded6b2a --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,39 @@ +name: Lints + +on: + push: + # Prevent duplicate runs of this workflow on our own internal PRs. + branches: + - main + pull_request: + branches: + - main + +jobs: + lint: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [14.x] + rust-toolchain: [nightly] + + steps: + - uses: actions/checkout@v2 + - name: Use Rust ${{ matrix.rust-toolchain }} + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust-toolchain }} + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: install build-essential + run: sudo apt-get install -y build-essential + - name: Formatting + run: cargo fmt --all -- --check + - name: Clippy (N-API) + run: cargo clippy-napi + - name: Clippy (Legacy) + run: cargo clippy-legacy diff --git a/crates/neon-build/src/napi/mod.rs b/crates/neon-build/src/napi/mod.rs index 1689cec3e..4c458b623 100644 --- a/crates/neon-build/src/napi/mod.rs +++ b/crates/neon-build/src/napi/mod.rs @@ -94,7 +94,9 @@ impl Setup { } fn absolute_output_file(&self) -> PathBuf { - let output_file = self.output_file.clone() + let output_file = self + .output_file + .clone() .unwrap_or_else(|| PathBuf::from("index.node")); // Don't prepend `output_dir` if `output_file` is absolute @@ -145,9 +147,7 @@ fn test_absolute_output_file_absolute_file() { #[test] fn test_absolute_output_file_absolute_dir() { let expected = PathBuf::from("/tmp/index.node"); - let actual = Setup::options() - .output_dir("/tmp") - .absolute_output_file(); + let actual = Setup::options().output_dir("/tmp").absolute_output_file(); assert_eq!(actual, expected); } @@ -155,9 +155,7 @@ fn test_absolute_output_file_absolute_dir() { #[test] fn test_absolute_output_file_relative_dir() { let expected = manifest_dir().join("lib").join("index.node"); - let actual = Setup::options() - .output_dir("lib") - .absolute_output_file(); + let actual = Setup::options().output_dir("lib").absolute_output_file(); assert_eq!(actual, expected); } diff --git a/crates/neon-macros/Cargo.toml b/crates/neon-macros/Cargo.toml index 0dc3c7baf..9682144b4 100644 --- a/crates/neon-macros/Cargo.toml +++ b/crates/neon-macros/Cargo.toml @@ -16,8 +16,3 @@ napi = [] [dependencies] quote = "1" syn = { version = "1", features = ["full"] } - -[dev-dependencies.neon] -version = "*" -path = "../.." -features = ["proc-macros"] diff --git a/crates/neon-macros/src/lib.rs b/crates/neon-macros/src/lib.rs index 51a0041b4..234759e9b 100644 --- a/crates/neon-macros/src/lib.rs +++ b/crates/neon-macros/src/lib.rs @@ -18,14 +18,14 @@ use legacy as macros; /// module. This attribute should only be used _once_ in a module and will /// be called each time the module is initialized in a context. /// -/// ```no_run +/// ```ignore /// # use neon::prelude::*; /// #[neon::main] /// fn my_module(mut cx: ModuleContext) -> NeonResult<()> { /// let version = cx.string("1.0.0"); -/// +/// /// cx.export_value("version", version)?; -/// +/// /// Ok(()) /// } /// ``` diff --git a/crates/neon-macros/src/napi.rs b/crates/neon-macros/src/napi.rs index 0d69ae0ed..ad2d4b868 100644 --- a/crates/neon-macros/src/napi.rs +++ b/crates/neon-macros/src/napi.rs @@ -23,7 +23,7 @@ pub(crate) fn main( ::std::mem::transmute(m), #name, ); - + m } diff --git a/crates/neon-runtime/src/lib.rs b/crates/neon-runtime/src/lib.rs index 33272fb0e..439933604 100644 --- a/crates/neon-runtime/src/lib.rs +++ b/crates/neon-runtime/src/lib.rs @@ -1,5 +1,7 @@ #[cfg(all(not(feature = "neon-sys"), not(feature = "napi")))] -compile_error!("The Neon runtime must have at least one of the `neon-sys` or `napi` backends enabled."); +compile_error!( + "The Neon runtime must have at least one of the `neon-sys` or `napi` backends enabled." +); use cfg_if::cfg_if; diff --git a/crates/neon-runtime/src/nan/mod.rs b/crates/neon-runtime/src/nan/mod.rs index 2f1c425ab..81f52c64f 100644 --- a/crates/neon-runtime/src/nan/mod.rs +++ b/crates/neon-runtime/src/nan/mod.rs @@ -1,19 +1,19 @@ -pub mod raw; -pub mod call; -pub mod scope; -pub mod object; pub mod array; -pub mod string; -pub mod primitive; -pub mod error; pub mod arraybuffer; pub mod buffer; -pub mod tag; -pub mod module; -pub mod mem; -pub mod fun; -pub mod convert; +pub mod call; pub mod class; -pub mod task; +pub mod convert; +pub mod error; +pub mod fun; pub mod handler; +pub mod mem; +pub mod module; +pub mod object; +pub mod primitive; +pub mod raw; +pub mod scope; +pub mod string; +pub mod tag; +pub mod task; pub mod try_catch; diff --git a/crates/neon-runtime/src/nan/raw.rs b/crates/neon-runtime/src/nan/raw.rs index d882e32ed..6aeb90d94 100644 --- a/crates/neon-runtime/src/nan/raw.rs +++ b/crates/neon-runtime/src/nan/raw.rs @@ -1,3 +1,5 @@ //! Fundamental definitions for mapping to the V8 memory space. -pub use neon_sys::{Local, FunctionCallbackInfo, Isolate, HandleScope, EscapableHandleScope, InheritedHandleScope}; +pub use neon_sys::{ + EscapableHandleScope, FunctionCallbackInfo, HandleScope, InheritedHandleScope, Isolate, Local, +}; diff --git a/crates/neon-runtime/src/nan/scope.rs b/crates/neon-runtime/src/nan/scope.rs index 6ea3d6a51..4bef7b81e 100644 --- a/crates/neon-runtime/src/nan/scope.rs +++ b/crates/neon-runtime/src/nan/scope.rs @@ -1,6 +1,6 @@ //! Facilities for working with `v8::HandleScope`s and `v8::EscapableHandleScope`s. -use crate::raw::{HandleScope, EscapableHandleScope, InheritedHandleScope, Isolate}; +use crate::raw::{EscapableHandleScope, HandleScope, InheritedHandleScope, Isolate}; pub trait Root { /// # Safety @@ -15,7 +15,9 @@ pub trait Root { } impl Root for HandleScope { - unsafe fn allocate() -> Self { HandleScope::new() } + unsafe fn allocate() -> Self { + HandleScope::new() + } unsafe fn enter(&mut self, isolate: Isolate) { enter(self, isolate) } @@ -25,7 +27,9 @@ impl Root for HandleScope { } impl Root for EscapableHandleScope { - unsafe fn allocate() -> Self { EscapableHandleScope::new() } + unsafe fn allocate() -> Self { + EscapableHandleScope::new() + } unsafe fn enter(&mut self, isolate: Isolate) { enter_escapable(self, isolate) } @@ -35,9 +39,11 @@ impl Root for EscapableHandleScope { } impl Root for InheritedHandleScope { - unsafe fn allocate() -> Self { InheritedHandleScope } - unsafe fn enter(&mut self, _: Isolate) { } - unsafe fn exit(&mut self, _: Isolate) { } + unsafe fn allocate() -> Self { + InheritedHandleScope + } + unsafe fn enter(&mut self, _: Isolate) {} + unsafe fn exit(&mut self, _: Isolate) {} } /// Mutates the `out` argument provided to refer to the newly escaped `v8::Local` value. diff --git a/crates/neon-runtime/src/napi/arraybuffer.rs b/crates/neon-runtime/src/napi/arraybuffer.rs index 2118cfca1..96e454608 100644 --- a/crates/neon-runtime/src/napi/arraybuffer.rs +++ b/crates/neon-runtime/src/napi/arraybuffer.rs @@ -21,8 +21,8 @@ pub unsafe fn data(env: Env, base_out: &mut *mut c_void, obj: Local) -> usize { } pub unsafe fn new_external(env: Env, data: T) -> Local - where - T: AsMut<[u8]> + Send, +where + T: AsMut<[u8]> + Send, { // Safety: Boxing could move the data; must box before grabbing a raw pointer let mut data = Box::new(data); diff --git a/crates/neon-runtime/src/napi/bindings/functions.rs b/crates/neon-runtime/src/napi/bindings/functions.rs index 5caeb126e..a143a1df1 100644 --- a/crates/neon-runtime/src/napi/bindings/functions.rs +++ b/crates/neon-runtime/src/napi/bindings/functions.rs @@ -1,310 +1,273 @@ #![allow(clippy::too_many_arguments)] mod napi1 { - use std::os::raw::{c_char, c_void}; use super::super::types::*; + use std::os::raw::{c_char, c_void}; + + generate!( + extern "C" { + fn get_undefined(env: Env, result: *mut Value) -> Status; + + fn get_null(env: Env, result: *mut Value) -> Status; + + fn get_global(env: Env, result: *mut Value) -> Status; + + fn get_boolean(env: Env, value: bool, result: *mut Value) -> Status; + + fn create_double(env: Env, value: f64, result: *mut Value) -> Status; + + fn create_object(env: Env, result: *mut Value) -> Status; + + fn get_value_bool(env: Env, value: Value, result: *mut bool) -> Status; - generate!(extern "C" { - fn get_undefined(env: Env, result: *mut Value) -> Status; + fn get_value_double(env: Env, value: Value, result: *mut f64) -> Status; - fn get_null(env: Env, result: *mut Value) -> Status; + fn create_array_with_length(env: Env, length: usize, result: *mut Value) -> Status; - fn get_global(env: Env, result: *mut Value) -> Status; + fn get_array_length(env: Env, value: Value, result: *mut u32) -> Status; - fn get_boolean(env: Env, value: bool, result: *mut Value) -> Status; + fn get_new_target(env: Env, cbinfo: CallbackInfo, result: *mut Value) -> Status; - fn create_double(env: Env, value: f64, result: *mut Value) -> Status; + fn coerce_to_object(env: Env, value: Value, result: *mut Value) -> Status; - fn create_object(env: Env, result: *mut Value) -> Status; + fn coerce_to_string(env: Env, value: Value, result: *mut Value) -> Status; - fn get_value_bool(env: Env, value: Value, result: *mut bool) -> Status; + fn throw(env: Env, error: Value) -> Status; - fn get_value_double(env: Env, value: Value, result: *mut f64) -> Status; + fn create_error(env: Env, code: Value, msg: Value, result: *mut Value) -> Status; - fn create_array_with_length(env: Env, length: usize, result: *mut Value) -> Status; + fn get_and_clear_last_exception(env: Env, result: *mut Value) -> Status; - fn get_array_length(env: Env, value: Value, result: *mut u32)-> Status; + fn is_exception_pending(env: Env, result: *mut bool) -> Status; - fn get_new_target(env: Env, cbinfo: CallbackInfo, result: *mut Value) -> Status; + fn get_value_external(env: Env, value: Value, result: *mut *mut c_void) -> Status; - fn coerce_to_object(env: Env, value: Value, result: *mut Value) -> Status; + fn typeof_value(env: Env, value: Value, result: *mut ValueType) -> Status; - fn coerce_to_string(env: Env, value: Value, result: *mut Value) -> Status; + fn close_escapable_handle_scope(env: Env, scope: EscapableHandleScope) -> Status; - fn throw(env: Env, error: Value) -> Status; + fn open_escapable_handle_scope(env: Env, result: *mut EscapableHandleScope) -> Status; - fn create_error(env: Env, code: Value, msg: Value, result: *mut Value) -> Status; + fn open_handle_scope(env: Env, result: *mut HandleScope) -> Status; - fn get_and_clear_last_exception(env: Env, result: *mut Value) -> Status; + fn close_handle_scope(env: Env, scope: HandleScope) -> Status; - fn is_exception_pending(env: Env, result: *mut bool) -> Status; + fn is_arraybuffer(env: Env, value: Value, result: *mut bool) -> Status; + fn is_buffer(env: Env, value: Value, result: *mut bool) -> Status; + fn is_error(env: Env, value: Value, result: *mut bool) -> Status; + fn is_array(env: Env, value: Value, result: *mut bool) -> Status; - fn get_value_external(env: Env, value: Value, result: *mut *mut c_void) -> Status; + fn get_value_string_utf8( + env: Env, + value: Value, + buf: *mut c_char, + bufsize: usize, + result: *mut usize, + ) -> Status; - fn typeof_value(env: Env, value: Value, result: *mut ValueType) -> Status; + fn create_type_error(env: Env, code: Value, msg: Value, result: *mut Value) -> Status; - fn close_escapable_handle_scope(env: Env, scope: EscapableHandleScope) -> Status; + fn create_range_error(env: Env, code: Value, msg: Value, result: *mut Value) -> Status; - fn open_escapable_handle_scope(env: Env, result: *mut EscapableHandleScope) -> Status; + fn create_string_utf8( + env: Env, + str: *const c_char, + length: usize, + result: *mut Value, + ) -> Status; - fn open_handle_scope(env: Env, result: *mut HandleScope) -> Status; + fn create_arraybuffer( + env: Env, + byte_length: usize, + data: *mut *mut c_void, + result: *mut Value, + ) -> Status; - fn close_handle_scope(env: Env, scope: HandleScope) -> Status; + fn get_arraybuffer_info( + env: Env, + arraybuffer: Value, + data: *mut *mut c_void, + byte_length: *mut usize, + ) -> Status; - fn is_arraybuffer(env: Env, value: Value, result: *mut bool) -> Status; - fn is_buffer(env: Env, value: Value, result: *mut bool) -> Status; - fn is_error(env: Env, value: Value, result: *mut bool) -> Status; - fn is_array(env: Env, value: Value, result: *mut bool) -> Status; + fn create_buffer( + env: Env, + length: usize, + data: *mut *mut c_void, + result: *mut Value, + ) -> Status; - fn get_value_string_utf8( - env: Env, - value: Value, - buf: *mut c_char, - bufsize: usize, - result: *mut usize, - ) -> Status; - - fn create_type_error( - env: Env, - code: Value, - msg: Value, - result: *mut Value, - ) -> Status; - - fn create_range_error( - env: Env, - code: Value, - msg: Value, - result: *mut Value, - ) -> Status; - - fn create_string_utf8( - env: Env, - str: *const c_char, - length: usize, - result: *mut Value, - ) -> Status; - - fn create_arraybuffer( - env: Env, - byte_length: usize, - data: *mut *mut c_void, - result: *mut Value, - ) -> Status; - - fn get_arraybuffer_info( - env: Env, - arraybuffer: Value, - data: *mut *mut c_void, - byte_length: *mut usize, - ) -> Status; - - fn create_buffer( - env: Env, - length: usize, - data: *mut *mut c_void, - result: *mut Value, - ) -> Status; - - fn get_buffer_info( - env: Env, - value: Value, - data: *mut *mut c_void, - length: *mut usize, - ) -> Status; - - fn get_cb_info( - env: Env, - cbinfo: CallbackInfo, - argc: *mut usize, - argv: *mut Value, - this_arg: *mut Value, - data: *mut *mut c_void, - ) -> Status; - - fn create_external( - env: Env, - data: *mut c_void, - finalize_cb: Finalize, - finalize_hint: *mut c_void, - result: *mut Value, - ) -> Status; - - fn new_instance( - env: Env, - constructor: Value, - argc: usize, - argv: *const Value, - result: *mut Value, - ) -> Status; - - fn call_function( - env: Env, - recv: Value, - func: Value, - argc: usize, - argv: *const Value, - result: *mut Value, - ) -> Status; - - fn create_function( - env: Env, - utf8name: *const c_char, - length: usize, - cb: Callback, - data: *mut c_void, - result: *mut Value, - ) -> Status; - - fn set_property( - env: Env, - object: Value, - key: Value, - value: Value, - ) -> Status; - - fn get_property( - env: Env, - object: Value, - key: Value, - result: *mut Value, - ) -> Status; - - fn set_element( - env: Env, - object: Value, - index: u32, - value: Value, - ) -> Status; - - fn get_element( - env: Env, - object: Value, - index: u32, - result: *mut Value, - ) -> Status; - - fn escape_handle( - env: Env, - scope: EscapableHandleScope, - escapee: Value, - result: *mut Value, - ) -> Status; - - fn create_reference( - env: Env, - value: Value, - initial_ref_count: u32, - result: *mut Ref, - ) -> Status; - - fn reference_ref(env: Env, reference: Ref, result: *mut u32) -> Status; - - fn reference_unref(env: Env, reference: Ref, result: *mut u32) -> Status; - - fn get_reference_value( - env: Env, - reference: Ref, - result: *mut Value, - ) -> Status; - - fn strict_equals( - env: Env, - lhs: Value, - rhs: Value, - result: *mut bool - ) -> Status; - - fn create_external_arraybuffer( - env: Env, - data: *mut c_void, - length: usize, - finalize_cb: Finalize, - finalize_hint: *mut c_void, - result: *mut Value, - ) -> Status; - - fn create_external_buffer( - env: Env, - length: usize, - data: *mut c_void, - finalize_cb: Finalize, - finalize_hint: *mut c_void, - result: *mut Value, - ) -> Status; - }); + fn get_buffer_info( + env: Env, + value: Value, + data: *mut *mut c_void, + length: *mut usize, + ) -> Status; + + fn get_cb_info( + env: Env, + cbinfo: CallbackInfo, + argc: *mut usize, + argv: *mut Value, + this_arg: *mut Value, + data: *mut *mut c_void, + ) -> Status; + + fn create_external( + env: Env, + data: *mut c_void, + finalize_cb: Finalize, + finalize_hint: *mut c_void, + result: *mut Value, + ) -> Status; + + fn new_instance( + env: Env, + constructor: Value, + argc: usize, + argv: *const Value, + result: *mut Value, + ) -> Status; + + fn call_function( + env: Env, + recv: Value, + func: Value, + argc: usize, + argv: *const Value, + result: *mut Value, + ) -> Status; + + fn create_function( + env: Env, + utf8name: *const c_char, + length: usize, + cb: Callback, + data: *mut c_void, + result: *mut Value, + ) -> Status; + + fn set_property(env: Env, object: Value, key: Value, value: Value) -> Status; + + fn get_property(env: Env, object: Value, key: Value, result: *mut Value) -> Status; + + fn set_element(env: Env, object: Value, index: u32, value: Value) -> Status; + + fn get_element(env: Env, object: Value, index: u32, result: *mut Value) -> Status; + + fn escape_handle( + env: Env, + scope: EscapableHandleScope, + escapee: Value, + result: *mut Value, + ) -> Status; + + fn create_reference( + env: Env, + value: Value, + initial_ref_count: u32, + result: *mut Ref, + ) -> Status; + + fn reference_ref(env: Env, reference: Ref, result: *mut u32) -> Status; + + fn reference_unref(env: Env, reference: Ref, result: *mut u32) -> Status; + + fn get_reference_value(env: Env, reference: Ref, result: *mut Value) -> Status; + + fn strict_equals(env: Env, lhs: Value, rhs: Value, result: *mut bool) -> Status; + + fn create_external_arraybuffer( + env: Env, + data: *mut c_void, + length: usize, + finalize_cb: Finalize, + finalize_hint: *mut c_void, + result: *mut Value, + ) -> Status; + + fn create_external_buffer( + env: Env, + length: usize, + data: *mut c_void, + finalize_cb: Finalize, + finalize_hint: *mut c_void, + result: *mut Value, + ) -> Status; + } + ); } #[cfg(feature = "napi-4")] mod napi4 { - use std::os::raw::c_void; use super::super::types::*; + use std::os::raw::c_void; - generate!(extern "C" { - fn create_threadsafe_function( - env: Env, - func: Value, - async_resource: Value, - async_resource_name: Value, - max_queue_size: usize, - initial_thread_count: usize, - thread_finalize_data: *mut c_void, - thread_finalize_cb: Finalize, - context: *mut c_void, - call_js_cb: ThreadsafeFunctionCallJs, - result: *mut ThreadsafeFunction, - ) -> Status; - - fn call_threadsafe_function( - func: ThreadsafeFunction, - data: *mut c_void, - is_blocking: ThreadsafeFunctionCallMode, - ) -> Status; - - fn release_threadsafe_function( - func: ThreadsafeFunction, - mode: ThreadsafeFunctionReleaseMode, - ) -> Status; - - fn ref_threadsafe_function( - env: Env, - func: ThreadsafeFunction, - ) -> Status; - - fn unref_threadsafe_function( - env: Env, - func: ThreadsafeFunction, - ) -> Status; - }); + generate!( + extern "C" { + fn create_threadsafe_function( + env: Env, + func: Value, + async_resource: Value, + async_resource_name: Value, + max_queue_size: usize, + initial_thread_count: usize, + thread_finalize_data: *mut c_void, + thread_finalize_cb: Finalize, + context: *mut c_void, + call_js_cb: ThreadsafeFunctionCallJs, + result: *mut ThreadsafeFunction, + ) -> Status; + + fn call_threadsafe_function( + func: ThreadsafeFunction, + data: *mut c_void, + is_blocking: ThreadsafeFunctionCallMode, + ) -> Status; + + fn release_threadsafe_function( + func: ThreadsafeFunction, + mode: ThreadsafeFunctionReleaseMode, + ) -> Status; + + fn ref_threadsafe_function(env: Env, func: ThreadsafeFunction) -> Status; + + fn unref_threadsafe_function(env: Env, func: ThreadsafeFunction) -> Status; + } + ); } #[cfg(feature = "napi-5")] mod napi5 { use super::super::types::*; - generate!(extern "C" { - fn create_date(env: Env, value: f64, result: *mut Value) -> Status; + generate!( + extern "C" { + fn create_date(env: Env, value: f64, result: *mut Value) -> Status; - fn get_date_value(env: Env, value: Value, result: *mut f64) -> Status; + fn get_date_value(env: Env, value: Value, result: *mut f64) -> Status; - fn is_date(env: Env, value: Value, result: *mut bool) -> Status; - }); + fn is_date(env: Env, value: Value, result: *mut bool) -> Status; + } + ); } #[cfg(feature = "napi-6")] mod napi6 { use super::super::types::*; - generate!(extern "C" { - fn get_all_property_names( - env: Env, - object: Value, - key_mode: KeyCollectionMode, - key_filter: KeyFilter, - key_conversion: KeyConversion, - result: *mut Value, - ) -> Status; - }); + generate!( + extern "C" { + fn get_all_property_names( + env: Env, + object: Value, + key_mode: KeyCollectionMode, + key_filter: KeyFilter, + key_conversion: KeyConversion, + result: *mut Value, + ) -> Status; + } + ); } pub(crate) use napi1::*; @@ -322,10 +285,7 @@ unsafe fn get_version(host: &libloading::Library, env: Env) -> Result Status>(b"napi_get_version")?; let mut version = 0; - assert_eq!( - get_version(env, &mut version as *mut _), - Status::Ok, - ); + assert_eq!(get_version(env, &mut version as *mut _), Status::Ok,); Ok(version) } diff --git a/crates/neon-runtime/src/napi/bindings/mod.rs b/crates/neon-runtime/src/napi/bindings/mod.rs index 0d3671c5e..fba148c8d 100644 --- a/crates/neon-runtime/src/napi/bindings/mod.rs +++ b/crates/neon-runtime/src/napi/bindings/mod.rs @@ -171,8 +171,8 @@ use std::sync::Once; pub(crate) use functions::*; pub(crate) use types::*; -mod types; mod functions; +mod types; static SETUP: Once = Once::new(); diff --git a/crates/neon-runtime/src/napi/bindings/types.rs b/crates/neon-runtime/src/napi/bindings/types.rs index 4d96dde32..8a82f3f34 100644 --- a/crates/neon-runtime/src/napi/bindings/types.rs +++ b/crates/neon-runtime/src/napi/bindings/types.rs @@ -57,26 +57,14 @@ pub struct ThreadsafeFunction__ { #[cfg(feature = "napi-4")] pub type ThreadsafeFunction = *mut ThreadsafeFunction__; -pub(crate) type Callback = Option< - unsafe extern "C" fn(env: Env, info: CallbackInfo) -> Value, ->; +pub(crate) type Callback = Option Value>; -pub(crate) type Finalize = Option< - unsafe extern "C" fn( - env: Env, - finalize_data: *mut c_void, - finalize_hint: *mut c_void, - ), ->; +pub(crate) type Finalize = + Option; #[cfg(feature = "napi-4")] pub type ThreadsafeFunctionCallJs = Option< - unsafe extern "C" fn( - env: Env, - js_callback: Value, - context: *mut c_void, - data: *mut c_void, - ), + unsafe extern "C" fn(env: Env, js_callback: Value, context: *mut c_void, data: *mut c_void), >; #[allow(dead_code)] diff --git a/crates/neon-runtime/src/napi/call.rs b/crates/neon-runtime/src/napi/call.rs index 8b19e77b4..a8c917d53 100644 --- a/crates/neon-runtime/src/napi/call.rs +++ b/crates/neon-runtime/src/napi/call.rs @@ -4,20 +4,20 @@ use std::ptr::null_mut; use smallvec::{smallvec, SmallVec}; -use crate::raw::{FunctionCallbackInfo, Env, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, FunctionCallbackInfo, Local}; #[repr(C)] pub struct CCallback { pub static_callback: *mut c_void, - pub dynamic_callback: *mut c_void + pub dynamic_callback: *mut c_void, } impl Default for CCallback { fn default() -> Self { CCallback { static_callback: null_mut(), - dynamic_callback: null_mut() + dynamic_callback: null_mut(), } } } @@ -25,11 +25,7 @@ impl Default for CCallback { pub unsafe fn is_construct(env: Env, info: FunctionCallbackInfo) -> bool { let mut target: MaybeUninit = MaybeUninit::zeroed(); - let status = napi::get_new_target( - env, - info, - target.as_mut_ptr() - ); + let status = napi::get_new_target(env, info, target.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -43,14 +39,7 @@ pub unsafe fn is_construct(env: Env, info: FunctionCallbackInfo) -> bool { } pub unsafe fn this(env: Env, info: FunctionCallbackInfo, out: &mut Local) { - let status = napi::get_cb_info( - env, - info, - null_mut(), - null_mut(), - out as *mut _, - null_mut(), - ); + let status = napi::get_cb_info(env, info, null_mut(), null_mut(), out as *mut _, null_mut()); assert_eq!(status, napi::Status::Ok); } diff --git a/crates/neon-runtime/src/napi/date.rs b/crates/neon-runtime/src/napi/date.rs index 0da2ef142..c63395d4b 100644 --- a/crates/neon-runtime/src/napi/date.rs +++ b/crates/neon-runtime/src/napi/date.rs @@ -1,6 +1,6 @@ -use std::mem::MaybeUninit; use crate::napi::bindings as napi; use crate::raw::{Env, Local}; +use std::mem::MaybeUninit; /// Create a new date object /// diff --git a/crates/neon-runtime/src/napi/error.rs b/crates/neon-runtime/src/napi/error.rs index 2cbdb6256..f46927807 100644 --- a/crates/neon-runtime/src/napi/error.rs +++ b/crates/neon-runtime/src/napi/error.rs @@ -50,12 +50,7 @@ pub unsafe fn throw(env: Env, val: Local) { pub unsafe fn new_error(env: Env, out: &mut Local, msg: Local) { let mut result = MaybeUninit::uninit(); - let status = napi::create_error( - env, - ptr::null_mut(), - msg, - result.as_mut_ptr(), - ); + let status = napi::create_error(env, ptr::null_mut(), msg, result.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -64,12 +59,7 @@ pub unsafe fn new_error(env: Env, out: &mut Local, msg: Local) { pub unsafe fn new_type_error(env: Env, out: &mut Local, msg: Local) { let mut result = MaybeUninit::uninit(); - let status = napi::create_type_error( - env, - ptr::null_mut(), - msg, - result.as_mut_ptr(), - ); + let status = napi::create_type_error(env, ptr::null_mut(), msg, result.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -78,12 +68,7 @@ pub unsafe fn new_type_error(env: Env, out: &mut Local, msg: Local) { pub unsafe fn new_range_error(env: Env, out: &mut Local, msg: Local) { let mut result = MaybeUninit::uninit(); - let status = napi::create_range_error( - env, - ptr::null_mut(), - msg, - result.as_mut_ptr(), - ); + let status = napi::create_range_error(env, ptr::null_mut(), msg, result.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -92,22 +77,12 @@ pub unsafe fn new_range_error(env: Env, out: &mut Local, msg: Local) { pub unsafe fn throw_error_from_utf8(env: Env, msg: *const u8, len: i32) { let mut out = MaybeUninit::uninit(); - let status = napi::create_string_utf8( - env, - msg as *const _, - len as usize, - out.as_mut_ptr(), - ); + let status = napi::create_string_utf8(env, msg as *const _, len as usize, out.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); let mut err = MaybeUninit::uninit(); - let status = napi::create_error( - env, - ptr::null_mut(), - out.assume_init(), - err.as_mut_ptr(), - ); + let status = napi::create_error(env, ptr::null_mut(), out.assume_init(), err.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); diff --git a/crates/neon-runtime/src/napi/external.rs b/crates/neon-runtime/src/napi/external.rs index ff7868dfa..1f32a2001 100644 --- a/crates/neon-runtime/src/napi/external.rs +++ b/crates/neon-runtime/src/napi/external.rs @@ -1,7 +1,7 @@ use std::mem::MaybeUninit; -use crate::raw::{Env, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, Local}; /// `finalize_external` is invoked immediately before a `napi_external` is garbage collected extern "C" fn finalize_external( @@ -25,16 +25,9 @@ extern "C" fn finalize_external( /// module. Calling `deref` with an external created by another native module, /// even another neon module, is undefined behavior. /// https://github.com/neon-bindings/neon/issues/591 -pub unsafe fn deref( - env: Env, - local: Local, -) -> Option<*const T> { +pub unsafe fn deref(env: Env, local: Local) -> Option<*const T> { let mut result = MaybeUninit::uninit(); - let status = napi::typeof_value( - env, - local, - result.as_mut_ptr(), - ); + let status = napi::typeof_value(env, local, result.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -49,11 +42,7 @@ pub unsafe fn deref( } let mut result = MaybeUninit::uninit(); - let status = napi::get_value_external( - env, - local, - result.as_mut_ptr(), - ); + let status = napi::get_value_external(env, local, result.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -61,11 +50,7 @@ pub unsafe fn deref( } /// Creates a `napi_external` from a Rust type -pub unsafe fn create( - env: Env, - v: T, - finalizer: fn(Env, T), -) -> Local { +pub unsafe fn create(env: Env, v: T, finalizer: fn(Env, T)) -> Local { let v = Box::new(v); let mut result = MaybeUninit::uninit(); diff --git a/crates/neon-runtime/src/napi/fun.rs b/crates/neon-runtime/src/napi/fun.rs index 79dcebb6b..f05ab51b5 100644 --- a/crates/neon-runtime/src/napi/fun.rs +++ b/crates/neon-runtime/src/napi/fun.rs @@ -4,8 +4,8 @@ use std::os::raw::c_void; use std::ptr::null; use crate::call::CCallback; -use crate::raw::{Env, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, Local}; /// Mutates the `out` argument provided to refer to a newly created `v8::Function`. Returns /// `false` if the value couldn't be created. @@ -26,13 +26,33 @@ pub unsafe fn get_dynamic_callback(_env: Env, data: *mut c_void) -> *mut c_void data } -pub unsafe fn call(out: &mut Local, env: Env, fun: Local, this: Local, argc: i32, argv: *mut c_void) -> bool { - let status = napi::call_function(env, this, fun, argc as usize, argv as *const _, out as *mut _); +pub unsafe fn call( + out: &mut Local, + env: Env, + fun: Local, + this: Local, + argc: i32, + argv: *mut c_void, +) -> bool { + let status = napi::call_function( + env, + this, + fun, + argc as usize, + argv as *const _, + out as *mut _, + ); status == napi::Status::Ok } -pub unsafe fn construct(out: &mut Local, env: Env, fun: Local, argc: i32, argv: *mut c_void) -> bool { +pub unsafe fn construct( + out: &mut Local, + env: Env, + fun: Local, + argc: i32, + argv: *mut c_void, +) -> bool { let status = napi::new_instance(env, fun, argc as usize, argv as *const _, out as *mut _); status == napi::Status::Ok diff --git a/crates/neon-runtime/src/napi/mem.rs b/crates/neon-runtime/src/napi/mem.rs index 8126aba2e..9cd239d48 100644 --- a/crates/neon-runtime/src/napi/mem.rs +++ b/crates/neon-runtime/src/napi/mem.rs @@ -1,8 +1,11 @@ -use crate::raw::{Env, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, Local}; pub unsafe fn strict_equals(env: Env, lhs: Local, rhs: Local) -> bool { let mut result = false; - assert_eq!(napi::strict_equals(env, lhs, rhs, &mut result as *mut _), napi::Status::Ok); + assert_eq!( + napi::strict_equals(env, lhs, rhs, &mut result as *mut _), + napi::Status::Ok + ); result } diff --git a/crates/neon-runtime/src/napi/mod.rs b/crates/neon-runtime/src/napi/mod.rs index ed27b850e..5e9a96d58 100644 --- a/crates/neon-runtime/src/napi/mod.rs +++ b/crates/neon-runtime/src/napi/mod.rs @@ -3,6 +3,8 @@ pub mod arraybuffer; pub mod buffer; pub mod call; pub mod convert; +#[cfg(feature = "napi-5")] +pub mod date; pub mod error; pub mod external; pub mod fun; @@ -10,12 +12,10 @@ pub mod mem; pub mod object; pub mod primitive; pub mod raw; +pub mod reference; pub mod scope; pub mod string; pub mod tag; -pub mod reference; -#[cfg(feature = "napi-5")] -pub mod date; #[cfg(feature = "napi-4")] pub mod tsfn; diff --git a/crates/neon-runtime/src/napi/object.rs b/crates/neon-runtime/src/napi/object.rs index a503bb152..b5e96953a 100644 --- a/crates/neon-runtime/src/napi/object.rs +++ b/crates/neon-runtime/src/napi/object.rs @@ -21,7 +21,8 @@ pub unsafe fn get_own_property_names(out: &mut Local, env: Env, object: Local) - napi::KeyFilter::ALL_PROPERTIES | napi::KeyFilter::SKIP_SYMBOLS, napi::KeyConversion::NumbersToStrings, property_names.as_mut_ptr(), - ) != napi::Status::Ok { + ) != napi::Status::Ok + { return false; } @@ -52,7 +53,13 @@ pub unsafe fn set_index(out: &mut bool, env: Env, object: Local, index: u32, val } /// Mutate the `out` argument to refer to the value at a named `key` in the given `object`. Returns `false` if the value couldn't be retrieved. -pub unsafe fn get_string(env: Env, out: &mut Local, object: Local, key: *const u8, len: i32) -> bool { +pub unsafe fn get_string( + env: Env, + out: &mut Local, + object: Local, + key: *const u8, + len: i32, +) -> bool { let mut key_val = MaybeUninit::uninit(); // Not using `crate::string::new()` because it requires a _reference_ to a Local, @@ -64,9 +71,7 @@ pub unsafe fn get_string(env: Env, out: &mut Local, object: Local, key: *const u } // Not using napi_get_named_property() because the `key` may not be null terminated. - if napi::get_property(env, object, key_val.assume_init(), out as *mut _) - != napi::Status::Ok - { + if napi::get_property(env, object, key_val.assume_init(), out as *mut _) != napi::Status::Ok { return false; } @@ -79,7 +84,14 @@ pub unsafe fn get_string(env: Env, out: &mut Local, object: Local, key: *const u /// see [discussion]. /// /// [discussion]: https://github.com/neon-bindings/neon/pull/458#discussion_r344827965 -pub unsafe fn set_string(env: Env, out: &mut bool, object: Local, key: *const u8, len: i32, val: Local) -> bool { +pub unsafe fn set_string( + env: Env, + out: &mut bool, + object: Local, + key: *const u8, + len: i32, + val: Local, +) -> bool { let mut key_val = MaybeUninit::uninit(); *out = true; @@ -91,9 +103,7 @@ pub unsafe fn set_string(env: Env, out: &mut bool, object: Local, key: *const u8 return false; } - if napi::set_property(env, object, key_val.assume_init(), val) - != napi::Status::Ok - { + if napi::set_property(env, object, key_val.assume_init(), val) != napi::Status::Ok { *out = false; return false; } diff --git a/crates/neon-runtime/src/napi/primitive.rs b/crates/neon-runtime/src/napi/primitive.rs index dac5f06f1..2df6f19ee 100644 --- a/crates/neon-runtime/src/napi/primitive.rs +++ b/crates/neon-runtime/src/napi/primitive.rs @@ -1,5 +1,5 @@ -use crate::raw::{Local, Env}; use crate::napi::bindings as napi; +use crate::raw::{Env, Local}; /// Mutates the `out` argument provided to refer to the global `undefined` object. pub unsafe fn undefined(out: &mut Local, env: Env) { @@ -20,7 +20,10 @@ pub unsafe fn boolean(out: &mut Local, env: Env, b: bool) { /// boolean, this function panics. pub unsafe fn boolean_value(env: Env, p: Local) -> bool { let mut value = false; - assert_eq!(napi::get_value_bool(env, p, &mut value as *mut bool), napi::Status::Ok); + assert_eq!( + napi::get_value_bool(env, p, &mut value as *mut bool), + napi::Status::Ok + ); value } @@ -34,6 +37,9 @@ pub unsafe fn number(out: &mut Local, env: Env, v: f64) { /// the given `Local` is not a number. pub unsafe fn number_value(env: Env, p: Local) -> f64 { let mut value = 0.0; - assert_eq!(napi::get_value_double(env, p, &mut value as *mut f64), napi::Status::Ok); + assert_eq!( + napi::get_value_double(env, p, &mut value as *mut f64), + napi::Status::Ok + ); value } diff --git a/crates/neon-runtime/src/napi/raw.rs b/crates/neon-runtime/src/napi/raw.rs index fd9d75b49..6f849a40b 100644 --- a/crates/neon-runtime/src/napi/raw.rs +++ b/crates/neon-runtime/src/napi/raw.rs @@ -11,11 +11,15 @@ pub type Env = napi::Env; #[repr(C)] #[derive(Clone, Copy)] pub struct HandleScope { - pub word: napi::HandleScope + pub word: napi::HandleScope, } impl HandleScope { - pub fn new() -> Self { Self { word: ptr::null_mut() } } + pub fn new() -> Self { + Self { + word: ptr::null_mut(), + } + } } impl Default for HandleScope { @@ -27,11 +31,15 @@ impl Default for HandleScope { #[repr(C)] #[derive(Clone, Copy)] pub struct EscapableHandleScope { - pub word: napi::EscapableHandleScope + pub word: napi::EscapableHandleScope, } impl EscapableHandleScope { - pub fn new() -> Self { Self { word: ptr::null_mut() } } + pub fn new() -> Self { + Self { + word: ptr::null_mut(), + } + } } impl Default for EscapableHandleScope { diff --git a/crates/neon-runtime/src/napi/reference.rs b/crates/neon-runtime/src/napi/reference.rs index b867da10c..9166fa3cb 100644 --- a/crates/neon-runtime/src/napi/reference.rs +++ b/crates/neon-runtime/src/napi/reference.rs @@ -2,7 +2,7 @@ use std::mem::MaybeUninit; use crate::napi::bindings as napi; -use crate::raw::{Local, Env}; +use crate::raw::{Env, Local}; pub unsafe fn new(env: Env, value: Local) -> napi::Ref { let mut result = MaybeUninit::uninit(); diff --git a/crates/neon-runtime/src/napi/scope.rs b/crates/neon-runtime/src/napi/scope.rs index 73f5b305d..de88d7eef 100644 --- a/crates/neon-runtime/src/napi/scope.rs +++ b/crates/neon-runtime/src/napi/scope.rs @@ -1,8 +1,7 @@ - use std::mem::MaybeUninit; -use crate::raw::{Env, HandleScope, EscapableHandleScope, InheritedHandleScope, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, EscapableHandleScope, HandleScope, InheritedHandleScope, Local}; // TODO: This leaves a lot of room for UB; we can have a cleaner // implementation for N-API. @@ -13,7 +12,9 @@ pub trait Root { } impl Root for HandleScope { - unsafe fn allocate() -> Self { HandleScope::new() } + unsafe fn allocate() -> Self { + HandleScope::new() + } unsafe fn enter(&mut self, env: Env) { let mut scope = MaybeUninit::uninit(); let status = napi::open_handle_scope(env, scope.as_mut_ptr()); @@ -30,7 +31,9 @@ impl Root for HandleScope { } impl Root for EscapableHandleScope { - unsafe fn allocate() -> Self { EscapableHandleScope::new() } + unsafe fn allocate() -> Self { + EscapableHandleScope::new() + } unsafe fn enter(&mut self, env: Env) { let mut scope = MaybeUninit::uninit(); let status = napi::open_escapable_handle_scope(env, scope.as_mut_ptr()); @@ -47,9 +50,11 @@ impl Root for EscapableHandleScope { } impl Root for InheritedHandleScope { - unsafe fn allocate() -> Self { InheritedHandleScope } - unsafe fn enter(&mut self, _: Env) { } - unsafe fn exit(&mut self, _: Env) { } + unsafe fn allocate() -> Self { + InheritedHandleScope + } + unsafe fn enter(&mut self, _: Env) {} + unsafe fn exit(&mut self, _: Env) {} } pub unsafe fn escape(env: Env, out: &mut Local, scope: *mut EscapableHandleScope, value: Local) { @@ -59,5 +64,8 @@ pub unsafe fn escape(env: Env, out: &mut Local, scope: *mut EscapableHandleScope } pub unsafe fn get_global(env: Env, out: &mut Local) { - assert_eq!(crate::napi::bindings::get_global(env, out as *mut _), napi::Status::Ok); + assert_eq!( + crate::napi::bindings::get_global(env, out as *mut _), + napi::Status::Ok + ); } diff --git a/crates/neon-runtime/src/napi/string.rs b/crates/neon-runtime/src/napi/string.rs index a2872bc42..4a1d74efc 100644 --- a/crates/neon-runtime/src/napi/string.rs +++ b/crates/neon-runtime/src/napi/string.rs @@ -1,29 +1,18 @@ use std::mem::MaybeUninit; use std::ptr; -use crate::raw::{Env, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, Local}; pub unsafe fn new(out: &mut Local, env: Env, data: *const u8, len: i32) -> bool { - let status = napi::create_string_utf8( - env, - data as *const _, - len as usize, - out, - ); + let status = napi::create_string_utf8(env, data as *const _, len as usize, out); status == napi::Status::Ok } pub unsafe fn utf8_len(env: Env, value: Local) -> isize { let mut len = MaybeUninit::uninit(); - let status = napi::get_value_string_utf8( - env, - value, - ptr::null_mut(), - 0, - len.as_mut_ptr(), - ); + let status = napi::get_value_string_utf8(env, value, ptr::null_mut(), 0, len.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); @@ -32,13 +21,8 @@ pub unsafe fn utf8_len(env: Env, value: Local) -> isize { pub unsafe fn data(env: Env, out: *mut u8, len: isize, value: Local) -> isize { let mut read = MaybeUninit::uninit(); - let status = napi::get_value_string_utf8( - env, - value, - out as *mut _, - len as usize, - read.as_mut_ptr(), - ); + let status = + napi::get_value_string_utf8(env, value, out as *mut _, len as usize, read.as_mut_ptr()); assert_eq!(status, napi::Status::Ok); diff --git a/crates/neon-runtime/src/napi/tag.rs b/crates/neon-runtime/src/napi/tag.rs index 0c4ef307d..d0cd048b3 100644 --- a/crates/neon-runtime/src/napi/tag.rs +++ b/crates/neon-runtime/src/napi/tag.rs @@ -1,10 +1,13 @@ -use crate::raw::{Env, Local}; use crate::napi::bindings as napi; +use crate::raw::{Env, Local}; /// Return true if an `napi_value` `val` has the expected value type. unsafe fn is_type(env: Env, val: Local, expect: napi::ValueType) -> bool { let mut actual = napi::ValueType::Undefined; - assert_eq!(napi::typeof_value(env, val, &mut actual as *mut _), napi::Status::Ok); + assert_eq!( + napi::typeof_value(env, val, &mut actual as *mut _), + napi::Status::Ok + ); actual == expect } @@ -37,7 +40,10 @@ pub unsafe fn is_object(env: Env, val: Local) -> bool { pub unsafe fn is_array(env: Env, val: Local) -> bool { let mut result = false; - assert_eq!(napi::is_array(env, val, &mut result as *mut _), napi::Status::Ok); + assert_eq!( + napi::is_array(env, val, &mut result as *mut _), + napi::Status::Ok + ); result } @@ -47,27 +53,39 @@ pub unsafe fn is_function(env: Env, val: Local) -> bool { pub unsafe fn is_error(env: Env, val: Local) -> bool { let mut result = false; - assert_eq!(napi::is_error(env, val, &mut result as *mut _), napi::Status::Ok); + assert_eq!( + napi::is_error(env, val, &mut result as *mut _), + napi::Status::Ok + ); result } /// Is `val` a Node.js Buffer instance? pub unsafe fn is_buffer(env: Env, val: Local) -> bool { let mut result = false; - assert_eq!(napi::is_buffer(env, val, &mut result as *mut _), napi::Status::Ok); + assert_eq!( + napi::is_buffer(env, val, &mut result as *mut _), + napi::Status::Ok + ); result } /// Is `val` an ArrayBuffer instance? pub unsafe fn is_arraybuffer(env: Env, val: Local) -> bool { let mut result = false; - assert_eq!(napi::is_arraybuffer(env, val, &mut result as *mut _), napi::Status::Ok); + assert_eq!( + napi::is_arraybuffer(env, val, &mut result as *mut _), + napi::Status::Ok + ); result } #[cfg(feature = "napi-5")] pub unsafe fn is_date(env: Env, val: Local) -> bool { let mut result = false; - assert_eq!(napi::is_date(env, val, &mut result as *mut _), napi::Status::Ok); + assert_eq!( + napi::is_date(env, val, &mut result as *mut _), + napi::Status::Ok + ); result } diff --git a/crates/neon-runtime/src/napi/tsfn.rs b/crates/neon-runtime/src/napi/tsfn.rs index e14002a07..271a46511 100644 --- a/crates/neon-runtime/src/napi/tsfn.rs +++ b/crates/neon-runtime/src/napi/tsfn.rs @@ -4,7 +4,7 @@ use std::ffi::c_void; use std::mem::MaybeUninit; use crate::napi::bindings as napi; -use crate::raw::{Local, Env}; +use crate::raw::{Env, Local}; unsafe fn string(env: Env, s: impl AsRef) -> Local { let s = s.as_ref(); @@ -64,10 +64,7 @@ impl CallError { impl ThreadsafeFunction { /// Creates a new unbounded N-API Threadsafe Function /// Safety: `Env` must be valid for the current thread - pub unsafe fn new( - env: Env, - callback: fn(Option, T), - ) -> Self { + pub unsafe fn new(env: Env, callback: fn(Option, T)) -> Self { Self::with_capacity(env, 0, callback) } @@ -98,7 +95,7 @@ impl ThreadsafeFunction { ), napi::Status::Ok, ); - + Self { tsfn: Tsfn(result.assume_init()), callback, @@ -111,21 +108,15 @@ impl ThreadsafeFunction { data: T, is_blocking: Option, ) -> Result<(), CallError> { - let is_blocking = is_blocking - .unwrap_or(napi::ThreadsafeFunctionCallMode::Blocking); + let is_blocking = is_blocking.unwrap_or(napi::ThreadsafeFunctionCallMode::Blocking); let callback = Box::into_raw(Box::new(Callback { callback: self.callback, data, })); - let status = unsafe { - napi::call_threadsafe_function( - self.tsfn.0, - callback as *mut _, - is_blocking, - ) - }; + let status = + unsafe { napi::call_threadsafe_function(self.tsfn.0, callback as *mut _, is_blocking) }; if status == napi::Status::Ok { Ok(()) @@ -144,10 +135,7 @@ impl ThreadsafeFunction { /// Safety: `Env` must be valid for the current thread pub unsafe fn reference(&mut self, env: Env) { assert_eq!( - napi::ref_threadsafe_function( - env, - self.tsfn.0, - ), + napi::ref_threadsafe_function(env, self.tsfn.0,), napi::Status::Ok, ); } @@ -156,10 +144,7 @@ impl ThreadsafeFunction { /// Safety: `Env` must be valid for the current thread pub unsafe fn unref(&mut self, env: Env) { assert_eq!( - napi::unref_threadsafe_function( - env, - self.tsfn.0, - ), + napi::unref_threadsafe_function(env, self.tsfn.0,), napi::Status::Ok, ); } @@ -171,17 +156,10 @@ impl ThreadsafeFunction { _context: *mut c_void, data: *mut c_void, ) { - let Callback { - callback, - data, - } = *Box::from_raw(data as *mut Callback); + let Callback { callback, data } = *Box::from_raw(data as *mut Callback); // Event loop has terminated - let env = if env.is_null() { - None - } else { - Some(env) - }; + let env = if env.is_null() { None } else { Some(env) }; callback(env, data); } diff --git a/crates/neon-sys/build.rs b/crates/neon-sys/build.rs index b2fc57e66..922f71fe1 100644 --- a/crates/neon-sys/build.rs +++ b/crates/neon-sys/build.rs @@ -12,11 +12,11 @@ mod build { #[cfg(not(feature = "docs-only"))] mod build { - use std::process::Command; + use regex::Regex; use std::env; use std::fs; use std::path::Path; - use regex::Regex; + use std::process::Command; pub fn main() { let out_dir = env::var("OUT_DIR").unwrap(); @@ -94,7 +94,8 @@ mod build { // // gyp verb architecture ia32 fn parse_node_arch(node_gyp_output: &str) -> String { - let version_regex = Regex::new(r"gyp verb architecture (?Pia32|x64|arm|arm64)").unwrap(); + let version_regex = + Regex::new(r"gyp verb architecture (?Pia32|x64|arm|arm64)").unwrap(); let captures = version_regex.captures(&node_gyp_output).unwrap(); String::from(&captures["arch"]) } @@ -109,7 +110,10 @@ mod build { .find(node_root_dir_flag_pattern) .map(|i| i + node_root_dir_flag_pattern.len()) .expect("Couldn't find node_root_dir in node-gyp output."); - let node_root_dir_end_index = node_gyp_output[node_root_dir_start_index..].find('\'').unwrap() + node_root_dir_start_index; + let node_root_dir_end_index = node_gyp_output[node_root_dir_start_index..] + .find('\'') + .unwrap() + + node_root_dir_start_index; &node_gyp_output[node_root_dir_start_index..node_root_dir_end_index] } @@ -131,7 +135,10 @@ mod build { .find(node_lib_file_flag_pattern) .map(|i| i + node_lib_file_flag_pattern.len()) .expect("Couldn't find node_lib_file in node-gyp output."); - let node_lib_file_end_index = node_gyp_output[node_lib_file_start_index..].find('\'').unwrap() + node_lib_file_start_index; + let node_lib_file_end_index = node_gyp_output[node_lib_file_start_index..] + .find('\'') + .unwrap() + + node_lib_file_start_index; &node_gyp_output[node_lib_file_start_index..node_lib_file_end_index] } @@ -147,11 +154,21 @@ mod build { } // Ensure that all package.json dependencies and dev dependencies are installed. - npm(native_dir).args(&["install", "--silent"]).status().expect("Failed to run \"npm install\" for neon-sys!"); + npm(native_dir) + .args(&["install", "--silent"]) + .status() + .expect("Failed to run \"npm install\" for neon-sys!"); // Run `node-gyp configure` in verbose mode to read node_root_dir on Windows. let output = npm(native_dir) - .args(&["run", if debug() { "configure-debug" } else { "configure-release" }]) + .args(&[ + "run", + if debug() { + "configure-debug" + } else { + "configure-release" + }, + ]) .output() .expect("Failed to run \"node-gyp configure\" for neon-sys!"); @@ -165,18 +182,34 @@ mod build { if cfg!(windows) { let node_gyp_output = String::from_utf8_lossy(&output.stderr); - println!("cargo:node_root_dir={}", parse_node_root_dir(&node_gyp_output)); - println!("cargo:node_lib_file={}", parse_node_lib_file(&node_gyp_output)); + println!( + "cargo:node_root_dir={}", + parse_node_root_dir(&node_gyp_output) + ); + println!( + "cargo:node_lib_file={}", + parse_node_lib_file(&node_gyp_output) + ); } // Run `node-gyp build`. let build_output = npm(native_dir) - .args(&["run", if debug() { "build-debug" } else { "build-release" }]) + .args(&[ + "run", + if debug() { + "build-debug" + } else { + "build-release" + }, + ]) .output() .expect("Failed to run \"node-gyp build\" for neon-sys!"); let node_gyp_build_output = String::from_utf8_lossy(&build_output.stderr); - println!("cargo:node_arch={}", parse_node_arch(&node_gyp_build_output)); + println!( + "cargo:node_arch={}", + parse_node_arch(&node_gyp_build_output) + ); } // Link the built object file into a static library. @@ -205,7 +238,10 @@ mod build { } }; - cc::Build::new().cpp(true).object(object_path).compile("libneon.a"); + cc::Build::new() + .cpp(true) + .object(object_path) + .compile("libneon.a"); } #[cfg(unix)] @@ -236,7 +272,7 @@ mod build { fn debug() -> bool { match env::var("DEBUG") { Ok(s) => s == "true", - Err(_) => false + Err(_) => false, } } } diff --git a/crates/neon-sys/src/lib.rs b/crates/neon-sys/src/lib.rs index ff95c73e7..d7910b618 100644 --- a/crates/neon-sys/src/lib.rs +++ b/crates/neon-sys/src/lib.rs @@ -1,5 +1,5 @@ -use std::os::raw::c_void; use std::mem; +use std::os::raw::c_void; use std::ptr::null_mut; /// A V8 `Local` handle. @@ -9,7 +9,7 @@ use std::ptr::null_mut; #[repr(C)] #[derive(Clone, Copy)] pub struct Local { - pub handle: *mut c_void + pub handle: *mut c_void, } /// Represents the details of how the function was called from JavaScript. @@ -38,11 +38,13 @@ const HANDLE_SCOPE_SIZE: usize = 24; #[derive(Clone, Copy)] pub struct HandleScope { pub align_to_pointer: [*mut c_void; 0], - pub fields: [u8; HANDLE_SCOPE_SIZE] + pub fields: [u8; HANDLE_SCOPE_SIZE], } impl HandleScope { - pub fn new() -> HandleScope { unsafe { mem::zeroed() } } + pub fn new() -> HandleScope { + unsafe { mem::zeroed() } + } } impl Default for HandleScope { @@ -62,11 +64,13 @@ const ESCAPABLE_HANDLE_SCOPE_SIZE: usize = 32; #[derive(Clone, Copy)] pub struct EscapableHandleScope { pub align_to_pointer: [*mut c_void; 0], - pub fields: [u8; ESCAPABLE_HANDLE_SCOPE_SIZE] + pub fields: [u8; ESCAPABLE_HANDLE_SCOPE_SIZE], } impl EscapableHandleScope { - pub fn new() -> EscapableHandleScope { unsafe { mem::zeroed() } } + pub fn new() -> EscapableHandleScope { + unsafe { mem::zeroed() } + } } impl Default for EscapableHandleScope { @@ -78,14 +82,14 @@ impl Default for EscapableHandleScope { #[repr(C)] pub struct CCallback { pub static_callback: *mut c_void, - pub dynamic_callback: *mut c_void + pub dynamic_callback: *mut c_void, } impl Default for CCallback { fn default() -> Self { CCallback { static_callback: null_mut(), - dynamic_callback: null_mut() + dynamic_callback: null_mut(), } } } @@ -95,7 +99,7 @@ pub enum TryCatchControl { Returned = 0, Threw = 1, Panicked = 2, - UnexpectedErr = 3 + UnexpectedErr = 3, } #[derive(Clone, Copy)] @@ -107,10 +111,12 @@ pub struct InheritedHandleScope; /// function returns `TryCatchControl::Returned`. /// The `unwind_value` argument can be assumed to be initialized if and only if the /// glue function returns `TryCatchControl::Panicked`. -pub type TryCatchGlue = extern fn(rust_thunk: *mut c_void, - cx: *mut c_void, - result: *mut c_void, - unwind_value: *mut *mut c_void) -> TryCatchControl; +pub type TryCatchGlue = extern "C" fn( + rust_thunk: *mut c_void, + cx: *mut c_void, + result: *mut c_void, + unwind_value: *mut *mut c_void, +) -> TryCatchControl; extern "C" { @@ -118,11 +124,19 @@ extern "C" { pub fn Neon_Array_Length(isolate: Isolate, array: Local) -> u32; pub fn Neon_ArrayBuffer_New(out: &mut Local, isolate: Isolate, size: u32) -> bool; - pub fn Neon_ArrayBuffer_Data<'a, 'b>(isolate: Isolate, base_out: &'a mut *mut c_void, obj: Local) -> usize; + pub fn Neon_ArrayBuffer_Data<'a, 'b>( + isolate: Isolate, + base_out: &'a mut *mut c_void, + obj: Local, + ) -> usize; pub fn Neon_Buffer_New(isolate: Isolate, out: &mut Local, size: u32) -> bool; pub fn Neon_Buffer_Uninitialized(isolate: Isolate, out: &mut Local, size: u32) -> bool; - pub fn Neon_Buffer_Data<'a, 'b>(isolate: Isolate, base_out: &'a mut *mut c_void, obj: Local) -> usize; + pub fn Neon_Buffer_Data<'a, 'b>( + isolate: Isolate, + base_out: &'a mut *mut c_void, + obj: Local, + ) -> usize; pub fn Neon_Call_SetReturn(info: FunctionCallbackInfo, value: Local); pub fn Neon_Call_GetIsolate(info: FunctionCallbackInfo) -> Isolate; @@ -135,17 +149,38 @@ extern "C" { pub fn Neon_Class_GetClassMap(isolate: Isolate) -> *mut c_void; pub fn Neon_Class_SetClassMap(isolate: Isolate, map: *mut c_void, free_map: *mut c_void); - pub fn Neon_Class_CreateBase(isolate: Isolate, - allocate: CCallback, - construct: CCallback, - call: CCallback, - drop: extern "C" fn(*mut c_void)) -> *mut c_void; - pub fn Neon_Class_GetName<'a>(base_out: &'a mut *mut u8, isolate: Isolate, metadata: *const c_void) -> usize; - pub fn Neon_Class_SetName(isolate: Isolate, metadata: *mut c_void, name: *const u8, byte_length: u32) -> bool; + pub fn Neon_Class_CreateBase( + isolate: Isolate, + allocate: CCallback, + construct: CCallback, + call: CCallback, + drop: extern "C" fn(*mut c_void), + ) -> *mut c_void; + pub fn Neon_Class_GetName<'a>( + base_out: &'a mut *mut u8, + isolate: Isolate, + metadata: *const c_void, + ) -> usize; + pub fn Neon_Class_SetName( + isolate: Isolate, + metadata: *mut c_void, + name: *const u8, + byte_length: u32, + ) -> bool; pub fn Neon_Class_ThrowCallError(isolate: Isolate, metadata: *mut c_void); pub fn Neon_Class_ThrowThisError(isolate: Isolate, metadata: *mut c_void); - pub fn Neon_Class_AddMethod(isolate: Isolate, metadata: *mut c_void, name: *const u8, byte_length: u32, method: Local) -> bool; - pub fn Neon_Class_MetadataToConstructor(out: &mut Local, isolate: Isolate, metadata: *mut c_void) -> bool; + pub fn Neon_Class_AddMethod( + isolate: Isolate, + metadata: *mut c_void, + name: *const u8, + byte_length: u32, + method: Local, + ) -> bool; + pub fn Neon_Class_MetadataToConstructor( + out: &mut Local, + isolate: Isolate, + metadata: *mut c_void, + ) -> bool; pub fn Neon_Class_GetAllocateKernel(data: *mut c_void) -> *mut c_void; pub fn Neon_Class_GetConstructKernel(data: *mut c_void) -> *mut c_void; pub fn Neon_Class_GetCallKernel(data: *mut c_void) -> *mut c_void; @@ -165,22 +200,52 @@ extern "C" { pub fn Neon_Fun_New(out: &mut Local, isolate: Isolate, callback: CCallback) -> bool; pub fn Neon_Fun_Template_New(out: &mut Local, isolate: Isolate, callback: CCallback) -> bool; pub fn Neon_Fun_GetDynamicCallback(isolate: Isolate, data: *mut c_void) -> *mut c_void; - pub fn Neon_Fun_Call(out: &mut Local, isolate: Isolate, fun: Local, this: Local, argc: i32, argv: *mut c_void) -> bool; - pub fn Neon_Fun_Construct(out: &mut Local, isolate: Isolate, fun: Local, argc: i32, argv: *mut c_void) -> bool; + pub fn Neon_Fun_Call( + out: &mut Local, + isolate: Isolate, + fun: Local, + this: Local, + argc: i32, + argv: *mut c_void, + ) -> bool; + pub fn Neon_Fun_Construct( + out: &mut Local, + isolate: Isolate, + fun: Local, + argc: i32, + argv: *mut c_void, + ) -> bool; pub fn Neon_Mem_SameHandle(h1: Local, h2: Local) -> bool; - pub fn Neon_Module_ExecKernel(kernel: *mut c_void, callback: extern fn(*mut c_void, *mut c_void, *mut c_void, *mut c_void), exports: Local, scope: *mut c_void, vm: *mut c_void); + pub fn Neon_Module_ExecKernel( + kernel: *mut c_void, + callback: extern "C" fn(*mut c_void, *mut c_void, *mut c_void, *mut c_void), + exports: Local, + scope: *mut c_void, + vm: *mut c_void, + ); pub fn Neon_Module_ExecCallback(callback: CCallback, exports: Local, vm: *mut c_void); pub fn Neon_Module_GetVersion() -> i32; pub fn Neon_Object_New(out: &mut Local, isolate: Isolate); - pub fn Neon_Object_GetOwnPropertyNames(out: &mut Local, isolate: Isolate, object: Local) -> bool; + pub fn Neon_Object_GetOwnPropertyNames( + out: &mut Local, + isolate: Isolate, + object: Local, + ) -> bool; pub fn Neon_Object_GetIsolate(obj: Local) -> Isolate; pub fn Neon_Object_Get_Index(out: &mut Local, object: Local, index: u32) -> bool; pub fn Neon_Object_Set_Index(out: &mut bool, object: Local, index: u32, val: Local) -> bool; - pub fn Neon_Object_Get_String(out: &mut Local, object: Local, key: *const u8, len: i32) -> bool; - pub fn Neon_Object_Set_String(out: &mut bool, object: Local, key: *const u8, len: i32, val: Local) -> bool; + pub fn Neon_Object_Get_String(out: &mut Local, object: Local, key: *const u8, len: i32) + -> bool; + pub fn Neon_Object_Set_String( + out: &mut bool, + object: Local, + key: *const u8, + len: i32, + val: Local, + ) -> bool; pub fn Neon_Object_Get(out: &mut Local, object: Local, key: Local) -> bool; pub fn Neon_Object_Set(out: &mut bool, object: Local, key: Local, val: Local) -> bool; @@ -195,9 +260,24 @@ extern "C" { pub fn Neon_Primitive_Number(out: &mut Local, isolate: Isolate, v: f64); pub fn Neon_Primitive_NumberValue(p: Local) -> f64; - pub fn Neon_Scope_Escape(isolate: Isolate, out: &mut Local, scope: *mut EscapableHandleScope, value: Local); - pub fn Neon_Scope_Chained(out: *mut c_void, closure: *mut c_void, callback: extern fn(&mut c_void, *mut c_void, *mut c_void, *mut c_void), parent_scope: *mut c_void); - pub fn Neon_Scope_Nested(out: *mut c_void, closure: *mut c_void, callback: extern fn(&mut c_void, *mut c_void, *mut c_void), realm: *mut c_void); + pub fn Neon_Scope_Escape( + isolate: Isolate, + out: &mut Local, + scope: *mut EscapableHandleScope, + value: Local, + ); + pub fn Neon_Scope_Chained( + out: *mut c_void, + closure: *mut c_void, + callback: extern "C" fn(&mut c_void, *mut c_void, *mut c_void, *mut c_void), + parent_scope: *mut c_void, + ); + pub fn Neon_Scope_Nested( + out: *mut c_void, + closure: *mut c_void, + callback: extern "C" fn(&mut c_void, *mut c_void, *mut c_void), + realm: *mut c_void, + ); pub fn Neon_Scope_Enter(scope: &mut HandleScope, isolate: Isolate); pub fn Neon_Scope_Exit(scope: &mut HandleScope); pub fn Neon_Scope_Enter_Escapable(scope: &mut EscapableHandleScope, isolate: Isolate); @@ -224,14 +304,19 @@ extern "C" { pub fn Neon_Tag_IsBuffer(isolate: Isolate, obj: Local) -> bool; pub fn Neon_Tag_IsArrayBuffer(isolate: Isolate, obj: Local) -> bool; - pub fn Neon_Task_Schedule(task: *mut c_void, - perform: unsafe extern fn(*mut c_void) -> *mut c_void, - complete: unsafe extern fn(*mut c_void, *mut c_void, &mut Local), - callback: Local); + pub fn Neon_Task_Schedule( + task: *mut c_void, + perform: unsafe extern "C" fn(*mut c_void) -> *mut c_void, + complete: unsafe extern "C" fn(*mut c_void, *mut c_void, &mut Local), + callback: Local, + ); pub fn Neon_EventHandler_New(isolate: Isolate, this: Local, callback: Local) -> *mut c_void; - pub fn Neon_EventHandler_Schedule(thread_safe_cb: *mut c_void, rust_callback: *mut c_void, - complete: unsafe extern fn(Local, Local, *mut c_void)); + pub fn Neon_EventHandler_Schedule( + thread_safe_cb: *mut c_void, + rust_callback: *mut c_void, + complete: unsafe extern "C" fn(Local, Local, *mut c_void), + ); pub fn Neon_EventHandler_Delete(thread_safe_cb: *mut c_void); /// Invokes a Rust closure with a `TryCatch` live on the stack. @@ -239,10 +324,12 @@ extern "C" { /// does not return `TryCatchControl::Panicked`. /// The `unwind_value` value can be assumed to be initialized if and only if this /// function returns `TryCatchControl::Panicked`. - pub fn Neon_TryCatch_With(glue: TryCatchGlue, - rust_thunk: *mut c_void, - cx: *mut c_void, - ok: *mut c_void, - err: *mut Local, - unwind_value: *mut *mut c_void) -> TryCatchControl; + pub fn Neon_TryCatch_With( + glue: TryCatchGlue, + rust_thunk: *mut c_void, + cx: *mut c_void, + ok: *mut c_void, + err: *mut Local, + unwind_value: *mut *mut c_void, + ) -> TryCatchControl; } diff --git a/src/borrow/internal.rs b/src/borrow/internal.rs index 0bbda7ab0..5ad59ac8a 100644 --- a/src/borrow/internal.rs +++ b/src/borrow/internal.rs @@ -1,7 +1,7 @@ +use borrow::LoanError; use std; -use std::os::raw::c_void; use std::collections::HashSet; -use borrow::LoanError; +use std::os::raw::c_void; pub unsafe trait Pointer { unsafe fn as_ptr(&self) -> *const c_void; @@ -31,14 +31,14 @@ unsafe impl<'a, T> Pointer for &'a mut T { pub struct Ledger { immutable_loans: HashSet<*const c_void>, - mutable_loans: HashSet<*const c_void> + mutable_loans: HashSet<*const c_void>, } impl Ledger { pub fn new() -> Self { Ledger { immutable_loans: HashSet::new(), - mutable_loans: HashSet::new() + mutable_loans: HashSet::new(), } } diff --git a/src/borrow/mod.rs b/src/borrow/mod.rs index bd08a0120..1de6c4235 100644 --- a/src/borrow/mod.rs +++ b/src/borrow/mod.rs @@ -2,65 +2,59 @@ pub(crate) mod internal; -use std::ops::{Deref, DerefMut, Drop}; use std::fmt; +use std::ops::{Deref, DerefMut, Drop}; use std::os::raw::c_void; -use context::Lock; use self::internal::Pointer; +use context::Lock; /// A trait for JS values whose internal contents can be borrowed immutably by Rust while the JS engine is locked. pub trait Borrow: Sized { - /// The type of the value's internal contents. type Target: Pointer; /// Borrow the contents of this value immutably. - /// + /// /// If there is already an outstanding mutable loan for this value, this method panics. fn borrow<'a>(self, lock: &'a Lock<'a>) -> Ref<'a, Self::Target> { match self.try_borrow(lock) { Ok(r) => r, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), } } /// Borrow the contents of this value immutably. - /// + /// /// If there is already an outstanding mutable loan for this value, this method fails with a `LoanError`. fn try_borrow<'a>(self, lock: &'a Lock<'a>) -> Result, LoanError>; - } /// A trait for JS values whose internal contents can be borrowed mutably by Rust while the JS engine is locked. pub trait BorrowMut: Borrow { - /// Borrow the contents of this value mutably. - /// + /// /// If there is already an outstanding loan for this value, this method panics. fn borrow_mut<'a>(self, lock: &'a Lock<'a>) -> RefMut<'a, Self::Target> { match self.try_borrow_mut(lock) { Ok(r) => r, - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), } } /// Borrow the contents of this value mutably. - /// + /// /// If there is already an outstanding loan for this value, this method panics. fn try_borrow_mut<'a>(self, lock: &'a Lock<'a>) -> Result, LoanError>; - } /// An error produced by a failed loan in the `Borrow` or `BorrowMut` traits. pub enum LoanError { - /// Indicates that there is already an outstanding mutable loan for the object at this address. Mutating(*const c_void), /// Indicates that there is already an outstanding immutable loan for the object at this address. - Frozen(*const c_void) - + Frozen(*const c_void), } impl fmt::Display for LoanError { @@ -79,7 +73,7 @@ impl fmt::Display for LoanError { /// An immutable reference to the contents of a borrowed JS value. pub struct Ref<'a, T: Pointer> { pointer: T, - lock: &'a Lock<'a> + lock: &'a Lock<'a>, } impl<'a, T: Pointer> Ref<'a, T> { @@ -108,7 +102,7 @@ impl<'a, T: Pointer> Deref for Ref<'a, T> { /// A mutable reference to the contents of a borrowed JS value. pub struct RefMut<'a, T: Pointer> { pointer: T, - lock: &'a Lock<'a> + lock: &'a Lock<'a>, } impl<'a, T: Pointer> RefMut<'a, T> { diff --git a/src/context/internal.rs b/src/context/internal.rs index 45b4f4f1f..7590cb787 100644 --- a/src/context/internal.rs +++ b/src/context/internal.rs @@ -1,22 +1,22 @@ -#[cfg(feature = "legacy-runtime")] -use std::any::Any; -use std::cell::{Cell, RefCell}; -use std::mem::MaybeUninit; -#[cfg(feature = "legacy-runtime")] -use std::os::raw::c_void; -#[cfg(feature = "legacy-runtime")] -use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; +use super::ModuleContext; +use handle::Handle; use neon_runtime; use neon_runtime::raw; use neon_runtime::scope::Root; #[cfg(feature = "legacy-runtime")] use neon_runtime::try_catch::TryCatchControl; -use types::{JsObject, JsValue}; -use handle::Handle; #[cfg(feature = "legacy-runtime")] use object::class::ClassMap; use result::NeonResult; -use super::ModuleContext; +#[cfg(feature = "legacy-runtime")] +use std::any::Any; +use std::cell::{Cell, RefCell}; +use std::mem::MaybeUninit; +#[cfg(feature = "legacy-runtime")] +use std::os::raw::c_void; +#[cfg(feature = "legacy-runtime")] +use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; +use types::{JsObject, JsValue}; #[cfg(feature = "legacy-runtime")] #[repr(C)] @@ -68,20 +68,18 @@ impl Env { #[cfg(feature = "legacy-runtime")] pub(crate) fn current() -> Env { - unsafe { - std::mem::transmute(neon_runtime::call::current_isolate()) - } + unsafe { std::mem::transmute(neon_runtime::call::current_isolate()) } } } pub struct ScopeMetadata { env: Env, - active: Cell + active: Cell, } pub struct Scope<'a, R: Root + 'static> { pub metadata: ScopeMetadata, - pub handle_scope: &'a mut R + pub handle_scope: &'a mut R, } impl<'a, R: Root + 'static> Scope<'a, R> { @@ -94,9 +92,9 @@ impl<'a, R: Root + 'static> Scope<'a, R> { let scope = Scope { metadata: ScopeMetadata { env, - active: Cell::new(true) + active: Cell::new(true), }, - handle_scope: &mut handle_scope + handle_scope: &mut handle_scope, }; f(scope) }; @@ -124,12 +122,17 @@ pub trait ContextInternal<'a>: Sized { } } - fn activate(&self) { self.scope_metadata().active.set(true); } - fn deactivate(&self) { self.scope_metadata().active.set(false); } + fn activate(&self) { + self.scope_metadata().active.set(true); + } + fn deactivate(&self) { + self.scope_metadata().active.set(false); + } #[cfg(feature = "legacy-runtime")] fn try_catch_internal(&mut self, f: F) -> Result> - where F: FnOnce(&mut Self) -> NeonResult, + where + F: FnOnce(&mut Self) -> NeonResult, { // A closure does not have a guaranteed layout, so we need to box it in order to pass // a pointer to it across the boundary into C++. @@ -140,12 +143,14 @@ pub trait ContextInternal<'a>: Sized { let mut unwind_value: MaybeUninit<*mut c_void> = MaybeUninit::zeroed(); let ctrl = unsafe { - neon_runtime::try_catch::with(try_catch_glue::, - rust_thunk as *mut c_void, - (self as *mut Self) as *mut c_void, - ok.as_mut_ptr() as *mut c_void, - err.as_mut_ptr(), - unwind_value.as_mut_ptr()) + neon_runtime::try_catch::with( + try_catch_glue::, + rust_thunk as *mut c_void, + (self as *mut Self) as *mut c_void, + ok.as_mut_ptr() as *mut c_void, + err.as_mut_ptr(), + unwind_value.as_mut_ptr(), + ) }; match ctrl { @@ -168,7 +173,8 @@ pub trait ContextInternal<'a>: Sized { #[cfg(feature = "napi-1")] fn try_catch_internal(&mut self, f: F) -> Result> - where F: FnOnce(&mut Self) -> NeonResult + where + F: FnOnce(&mut Self) -> NeonResult, { let result = f(self); let mut local: MaybeUninit = MaybeUninit::zeroed(); @@ -185,12 +191,15 @@ pub trait ContextInternal<'a>: Sized { } #[cfg(feature = "legacy-runtime")] -extern "C" fn try_catch_glue<'a, 'b: 'a, C, T, F>(rust_thunk: *mut c_void, - cx: *mut c_void, - returned: *mut c_void, - unwind_value: *mut *mut c_void) -> TryCatchControl - where C: ContextInternal<'a>, - F: FnOnce(&mut C) -> NeonResult, +extern "C" fn try_catch_glue<'a, 'b: 'a, C, T, F>( + rust_thunk: *mut c_void, + cx: *mut c_void, + returned: *mut c_void, + unwind_value: *mut *mut c_void, +) -> TryCatchControl +where + C: ContextInternal<'a>, + F: FnOnce(&mut C) -> NeonResult, { let f: F = *unsafe { Box::from_raw(rust_thunk as *mut F) }; let cx: &mut C = unsafe { &mut *cx.cast() }; @@ -205,18 +214,16 @@ extern "C" fn try_catch_glue<'a, 'b: 'a, C, T, F>(rust_thunk: *mut c_void, Ok(Ok(result)) => unsafe { (returned as *mut T).write(result); TryCatchControl::Returned - } + }, // No Rust panic, caught a JS exception. - Ok(Err(_)) => { - TryCatchControl::Threw - } + Ok(Err(_)) => TryCatchControl::Threw, // Rust panicked. Err(err) => unsafe { // A panic value has an undefined layout, so wrap it in an extra box. let boxed = Box::new(err); *unwind_value = Box::into_raw(boxed) as *mut c_void; TryCatchControl::Panicked - } + }, } } @@ -230,8 +237,14 @@ pub fn initialize_module(exports: Handle, init: fn(ModuleContext) -> N } #[cfg(feature = "napi-1")] -pub fn initialize_module(env: raw::Env, exports: Handle, init: fn(ModuleContext) -> NeonResult<()>) { - unsafe { neon_runtime::setup(env); } +pub fn initialize_module( + env: raw::Env, + exports: Handle, + init: fn(ModuleContext) -> NeonResult<()>, +) { + unsafe { + neon_runtime::setup(env); + } IS_RUNNING.with(|v| { *v.borrow_mut() = true; diff --git a/src/context/mod.rs b/src/context/mod.rs index e957b3463..0a7653fbf 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -2,33 +2,36 @@ pub(crate) mod internal; +use borrow::internal::Ledger; +use borrow::{Borrow, BorrowMut, Ref, RefMut}; +use context::internal::Env; +#[cfg(all(feature = "napi-4", feature = "event-queue-api"))] +use event::EventQueue; +use handle::{Handle, Managed}; +use neon_runtime; +use neon_runtime::raw; +#[cfg(feature = "legacy-runtime")] +use object::class::Class; +use object::{Object, This}; +use result::{JsResult, NeonResult, Throw}; +#[cfg(feature = "napi-1")] +use smallvec::SmallVec; use std; use std::cell::RefCell; use std::convert::Into; use std::marker::PhantomData; use std::os::raw::c_void; use std::panic::UnwindSafe; -use neon_runtime; -use neon_runtime::raw; -use borrow::{Ref, RefMut, Borrow, BorrowMut}; -use borrow::internal::Ledger; -use context::internal::Env; -use handle::{Managed, Handle}; -#[cfg(all(feature = "napi-4", feature = "event-queue-api"))] -use event::EventQueue; -use types::{JsValue, Value, JsObject, JsArray, JsFunction, JsBoolean, JsNumber, JsString, StringResult, JsNull, JsUndefined}; -#[cfg(feature = "napi-5")] -use types::date::{JsDate, DateError}; +use types::binary::{JsArrayBuffer, JsBuffer}; #[cfg(feature = "napi-1")] use types::boxed::{Finalize, JsBox}; -use types::binary::{JsArrayBuffer, JsBuffer}; +#[cfg(feature = "napi-5")] +use types::date::{DateError, JsDate}; use types::error::JsError; -use object::{Object, This}; -#[cfg(feature = "legacy-runtime")] -use object::class::Class; -use result::{NeonResult, JsResult, Throw}; -#[cfg(feature = "napi-1")] -use smallvec::SmallVec; +use types::{ + JsArray, JsBoolean, JsFunction, JsNull, JsNumber, JsObject, JsString, JsUndefined, JsValue, + StringResult, Value, +}; use self::internal::{ContextInternal, Scope, ScopeMetadata}; @@ -47,15 +50,17 @@ impl CallbackInfo<'_> { } } - pub unsafe fn with_cx FnOnce(CallContext<'a, T>) -> U>(&self, env: Env, f: F) -> U { + pub unsafe fn with_cx FnOnce(CallContext<'a, T>) -> U>( + &self, + env: Env, + f: F, + ) -> U { CallContext::::with(env, self, f) } #[cfg(feature = "legacy-runtime")] pub fn set_return(&self, value: Handle) { - unsafe { - neon_runtime::call::set_return(self.info, value.to_raw()) - } + unsafe { neon_runtime::call::set_return(self.info, value.to_raw()) } } #[cfg(feature = "legacy-runtime")] @@ -77,9 +82,7 @@ impl CallbackInfo<'_> { } pub fn len<'b, C: Context<'b>>(&self, cx: &C) -> i32 { - unsafe { - neon_runtime::call::len(cx.env().to_raw(), self.info) - } + unsafe { neon_runtime::call::len(cx.env().to_raw(), self.info) } } #[cfg(feature = "legacy-runtime")] @@ -96,9 +99,7 @@ impl CallbackInfo<'_> { #[cfg(feature = "napi-1")] pub fn argv<'b, C: Context<'b>>(&self, cx: &mut C) -> SmallVec<[raw::Local; 8]> { - unsafe { - neon_runtime::call::argv(cx.env().to_raw(), self.info) - } + unsafe { neon_runtime::call::argv(cx.env().to_raw(), self.info) } } pub fn this<'b, C: Context<'b>>(&self, cx: &mut C) -> raw::Local { @@ -115,7 +116,7 @@ impl CallbackInfo<'_> { #[derive(Clone, Copy, Debug)] pub enum CallKind { Construct, - Call + Call, } /// An RAII implementation of a "scoped lock" of the JS engine. When this structure is dropped (falls out of scope), the engine will be unlocked. @@ -124,7 +125,7 @@ pub enum CallKind { pub struct Lock<'a> { pub(crate) ledger: RefCell, pub(crate) env: Env, - phantom: PhantomData<&'a ()> + phantom: PhantomData<&'a ()>, } impl<'a> Lock<'a> { @@ -141,7 +142,6 @@ impl<'a> Lock<'a> { /// /// A context has a lifetime `'a`, which ensures the safety of handles managed by the JS garbage collector. All handles created during the lifetime of a context are kept alive for that duration and cannot outlive the context. pub trait Context<'a>: ContextInternal<'a> { - /// Lock the JavaScript engine, returning an RAII guard that keeps the lock active as long as the guard is alive. /// /// If this is not the currently active context (for example, if it was used to spawn a scoped context with `execute_scoped` or `compute_scoped`), this method will panic. @@ -170,9 +170,10 @@ pub trait Context<'a>: ContextInternal<'a> { /// but while the extra `&` is a small ergonomics regression, this API is still a nice /// convenience. fn borrow<'c, V, T, F>(&self, v: &'c Handle, f: F) -> T - where V: Value, - &'c V: Borrow, - F: for<'b> FnOnce(Ref<'b, <&'c V as Borrow>::Target>) -> T + where + V: Value, + &'c V: Borrow, + F: for<'b> FnOnce(Ref<'b, <&'c V as Borrow>::Target>) -> T, { let lock = self.lock(); let contents = v.borrow(&lock); @@ -201,9 +202,10 @@ pub trait Context<'a>: ContextInternal<'a> { /// but while the extra `&mut` is a small ergonomics regression, this API is still a nice /// convenience. fn borrow_mut<'c, V, T, F>(&self, v: &'c mut Handle, f: F) -> T - where V: Value, - &'c mut V: BorrowMut, - F: for<'b> FnOnce(RefMut<'b, <&'c mut V as Borrow>::Target>) -> T + where + V: Value, + &'c mut V: BorrowMut, + F: for<'b> FnOnce(RefMut<'b, <&'c mut V as Borrow>::Target>) -> T, { let lock = self.lock(); let contents = v.borrow_mut(&lock); @@ -216,7 +218,8 @@ pub trait Context<'a>: ContextInternal<'a> { /// /// This method can be useful for limiting the life of temporary values created during long-running computations, to prevent leaks. fn execute_scoped(&self, f: F) -> T - where F: for<'b> FnOnce(ExecuteContext<'b>) -> T + where + F: for<'b> FnOnce(ExecuteContext<'b>) -> T, { self.check_active(); self.deactivate(); @@ -231,19 +234,23 @@ pub trait Context<'a>: ContextInternal<'a> { /// /// This method can be useful for limiting the life of temporary values created during long-running computations, to prevent leaks. fn compute_scoped(&self, f: F) -> JsResult<'a, V> - where V: Value, - F: for<'b, 'c> FnOnce(ComputeContext<'b, 'c>) -> JsResult<'b, V> + where + V: Value, + F: for<'b, 'c> FnOnce(ComputeContext<'b, 'c>) -> JsResult<'b, V>, { self.check_active(); self.deactivate(); - let result = ComputeContext::with(self, |cx| { - unsafe { - let escapable_handle_scope = cx.scope.handle_scope as *mut raw::EscapableHandleScope; - let escapee = f(cx)?; - let mut result_local: raw::Local = std::mem::zeroed(); - neon_runtime::scope::escape(self.env().to_raw(), &mut result_local, escapable_handle_scope, escapee.to_raw()); - Ok(Handle::new_internal(V::from_raw(self.env(), result_local))) - } + let result = ComputeContext::with(self, |cx| unsafe { + let escapable_handle_scope = cx.scope.handle_scope as *mut raw::EscapableHandleScope; + let escapee = f(cx)?; + let mut result_local: raw::Local = std::mem::zeroed(); + neon_runtime::scope::escape( + self.env().to_raw(), + &mut result_local, + escapable_handle_scope, + escapee.to_raw(), + ); + Ok(Handle::new_internal(V::from_raw(self.env(), result_local))) }); self.activate(); result @@ -251,7 +258,8 @@ pub trait Context<'a>: ContextInternal<'a> { #[cfg(feature = "try-catch-api")] fn try_catch(&mut self, f: F) -> Result> - where F: FnOnce(&mut Self) -> NeonResult + where + F: FnOnce(&mut Self) -> NeonResult, { self.try_catch_internal(f) } @@ -324,10 +332,8 @@ pub trait Context<'a>: ContextInternal<'a> { /// Produces a handle to the JavaScript global object. fn global(&mut self) -> Handle<'a, JsObject> { - JsObject::build(|out| { - unsafe { - neon_runtime::scope::get_global(self.env().to_raw(), out); - } + JsObject::build(|out| unsafe { + neon_runtime::scope::get_global(self.env().to_raw(), out); }) } @@ -403,30 +409,38 @@ pub trait Context<'a>: ContextInternal<'a> { /// A view of the JS engine in the context of top-level initialization of a Neon module. pub struct ModuleContext<'a> { scope: Scope<'a, raw::HandleScope>, - exports: Handle<'a, JsObject> + exports: Handle<'a, JsObject>, } -impl<'a> UnwindSafe for ModuleContext<'a> { } +impl<'a> UnwindSafe for ModuleContext<'a> {} impl<'a> ModuleContext<'a> { - pub(crate) fn with FnOnce(ModuleContext<'b>) -> T>(env: Env, exports: Handle<'a, JsObject>, f: F) -> T { + pub(crate) fn with FnOnce(ModuleContext<'b>) -> T>( + env: Env, + exports: Handle<'a, JsObject>, + f: F, + ) -> T { // These assertions ensure the proper amount of space is reserved on the rust stack // This is only necessary in the legacy runtime. #[cfg(feature = "legacy-runtime")] { - debug_assert!(unsafe { neon_runtime::scope::size() } <= std::mem::size_of::()); - debug_assert!(unsafe { neon_runtime::scope::alignment() } <= std::mem::align_of::()); + debug_assert!( + unsafe { neon_runtime::scope::size() } <= std::mem::size_of::() + ); + debug_assert!( + unsafe { neon_runtime::scope::alignment() } + <= std::mem::align_of::() + ); } - Scope::with(env, |scope| { - f(ModuleContext { - scope, - exports - }) - }) + Scope::with(env, |scope| f(ModuleContext { scope, exports })) } /// Convenience method for exporting a Neon function from a module. - pub fn export_function(&mut self, key: &str, f: fn(FunctionContext) -> JsResult) -> NeonResult<()> { + pub fn export_function( + &mut self, + key: &str, + f: fn(FunctionContext) -> JsResult, + ) -> NeonResult<()> { let value = JsFunction::new(self, f)?.upcast::(); self.exports.set(self, key, value)?; Ok(()) @@ -458,18 +472,19 @@ impl<'a> ContextInternal<'a> for ModuleContext<'a> { } } -impl<'a> Context<'a> for ModuleContext<'a> { } +impl<'a> Context<'a> for ModuleContext<'a> {} /// A view of the JS engine in the context of a scoped computation started by `Context::execute_scoped()`. pub struct ExecuteContext<'a> { - scope: Scope<'a, raw::HandleScope> + scope: Scope<'a, raw::HandleScope>, } impl<'a> ExecuteContext<'a> { - pub(crate) fn with, F: for<'b> FnOnce(ExecuteContext<'b>) -> T>(cx: &C, f: F) -> T { - Scope::with(cx.env(), |scope| { - f(ExecuteContext { scope }) - }) + pub(crate) fn with, F: for<'b> FnOnce(ExecuteContext<'b>) -> T>( + cx: &C, + f: F, + ) -> T { + Scope::with(cx.env(), |scope| f(ExecuteContext { scope })) } } @@ -479,22 +494,25 @@ impl<'a> ContextInternal<'a> for ExecuteContext<'a> { } } -impl<'a> Context<'a> for ExecuteContext<'a> { } +impl<'a> Context<'a> for ExecuteContext<'a> {} /// A view of the JS engine in the context of a scoped computation started by `Context::compute_scoped()`. pub struct ComputeContext<'a, 'outer> { scope: Scope<'a, raw::EscapableHandleScope>, phantom_inner: PhantomData<&'a ()>, - phantom_outer: PhantomData<&'outer ()> + phantom_outer: PhantomData<&'outer ()>, } impl<'a, 'b> ComputeContext<'a, 'b> { - pub(crate) fn with, F: for<'c, 'd> FnOnce(ComputeContext<'c, 'd>) -> T>(cx: &C, f: F) -> T { + pub(crate) fn with, F: for<'c, 'd> FnOnce(ComputeContext<'c, 'd>) -> T>( + cx: &C, + f: F, + ) -> T { Scope::with(cx.env(), |scope| { f(ComputeContext { scope, phantom_inner: PhantomData, - phantom_outer: PhantomData + phantom_outer: PhantomData, }) }) } @@ -506,7 +524,7 @@ impl<'a, 'b> ContextInternal<'a> for ComputeContext<'a, 'b> { } } -impl<'a, 'b> Context<'a> for ComputeContext<'a, 'b> { } +impl<'a, 'b> Context<'a> for ComputeContext<'a, 'b> {} /// A view of the JS engine in the context of a function call. /// @@ -516,10 +534,10 @@ pub struct CallContext<'a, T: This> { info: &'a CallbackInfo<'a>, #[cfg(feature = "napi-1")] arguments: Option>, - phantom_type: PhantomData + phantom_type: PhantomData, } -impl<'a, T: This> UnwindSafe for CallContext<'a, T> { } +impl<'a, T: This> UnwindSafe for CallContext<'a, T> {} impl<'a, T: This> CallContext<'a, T> { /// Indicates whether the function was called via the JavaScript `[[Call]]` or `[[Construct]]` semantics. @@ -533,28 +551,38 @@ impl<'a, T: This> CallContext<'a, T> { kind } - pub(crate) fn with FnOnce(CallContext<'b, T>) -> U>(env: Env, info: &'a CallbackInfo<'a>, f: F) -> U { + pub(crate) fn with FnOnce(CallContext<'b, T>) -> U>( + env: Env, + info: &'a CallbackInfo<'a>, + f: F, + ) -> U { Scope::with(env, |scope| { f(CallContext { scope, info, #[cfg(feature = "napi-1")] arguments: None, - phantom_type: PhantomData + phantom_type: PhantomData, }) }) } /// Indicates the number of arguments that were passed to the function. - pub fn len(&self) -> i32 { self.info.len(self) } + pub fn len(&self) -> i32 { + self.info.len(self) + } /// Indicates if no arguments were passed to the function. - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// Produces the `i`th argument, or `None` if `i` is greater than or equal to `self.len()`. pub fn argument_opt(&mut self, i: i32) -> Option> { #[cfg(feature = "legacy-runtime")] - { self.info.get(self, i) } + { + self.info.get(self, i) + } #[cfg(feature = "napi-1")] { @@ -576,7 +604,7 @@ impl<'a, T: This> CallContext<'a, T> { pub fn argument(&mut self, i: i32) -> JsResult<'a, V> { match self.argument_opt(i) { Some(v) => v.downcast_or_throw(self), - None => self.throw_type_error("not enough arguments") + None => self.throw_type_error("not enough arguments"), } } @@ -597,7 +625,7 @@ impl<'a, T: This> ContextInternal<'a> for CallContext<'a, T> { } } -impl<'a, T: This> Context<'a> for CallContext<'a, T> { } +impl<'a, T: This> Context<'a> for CallContext<'a, T> {} /// A shorthand for a `CallContext` with `this`-type `JsObject`. pub type FunctionContext<'a> = CallContext<'a, JsObject>; @@ -609,23 +637,19 @@ pub type MethodContext<'a, T> = CallContext<'a, T>; pub struct TaskContext<'a> { /// We use an "inherited HandleScope" here because the C++ `neon::Task::complete` /// method sets up and tears down a `HandleScope` for us. - scope: Scope<'a, raw::InheritedHandleScope> + scope: Scope<'a, raw::InheritedHandleScope>, } impl<'a> TaskContext<'a> { #[cfg(feature = "legacy-runtime")] pub(crate) fn with FnOnce(TaskContext<'b>) -> T>(f: F) -> T { let env = Env::current(); - Scope::with(env, |scope| { - f(TaskContext { scope }) - }) + Scope::with(env, |scope| f(TaskContext { scope })) } #[cfg(all(feature = "napi-4", feature = "event-queue-api"))] pub(crate) fn with_context FnOnce(TaskContext<'b>) -> T>(env: Env, f: F) -> T { - Scope::with(env, |scope| { - f(TaskContext { scope }) - }) + Scope::with(env, |scope| f(TaskContext { scope })) } } @@ -635,20 +659,18 @@ impl<'a> ContextInternal<'a> for TaskContext<'a> { } } -impl<'a> Context<'a> for TaskContext<'a> { } +impl<'a> Context<'a> for TaskContext<'a> {} /// A view of the JS engine in the context of a finalize method on garbage collection #[cfg(feature = "napi-1")] pub(crate) struct FinalizeContext<'a> { - scope: Scope<'a, raw::HandleScope> + scope: Scope<'a, raw::HandleScope>, } #[cfg(feature = "napi-1")] impl<'a> FinalizeContext<'a> { pub(crate) fn with FnOnce(FinalizeContext<'b>) -> T>(env: Env, f: F) -> T { - Scope::with(env, |scope| { - f(FinalizeContext { scope }) - }) + Scope::with(env, |scope| f(FinalizeContext { scope })) } } @@ -660,4 +682,4 @@ impl<'a> ContextInternal<'a> for FinalizeContext<'a> { } #[cfg(feature = "napi-1")] -impl<'a> Context<'a> for FinalizeContext<'a> { } +impl<'a> Context<'a> for FinalizeContext<'a> {} diff --git a/src/event/event_handler.rs b/src/event/event_handler.rs index 8d7a28409..af271b160 100644 --- a/src/event/event_handler.rs +++ b/src/event/event_handler.rs @@ -2,13 +2,13 @@ use std::os::raw::c_void; -use types::*; +use context::internal::ContextInternal; +use context::Context; use handle::{Handle, Managed}; use neon_runtime; use neon_runtime::raw; use std::sync::Arc; -use context::Context; -use context::internal::ContextInternal; +use types::*; type EventContext<'a> = crate::context::TaskContext<'a>; @@ -29,7 +29,11 @@ impl Drop for EventHandlerInner { pub struct EventHandler(Arc); impl EventHandler { - pub fn new<'a, C: Context<'a>, T: Value>(cx: &C, this: Handle, callback: Handle) -> Self { + pub fn new<'a, C: Context<'a>, T: Value>( + cx: &C, + this: Handle, + callback: Handle, + ) -> Self { let cb = unsafe { neon_runtime::handler::new(cx.env().to_raw(), this.to_raw(), callback.to_raw()) }; @@ -37,9 +41,11 @@ impl EventHandler { } pub fn schedule(&self, arg_cb: F) - where T: Value, - F: for<'a> FnOnce(&mut EventContext<'a>) -> Vec>, - F: Send + 'static { + where + T: Value, + F: for<'a> FnOnce(&mut EventContext<'a>) -> Vec>, + F: Send + 'static, + { self.schedule_with(move |cx, this, callback| { let args = arg_cb(cx); let _result = callback.call(cx, this, args); @@ -47,8 +53,10 @@ impl EventHandler { } fn schedule_internal(&self, cb: F) - where F: FnOnce(&mut EventContext, Handle, Handle), - F: Send + 'static { + where + F: FnOnce(&mut EventContext, Handle, Handle), + F: Send + 'static, + { let callback = Box::into_raw(Box::new(cb)) as *mut c_void; unsafe { neon_runtime::handler::schedule((*self.0).0, callback, handle_callback::); @@ -56,8 +64,10 @@ impl EventHandler { } pub fn schedule_with(&self, arg_cb: F) - where F: FnOnce(&mut EventContext, Handle, Handle), - F: Send + 'static { + where + F: FnOnce(&mut EventContext, Handle, Handle), + F: Send + 'static, + { // HACK: Work around for race condition in `close`. `EventHandler` cannot be // dropped until all callbacks have executed. // NOTE: This will still leak memory if the callback is never called @@ -71,7 +81,10 @@ impl EventHandler { } unsafe extern "C" fn handle_callback(this: raw::Local, func: raw::Local, callback: *mut c_void) - where F: FnOnce(&mut EventContext, Handle, Handle), F: Send + 'static { +where + F: FnOnce(&mut EventContext, Handle, Handle), + F: Send + 'static, +{ EventContext::with(|mut cx: EventContext| { let this = JsValue::new_internal(this); let func: Handle = Handle::new_internal(JsFunction::from_raw(cx.env(), func)); diff --git a/src/event/event_queue.rs b/src/event/event_queue.rs index b0b8cb2c0..7c4b83ce4 100644 --- a/src/event/event_queue.rs +++ b/src/event/event_queue.rs @@ -38,13 +38,13 @@ type Callback = Box; /// cx.null().upcast::(), /// cx.number(result).upcast(), /// ]; -/// +/// /// callback.call(&mut cx, this, args)?; /// /// Ok(()) /// }); /// }); -/// +/// /// Ok(cx.undefined()) /// } /// ``` @@ -64,12 +64,7 @@ impl EventQueue { /// Creates an unbounded queue for scheduling closures on the JavaScript /// main thread pub fn new<'a, C: Context<'a>>(cx: &mut C) -> Self { - let tsfn = unsafe { - ThreadsafeFunction::new( - cx.env().to_raw(), - Self::callback, - ) - }; + let tsfn = unsafe { ThreadsafeFunction::new(cx.env().to_raw(), Self::callback) }; Self { tsfn, @@ -82,9 +77,7 @@ impl EventQueue { pub fn unref<'a, C: Context<'a>>(&mut self, cx: &mut C) -> &mut Self { self.has_ref = false; - unsafe { - self.tsfn.unref(cx.env().to_raw()) - } + unsafe { self.tsfn.unref(cx.env().to_raw()) } self } @@ -94,9 +87,7 @@ impl EventQueue { pub fn reference<'a, C: Context<'a>>(&mut self, cx: &mut C) -> &mut Self { self.has_ref = true; - unsafe { - self.tsfn.reference(cx.env().to_raw()) - } + unsafe { self.tsfn.reference(cx.env().to_raw()) } self } @@ -126,9 +117,7 @@ impl EventQueue { }); }); - self.tsfn - .call(callback, None) - .map_err(|_| EventQueueError) + self.tsfn.call(callback, None).map_err(|_| EventQueueError) } /// Returns a boolean indicating if this `EventQueue` will prevent the Node event diff --git a/src/event/mod.rs b/src/event/mod.rs index 482d61276..065f19579 100644 --- a/src/event/mod.rs +++ b/src/event/mod.rs @@ -11,5 +11,7 @@ mod event_handler; pub use self::event_handler::EventHandler; #[cfg(all(feature = "napi-1", feature = "event-handler-api"))] -compile_error!("The `EventHandler` API is not supported with the N-API \ - backend. Use `EventQueue` instead."); +compile_error!( + "The `EventHandler` API is not supported with the N-API \ + backend. Use `EventQueue` instead." +); diff --git a/src/handle/mod.rs b/src/handle/mod.rs index 79f4c1a66..c0dfd386b 100644 --- a/src/handle/mod.rs +++ b/src/handle/mod.rs @@ -8,17 +8,17 @@ mod root; #[cfg(feature = "napi-1")] pub use self::root::Root; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; -use std::error::Error; -use std::fmt::{self, Debug, Display}; +use self::internal::SuperType; +use context::internal::Env; +use context::Context; use neon_runtime; use neon_runtime::raw; -use types::Value; -use context::Context; -use context::internal::Env; use result::{JsResult, JsResultExt}; -use self::internal::SuperType; +use std::error::Error; +use std::fmt::{self, Debug, Display}; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; +use types::Value; /// The trait of data that is managed by the JS garbage collector and can only be accessed via handles. pub trait Managed: Copy { @@ -32,7 +32,7 @@ pub trait Managed: Copy { #[derive(Clone, Copy, Debug)] pub struct Handle<'a, T: Managed + 'a> { value: T, - phantom: PhantomData<&'a T> + phantom: PhantomData<&'a T>, } #[cfg(feature = "legacy-runtime")] @@ -43,13 +43,13 @@ impl<'a, T: Managed + 'a> PartialEq for Handle<'a, T> { } #[cfg(feature = "legacy-runtime")] -impl<'a, T: Managed + 'a> Eq for Handle<'a, T> { } +impl<'a, T: Managed + 'a> Eq for Handle<'a, T> {} impl<'a, T: Managed + 'a> Handle<'a, T> { pub(crate) fn new_internal(value: T) -> Handle<'a, T> { Handle { value, - phantom: PhantomData + phantom: PhantomData, } } } @@ -91,13 +91,12 @@ impl<'a, F: Value, T: Value> JsResultExt<'a, T> for DowncastResult<'a, F, T> { fn or_throw<'b, C: Context<'b>>(self, cx: &mut C) -> JsResult<'a, T> { match self { Ok(v) => Ok(v), - Err(e) => cx.throw_type_error(&e.to_string()) + Err(e) => cx.throw_type_error(&e.to_string()), } } } impl<'a, T: Value> Handle<'a, T> { - /// Safely upcast a handle to a supertype. /// /// This method does not require an execution context because it only copies a handle. @@ -151,7 +150,7 @@ impl<'a, T: Value> Handle<'a, T> { pub fn downcast(&self) -> DowncastResult<'a, T, U> { match U::downcast(Env::current(), self.value) { Some(v) => Ok(Handle::new_internal(v)), - None => Err(DowncastError::new()) + None => Err(DowncastError::new()), } } @@ -163,7 +162,7 @@ impl<'a, T: Value> Handle<'a, T> { pub fn downcast<'b, U: Value, C: Context<'b>>(&self, cx: &mut C) -> DowncastResult<'a, T, U> { match U::downcast(cx.env(), self.value) { Some(v) => Ok(Handle::new_internal(v)), - None => Err(DowncastError::new()) + None => Err(DowncastError::new()), } } @@ -184,7 +183,11 @@ impl<'a, T: Value> Handle<'a, T> { } #[cfg(feature = "napi-1")] - pub fn strict_equals<'b, U: Value, C: Context<'b>>(&self, cx: &mut C, other: Handle<'b, U>) -> bool { + pub fn strict_equals<'b, U: Value, C: Context<'b>>( + &self, + cx: &mut C, + other: Handle<'b, U>, + ) -> bool { unsafe { neon_runtime::mem::strict_equals(cx.env().to_raw(), self.to_raw(), other.to_raw()) } diff --git a/src/handle/root.rs b/src/handle/root.rs index 5d7498c66..faeed6e1e 100644 --- a/src/handle/root.rs +++ b/src/handle/root.rs @@ -45,9 +45,7 @@ impl Root { /// calling one of these methods, it will *panic*. pub fn new<'a, C: Context<'a>>(cx: &mut C, value: &T) -> Self { let env = cx.env().to_raw(); - let internal = unsafe { - reference::new(env, value.to_raw()) - }; + let internal = unsafe { reference::new(env, value.to_raw()) }; Self { internal: NapiRef(internal as *mut _), @@ -97,9 +95,7 @@ impl Root { let env = cx.env(); let internal = ManuallyDrop::new(self).internal.0 as *mut _; - let local = unsafe { - reference::get(env.to_raw(), internal) - }; + let local = unsafe { reference::get(env.to_raw(), internal) }; unsafe { reference::unreference(env.to_raw(), internal); @@ -113,9 +109,7 @@ impl Root { /// can be used in place of a clone immediately followed by a call to `into_inner`. pub fn to_inner<'a, C: Context<'a>>(&self, cx: &mut C) -> Handle<'a, T> { let env = cx.env(); - let local = unsafe { - reference::get(env.to_raw(), self.internal.0 as *mut _) - }; + let local = unsafe { reference::get(env.to_raw(), self.internal.0 as *mut _) }; Handle::new_internal(T::from_raw(env, local)) } @@ -123,7 +117,7 @@ impl Root { // Allows putting `Root` directly in a container that implements `Finalize` // For example, `Vec>` or `JsBox`. -impl Finalize for Root { +impl Finalize for Root { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { self.drop(cx); } @@ -140,8 +134,10 @@ impl Drop for Root { // Only panic if the event loop is still running if let Ok(true) = crate::context::internal::IS_RUNNING.try_with(|v| *v.borrow()) { - panic!("Must call `into_inner` or `drop` on `Root` \ - https://docs.rs/neon/latest/neon/sync/index.html#drop-safety"); + panic!( + "Must call `into_inner` or `drop` on `Root` \ + https://docs.rs/neon/latest/neon/sync/index.html#drop-safety" + ); } } } diff --git a/src/lib.rs b/src/lib.rs index a555000ed..1ac9b5aae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,7 @@ //! The [Neon](https://www.neon-bindings.com/) crate provides bindings for writing Node.js plugins with a safe and fast Rust API. -extern crate neon_runtime; extern crate cslice; +extern crate neon_runtime; extern crate semver; extern crate smallvec; @@ -12,18 +12,21 @@ extern crate neon_macros; #[macro_use] extern crate lazy_static; +pub mod borrow; pub mod context; +#[cfg(any( + feature = "event-handler-api", + all(feature = "napi-4", feature = "event-queue-api") +))] +pub mod event; pub mod handle; -pub mod types; +pub mod meta; pub mod object; -pub mod borrow; +pub mod prelude; pub mod result; #[cfg(feature = "legacy-runtime")] pub mod task; -#[cfg(any(feature = "event-handler-api", all(feature = "napi-4", feature = "event-queue-api")))] -pub mod event; -pub mod meta; -pub mod prelude; +pub mod types; #[doc(hidden)] pub mod macro_internal; @@ -280,7 +283,7 @@ macro_rules! impl_managed { $cls(raw) } } - } + }; } #[cfg(feature = "legacy-runtime")] @@ -378,10 +381,10 @@ macro_rules! neon_stringify { #[cfg(test)] mod tests { extern crate rustversion; + use semver::Version; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Mutex; - use semver::Version; // Create a mutex to enforce sequential running of the tests. lazy_static! { @@ -408,11 +411,14 @@ mod tests { eprintln!("Running Neon test: {} {} {}", shell, command_flag, cmd); assert!(Command::new(&shell) - .current_dir(dir) - .args(&[&command_flag, cmd]) - .status() - .expect(&format!("failed to execute test command: {} {} {}", shell, command_flag, cmd)) - .success()); + .current_dir(dir) + .args(&[&command_flag, cmd]) + .status() + .unwrap_or_else(|_| panic!( + "failed to execute test command: {} {} {}", + shell, command_flag, cmd + )) + .success()); } fn cli_setup() { @@ -441,7 +447,10 @@ mod tests { log("static_test"); - run("cargo test --release", &project_root().join("test").join("static")); + run( + "cargo test --release", + &project_root().join("test").join("static"), + ); } // Only run the static tests in Beta. This will catch changes to error reporting @@ -450,22 +459,30 @@ mod tests { #[rustversion::beta] #[cfg(feature = "enable-static-tests")] #[test] - fn static_test() { static_test_impl() } + fn static_test() { + static_test_impl() + } #[rustversion::beta] #[cfg(not(feature = "enable-static-tests"))] #[test] #[ignore] - fn static_test() { static_test_impl() } + fn static_test() { + static_test_impl() + } #[rustversion::not(beta)] #[cfg(feature = "enable-static-tests")] - compile_error!("The `enable-static-tests` feature can only be enabled with the Rust beta toolchain."); + compile_error!( + "The `enable-static-tests` feature can only be enabled with the Rust beta toolchain." + ); #[rustversion::not(beta)] #[test] #[ignore] - fn static_test() { static_test_impl() } + fn static_test() { + static_test_impl() + } #[test] fn dynamic_test() { diff --git a/src/macro_internal/mod.rs b/src/macro_internal/mod.rs index fdc125ce7..2d03312f1 100644 --- a/src/macro_internal/mod.rs +++ b/src/macro_internal/mod.rs @@ -1,10 +1,12 @@ //! Internals needed by macros. These have to be exported for the macros to work +pub use context::internal::{initialize_module, Env}; /// but are subject to change and should never be explicitly used. #[cfg(feature = "legacy-runtime")] // Used by the class macro. -pub use object::class::internal::{AllocateCallback, ConstructCallback, ConstructorCallCallback, MethodCallback}; -pub use context::internal::{initialize_module, Env}; +pub use object::class::internal::{ + AllocateCallback, ConstructCallback, ConstructorCallCallback, MethodCallback, +}; // An alias for neon_runtime so macros can refer to it. pub mod runtime { diff --git a/src/meta.rs b/src/meta.rs index d9aded75b..5575fa3ce 100644 --- a/src/meta.rs +++ b/src/meta.rs @@ -21,7 +21,7 @@ pub fn version() -> Version { minor: MINOR.parse().unwrap(), patch: PATCH.parse().unwrap(), pre: vec![], - build: vec![] + build: vec![], } } diff --git a/src/object/class/internal.rs b/src/object/class/internal.rs index 7850248de..a10f881d2 100644 --- a/src/object/class/internal.rs +++ b/src/object/class/internal.rs @@ -1,15 +1,15 @@ +use super::{Callback, Class, ClassInternal}; +use context::internal::{ContextInternal, Env}; +use context::{CallContext, CallbackInfo, Context}; +use handle::{Handle, Managed}; +use neon_runtime; +use neon_runtime::raw; +use result::{JsResult, NeonResult, Throw}; use std::mem; use std::os::raw::c_void; use std::ptr::null_mut; -use neon_runtime; -use neon_runtime::raw; -use super::{Class, ClassInternal, Callback}; -use handle::{Handle, Managed}; -use context::{CallbackInfo, CallContext, Context}; -use context::internal::{ContextInternal, Env}; -use result::{NeonResult, JsResult, Throw}; -use types::{JsValue, JsObject, JsFunction, JsUndefined, build}; use types::error::convert_panics; +use types::{build, JsFunction, JsObject, JsUndefined, JsValue}; #[repr(C)] pub struct MethodCallback(pub fn(CallContext) -> JsResult); @@ -19,7 +19,8 @@ impl Callback<()> for MethodCallback { unsafe { info.with_cx::(env, |mut cx| { let data = info.data(cx.env()); - let this: Handle = Handle::new_internal(JsValue::from_raw(env, info.this(&mut cx))); + let this: Handle = + Handle::new_internal(JsValue::from_raw(env, info.this(&mut cx))); #[cfg(feature = "legacy-runtime")] let is_a_t = this.is_a::(); @@ -28,13 +29,17 @@ impl Callback<()> for MethodCallback { if !is_a_t { if let Ok(metadata) = T::metadata(&mut cx) { - neon_runtime::class::throw_this_error(mem::transmute(cx.env()), metadata.pointer); + neon_runtime::class::throw_this_error( + mem::transmute(cx.env()), + metadata.pointer, + ); } return; }; - let dynamic_callback: fn(CallContext) -> JsResult = - mem::transmute(neon_runtime::fun::get_dynamic_callback(cx.env().to_raw(), data)); - if let Ok(value) = convert_panics(env, || { dynamic_callback(cx) }) { + let dynamic_callback: fn(CallContext) -> JsResult = mem::transmute( + neon_runtime::fun::get_dynamic_callback(cx.env().to_raw(), data), + ); + if let Ok(value) = convert_panics(env, || dynamic_callback(cx)) { info.set_return(value); } }) @@ -54,7 +59,10 @@ impl ConstructorCallCallback { fn callback(mut cx: CallContext) -> JsResult { unsafe { if let Ok(metadata) = T::metadata(&mut cx) { - neon_runtime::class::throw_call_error(mem::transmute(cx.env()), metadata.pointer); + neon_runtime::class::throw_call_error( + mem::transmute(cx.env()), + metadata.pointer, + ); } } Err(Throw) @@ -71,7 +79,7 @@ impl Callback<()> for ConstructorCallCallback { let data = info.data(cx.env()); let kernel: fn(CallContext) -> JsResult = mem::transmute(neon_runtime::class::get_call_kernel(data)); - if let Ok(value) = convert_panics(env, || { kernel(cx) }) { + if let Ok(value) = convert_panics(env, || kernel(cx)) { info.set_return(value); } }) @@ -93,7 +101,7 @@ impl Callback<*mut c_void> for AllocateCallback { let data = info.data(cx.env()); let kernel: fn(CallContext) -> NeonResult = mem::transmute(neon_runtime::class::get_allocate_kernel(data)); - if let Ok(value) = convert_panics(env, || { kernel(cx) }) { + if let Ok(value) = convert_panics(env, || kernel(cx)) { let p = Box::into_raw(Box::new(value)); p.cast() } else { @@ -109,7 +117,9 @@ impl Callback<*mut c_void> for AllocateCallback { } #[repr(C)] -pub struct ConstructCallback(pub fn(CallContext) -> NeonResult>>); +pub struct ConstructCallback( + pub fn(CallContext) -> NeonResult>>, +); impl Callback for ConstructCallback { extern "C" fn invoke(env: Env, info: CallbackInfo<'_>) -> bool { @@ -118,13 +128,13 @@ impl Callback for ConstructCallback { let data = info.data(cx.env()); let kernel: fn(CallContext) -> NeonResult>> = mem::transmute(neon_runtime::class::get_construct_kernel(data)); - match convert_panics(env, || { kernel(cx) }) { + match convert_panics(env, || kernel(cx)) { Ok(None) => true, Ok(Some(obj)) => { info.set_return(obj); true } - _ => false + _ => false, } }) } @@ -138,13 +148,20 @@ impl Callback for ConstructCallback { #[repr(C)] #[derive(Clone, Copy)] pub struct ClassMetadata { - pub(crate) pointer: *mut c_void + pub(crate) pointer: *mut c_void, } impl ClassMetadata { - pub unsafe fn constructor<'a, T: Class, C: Context<'a>>(&self, cx: &mut C) -> JsResult<'a, JsFunction> { + pub unsafe fn constructor<'a, T: Class, C: Context<'a>>( + &self, + cx: &mut C, + ) -> JsResult<'a, JsFunction> { build(cx.env(), |out| { - neon_runtime::class::metadata_to_constructor(out, mem::transmute(cx.env()), self.pointer) + neon_runtime::class::metadata_to_constructor( + out, + mem::transmute(cx.env()), + self.pointer, + ) }) } diff --git a/src/object/class/mod.rs b/src/object/class/mod.rs index 276a993ae..9d7d22edf 100644 --- a/src/object/class/mod.rs +++ b/src/object/class/mod.rs @@ -2,31 +2,33 @@ pub(crate) mod internal; +use self::internal::{ + AllocateCallback, ClassMetadata, ConstructCallback, ConstructorCallCallback, MethodCallback, +}; +use borrow::{Borrow, BorrowMut, LoanError, Ref, RefMut}; +use context::internal::Env; +use context::{Context, Lock}; +use handle::{Handle, Managed}; +use neon_runtime; +use neon_runtime::raw; +use object::{Object, This}; +use result::{JsResult, NeonResult, Throw}; use std::any::{Any, TypeId}; +use std::collections::HashMap; use std::mem; use std::os::raw::c_void; use std::slice; -use std::collections::HashMap; -use neon_runtime; -use neon_runtime::raw; -use context::{Context, Lock}; -use context::internal::Env; -use result::{NeonResult, JsResult, Throw}; -use borrow::{Borrow, BorrowMut, Ref, RefMut, LoanError}; -use handle::{Handle, Managed}; -use types::{Value, JsFunction, JsValue, build}; use types::internal::{Callback, ValueInternal}; -use object::{Object, This}; -use self::internal::{ClassMetadata, MethodCallback, ConstructorCallCallback, AllocateCallback, ConstructCallback}; +use types::{build, JsFunction, JsValue, Value}; pub(crate) struct ClassMap { - map: HashMap + map: HashMap, } impl ClassMap { pub(crate) fn new() -> ClassMap { ClassMap { - map: HashMap::new() + map: HashMap::new(), } } @@ -45,11 +47,10 @@ pub struct ClassDescriptor<'a, T: Class> { allocate: AllocateCallback, call: Option, construct: Option>, - methods: Vec<(&'a str, MethodCallback)> + methods: Vec<(&'a str, MethodCallback)>, } impl<'a, T: Class> ClassDescriptor<'a, T> { - /// Constructs a new minimal `ClassDescriptor` with a name and allocator. pub fn new<'b: 'a>(name: &'b str, allocate: AllocateCallback) -> Self { Self { @@ -57,7 +58,7 @@ impl<'a, T: Class> ClassDescriptor<'a, T> { allocate, call: None, construct: None, - methods: Vec::new() + methods: Vec::new(), } } @@ -78,7 +79,6 @@ impl<'a, T: Class> ClassDescriptor<'a, T> { self.methods.push((name, callback)); self } - } extern "C" fn drop_internals(internals: *mut c_void) { @@ -87,7 +87,7 @@ extern "C" fn drop_internals(internals: *mut c_void) { } /// The trait implemented by Neon classes. -/// +/// /// This trait is not intended to be implemented manually; it is implemented automatically by /// creating a class with the `class` syntax of the `declare_types!` macro. pub trait Class: Managed + Any { @@ -104,8 +104,9 @@ pub trait Class: Managed + Any { /// Convenience method for constructing new instances of this class without having to extract the constructor function. fn new<'a, 'b, C: Context<'a>, A, AS>(cx: &mut C, args: AS) -> JsResult<'a, Self> - where A: Value + 'b, - AS: IntoIterator> + where + A: Value + 'b, + AS: IntoIterator>, { let constructor = Self::constructor(cx)?; constructor.construct(cx, args) @@ -129,20 +130,17 @@ unsafe impl This for T { } } -impl Object for T { } +impl Object for T {} pub(crate) trait ClassInternal: Class { fn metadata_opt<'a, C: Context<'a>>(cx: &mut C) -> Option { - cx.env() - .class_map() - .get(&TypeId::of::()) - .copied() + cx.env().class_map().get(&TypeId::of::()).copied() } fn metadata<'a, C: Context<'a>>(cx: &mut C) -> NeonResult { match Self::metadata_opt(cx) { Some(metadata) => Ok(metadata), - None => Self::create(cx) + None => Self::create(cx), } } @@ -152,14 +150,22 @@ pub(crate) trait ClassInternal: Class { let env = cx.env().to_raw(); let allocate = descriptor.allocate.into_c_callback(); - let construct = descriptor.construct.map(|callback| callback.into_c_callback()).unwrap_or_default(); - let call = descriptor.call.unwrap_or_else(ConstructorCallCallback::default::).into_c_callback(); - - let metadata_pointer = neon_runtime::class::create_base(env, - allocate, - construct, - call, - drop_internals::); + let construct = descriptor + .construct + .map(|callback| callback.into_c_callback()) + .unwrap_or_default(); + let call = descriptor + .call + .unwrap_or_else(ConstructorCallCallback::default::) + .into_c_callback(); + + let metadata_pointer = neon_runtime::class::create_base( + env, + allocate, + construct, + call, + drop_internals::, + ); if metadata_pointer.is_null() { return Err(Throw); @@ -169,7 +175,12 @@ pub(crate) trait ClassInternal: Class { // v8::FunctionTemplate has a finalizer that will delete it. let class_name = descriptor.name; - if !neon_runtime::class::set_name(env, metadata_pointer, class_name.as_ptr(), class_name.len() as u32) { + if !neon_runtime::class::set_name( + env, + metadata_pointer, + class_name.as_ptr(), + class_name.len() as u32, + ) { return Err(Throw); } @@ -178,13 +189,19 @@ pub(crate) trait ClassInternal: Class { let callback = method.into_c_callback(); neon_runtime::fun::new_template(out, env, callback) })?; - if !neon_runtime::class::add_method(env, metadata_pointer, name.as_ptr(), name.len() as u32, method.to_raw()) { + if !neon_runtime::class::add_method( + env, + metadata_pointer, + name.as_ptr(), + name.len() as u32, + method.to_raw(), + ) { return Err(Throw); } } let metadata = ClassMetadata { - pointer: metadata_pointer + pointer: metadata_pointer, }; cx.env().class_map().set(TypeId::of::(), metadata); @@ -194,13 +211,11 @@ pub(crate) trait ClassInternal: Class { } } -impl ClassInternal for T { } +impl ClassInternal for T {} impl ValueInternal for T { fn name() -> String { - let mut isolate: Env = unsafe { - mem::transmute(neon_runtime::call::current_isolate()) - }; + let mut isolate: Env = unsafe { mem::transmute(neon_runtime::call::current_isolate()) }; let raw_isolate = unsafe { mem::transmute(isolate) }; let map = isolate.class_map(); match map.get(&TypeId::of::()) { @@ -209,7 +224,8 @@ impl ValueInternal for T { let mut chars = std::ptr::null_mut(); let buf = unsafe { - let len = neon_runtime::class::get_name(&mut chars, raw_isolate, metadata.pointer); + let len = + neon_runtime::class::get_name(&mut chars, raw_isolate, metadata.pointer); slice::from_raw_parts_mut(chars, len) }; @@ -223,14 +239,12 @@ impl ValueInternal for T { let map = env.class_map(); match map.get(&TypeId::of::()) { None => false, - Some(ref metadata) => unsafe { - metadata.has_instance(value.to_raw()) - } + Some(ref metadata) => unsafe { metadata.has_instance(value.to_raw()) }, } } } -impl Value for T { } +impl Value for T {} impl<'a, T: Class> Borrow for &'a T { type Target = &'a mut T::Internals; diff --git a/src/object/mod.rs b/src/object/mod.rs index 17388792a..25e249906 100644 --- a/src/object/mod.rs +++ b/src/object/mod.rs @@ -9,12 +9,12 @@ pub use self::traits::*; #[cfg(feature = "legacy-runtime")] mod traits { - use neon_runtime::raw; + use context::Context; use handle::{Handle, Managed}; - use types::{Value, JsValue, JsArray, build}; + use neon_runtime::raw; + use result::{JsResult, NeonResult, Throw}; use types::utf8::Utf8; - use context::Context; - use result::{NeonResult, JsResult, Throw}; + use types::{build, JsArray, JsValue, Value}; /// A property key in a JavaScript object. pub trait PropertyKey { @@ -56,18 +56,27 @@ mod traits { /// The trait of all object types. pub trait Object: Value { - fn get<'a, C: Context<'a>, K: PropertyKey>(self, cx: &mut C, key: K) -> NeonResult> { - build(cx.env(), |out| { unsafe { key.get_from(out, self.to_raw()) } }) + fn get<'a, C: Context<'a>, K: PropertyKey>( + self, + cx: &mut C, + key: K, + ) -> NeonResult> { + build(cx.env(), |out| unsafe { key.get_from(out, self.to_raw()) }) } fn get_own_property_names<'a, C: Context<'a>>(self, cx: &mut C) -> JsResult<'a, JsArray> { let env = cx.env(); - build(env, |out| { - unsafe { neon_runtime::object::get_own_property_names(out, env.to_raw(), self.to_raw()) } + build(env, |out| unsafe { + neon_runtime::object::get_own_property_names(out, env.to_raw(), self.to_raw()) }) } - fn set<'a, C: Context<'a>, K: PropertyKey, W: Value>(self, _: &mut C, key: K, val: Handle) -> NeonResult { + fn set<'a, C: Context<'a>, K: PropertyKey, W: Value>( + self, + _: &mut C, + key: K, + val: Handle, + ) -> NeonResult { let mut result = false; if unsafe { key.set_from(&mut result, self.to_raw(), val.to_raw()) } { Ok(result) @@ -86,18 +95,18 @@ mod traits { #[cfg(feature = "napi-1")] mod traits { - use neon_runtime::raw; - use handle::{Handle, Managed, Root}; - use types::{Value, JsValue, build}; - use types::utf8::Utf8; - use context::Context; use context::internal::Env; + use context::Context; + use handle::{Handle, Managed, Root}; + use neon_runtime::raw; use result::{NeonResult, Throw}; + use types::utf8::Utf8; + use types::{build, JsValue, Value}; - #[cfg(feature = "napi-6")] - use types::JsArray; #[cfg(feature = "napi-6")] use result::JsResult; + #[cfg(feature = "napi-6")] + use types::JsArray; /// A property key in a JavaScript object. pub trait PropertyKey { @@ -105,7 +114,7 @@ mod traits { self, cx: &mut C, out: &mut raw::Local, - obj: raw::Local + obj: raw::Local, ) -> bool; unsafe fn set_from<'c, C: Context<'c>>( @@ -122,7 +131,7 @@ mod traits { self, cx: &mut C, out: &mut raw::Local, - obj: raw::Local + obj: raw::Local, ) -> bool { neon_runtime::object::get_index(out, cx.env().to_raw(), obj, self) } @@ -143,7 +152,7 @@ mod traits { self, cx: &mut C, out: &mut raw::Local, - obj: raw::Local + obj: raw::Local, ) -> bool { let env = cx.env().to_raw(); @@ -168,7 +177,7 @@ mod traits { self, cx: &mut C, out: &mut raw::Local, - obj: raw::Local + obj: raw::Local, ) -> bool { let (ptr, len) = Utf8::from(self).into_small_unwrap().lower(); let env = cx.env().to_raw(); @@ -192,20 +201,31 @@ mod traits { /// The trait of all object types. pub trait Object: Value { - fn get<'a, C: Context<'a>, K: PropertyKey>(self, cx: &mut C, key: K) -> NeonResult> { - build(cx.env(), |out| { unsafe { key.get_from(cx, out, self.to_raw()) } }) + fn get<'a, C: Context<'a>, K: PropertyKey>( + self, + cx: &mut C, + key: K, + ) -> NeonResult> { + build(cx.env(), |out| unsafe { + key.get_from(cx, out, self.to_raw()) + }) } #[cfg(feature = "napi-6")] fn get_own_property_names<'a, C: Context<'a>>(self, cx: &mut C) -> JsResult<'a, JsArray> { let env = cx.env(); - build(cx.env(), |out| { - unsafe { neon_runtime::object::get_own_property_names(out, env.to_raw(), self.to_raw()) } + build(cx.env(), |out| unsafe { + neon_runtime::object::get_own_property_names(out, env.to_raw(), self.to_raw()) }) } - fn set<'a, C: Context<'a>, K: PropertyKey, W: Value>(self, cx: &mut C, key: K, val: Handle) -> NeonResult { + fn set<'a, C: Context<'a>, K: PropertyKey, W: Value>( + self, + cx: &mut C, + key: K, + val: Handle, + ) -> NeonResult { let mut result = false; if unsafe { key.set_from(cx, &mut result, self.to_raw(), val.to_raw()) } { Ok(result) diff --git a/src/prelude.rs b/src/prelude.rs index adba29f89..79c80cf28 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,24 +1,30 @@ //! A convenience module that re-exports the most commonly-used Neon APIs. -pub use handle::Handle; -pub use types::{JsBuffer, JsArrayBuffer, BinaryData, JsError, Value, JsValue, JsUndefined, JsNull, JsBoolean, JsString, JsNumber, JsObject, JsArray, JsFunction}; -pub use object::Object; -#[cfg(feature = "legacy-runtime")] -pub use object::Class; -pub use borrow::{Borrow, BorrowMut}; -pub use context::{CallKind, Context, ModuleContext, ExecuteContext, ComputeContext, CallContext, FunctionContext, MethodContext, TaskContext}; -pub use result::{NeonResult, JsResult, JsResultExt}; -#[cfg(feature = "legacy-runtime")] -pub use task::Task; -#[cfg(all(not(feature = "napi-1"), feature = "event-handler-api"))] -pub use event::EventHandler; -pub use crate::register_module; #[cfg(feature = "legacy-runtime")] pub use crate::declare_types; +#[cfg(all(feature = "napi-4", feature = "event-queue-api"))] +pub use crate::event::{EventQueue, EventQueueError}; +pub use crate::register_module; #[cfg(feature = "napi-1")] pub use crate::{ handle::Root, - types::boxed::{Finalize, JsBox} + types::boxed::{Finalize, JsBox}, +}; +pub use borrow::{Borrow, BorrowMut}; +pub use context::{ + CallContext, CallKind, ComputeContext, Context, ExecuteContext, FunctionContext, MethodContext, + ModuleContext, TaskContext, +}; +#[cfg(all(not(feature = "napi-1"), feature = "event-handler-api"))] +pub use event::EventHandler; +pub use handle::Handle; +#[cfg(feature = "legacy-runtime")] +pub use object::Class; +pub use object::Object; +pub use result::{JsResult, JsResultExt, NeonResult}; +#[cfg(feature = "legacy-runtime")] +pub use task::Task; +pub use types::{ + BinaryData, JsArray, JsArrayBuffer, JsBoolean, JsBuffer, JsError, JsFunction, JsNull, JsNumber, + JsObject, JsString, JsUndefined, JsValue, Value, }; -#[cfg(all(feature = "napi-4", feature = "event-queue-api"))] -pub use crate::event::{EventQueue, EventQueueError}; diff --git a/src/result/mod.rs b/src/result/mod.rs index abb184b1c..75679f323 100644 --- a/src/result/mod.rs +++ b/src/result/mod.rs @@ -1,13 +1,13 @@ //! Types and traits for working with JavaScript exceptions. -use std::fmt::{Display, Formatter, Result as FmtResult}; +use context::Context; use handle::Handle; +use std::fmt::{Display, Formatter, Result as FmtResult}; use types::Value; -use context::Context; /// An error sentinel type used by `NeonResult` (and `JsResult`) to indicate that the JavaScript engine /// has entered into a throwing state. -/// +/// /// `Throw` deliberately does not implement `std::error::Error`, because it's generally not a good idea /// to chain JavaScript exceptions with other kinds of Rust errors, since entering into the throwing /// state means that the JavaScript engine is unavailable until the exception is handled. diff --git a/src/task/mod.rs b/src/task/mod.rs index d87ecfff5..b4a8299ab 100644 --- a/src/task/mod.rs +++ b/src/task/mod.rs @@ -3,12 +3,12 @@ use std::marker::{Send, Sized}; use std::os::raw::c_void; -use types::{Value, JsFunction}; -use result::JsResult; -use handle::{Handle, Managed}; use context::TaskContext; +use handle::{Handle, Managed}; use neon_runtime; use neon_runtime::raw; +use result::JsResult; +use types::{JsFunction, Value}; /// A Rust task that can be executed in the background on the Node thread pool. pub trait Task: Send + Sized + 'static { @@ -25,7 +25,11 @@ pub trait Task: Send + Sized + 'static { fn perform(&self) -> Result; /// Convert the result of the task to a JavaScript value to be passed to the asynchronous callback. This method is executed on the main thread at some point after the background task is completed. - fn complete(self, cx: TaskContext, result: Result) -> JsResult; + fn complete( + self, + cx: TaskContext, + result: Result, + ) -> JsResult; /// Schedule a task to be executed on a background thread. /// @@ -39,10 +43,12 @@ pub trait Task: Send + Sized + 'static { let self_raw = Box::into_raw(boxed_self); let callback_raw = callback.to_raw(); unsafe { - neon_runtime::task::schedule(self_raw.cast(), - perform_task::, - complete_task::, - callback_raw); + neon_runtime::task::schedule( + self_raw.cast(), + perform_task::, + complete_task::, + callback_raw, + ); } } } @@ -54,7 +60,11 @@ unsafe extern "C" fn perform_task(task: *mut c_void) -> *mut c_void { Box::into_raw(Box::new(result)).cast() } -unsafe extern "C" fn complete_task(task: *mut c_void, result: *mut c_void, out: &mut raw::Local) { +unsafe extern "C" fn complete_task( + task: *mut c_void, + result: *mut c_void, + out: &mut raw::Local, +) { let result: Result = *Box::from_raw(result.cast()); let task: Box = Box::from_raw(task.cast()); TaskContext::with(|cx| { diff --git a/src/types/binary.rs b/src/types/binary.rs index 85ae77a87..b7a2e31b5 100644 --- a/src/types/binary.rs +++ b/src/types/binary.rs @@ -1,21 +1,21 @@ //! Types and traits representing binary JavaScript data. -use std::marker::PhantomData; -use std::mem::{self, MaybeUninit}; -use std::os::raw::c_void; -use std::slice; -use context::{Context, Lock}; -use context::internal::Env; -use borrow::{Borrow, BorrowMut, Ref, RefMut, LoanError}; use borrow::internal::Pointer; +use borrow::{Borrow, BorrowMut, LoanError, Ref, RefMut}; +use context::internal::Env; +use context::{Context, Lock}; #[cfg(feature = "napi-1")] use handle::Handle; use handle::Managed; -use types::{Value, Object, build}; -use types::internal::ValueInternal; -use result::JsResult; use neon_runtime; use neon_runtime::raw; +use result::JsResult; +use std::marker::PhantomData; +use std::mem::{self, MaybeUninit}; +use std::os::raw::c_void; +use std::slice; +use types::internal::ValueInternal; +use types::{build, Object, Value}; /// The Node [`Buffer`](https://nodejs.org/api/buffer.html) type. #[repr(C)] @@ -23,17 +23,23 @@ use neon_runtime::raw; pub struct JsBuffer(raw::Local); impl JsBuffer { - /// Constructs a new `Buffer` object, safely zero-filled. pub fn new<'a, C: Context<'a>>(cx: &mut C, size: u32) -> JsResult<'a, JsBuffer> { let env = cx.env(); - build(env, |out| { unsafe { neon_runtime::buffer::new(env.to_raw(), out, size) } }) + build(env, |out| unsafe { + neon_runtime::buffer::new(env.to_raw(), out, size) + }) } /// Constructs a new `Buffer` object, safely zero-filled. - pub unsafe fn uninitialized<'a, C: Context<'a>>(cx: &mut C, size: u32) -> JsResult<'a, JsBuffer> { + pub unsafe fn uninitialized<'a, C: Context<'a>>( + cx: &mut C, + size: u32, + ) -> JsResult<'a, JsBuffer> { let env = cx.env(); - build(env, |out| { neon_runtime::buffer::uninitialized(env.to_raw(), out, size) }) + build(env, |out| { + neon_runtime::buffer::uninitialized(env.to_raw(), out, size) + }) } #[cfg(feature = "napi-1")] @@ -44,31 +50,35 @@ impl JsBuffer { T: AsMut<[u8]> + Send, { let env = cx.env().to_raw(); - let value = unsafe { - neon_runtime::buffer::new_external(env, data) - }; + let value = unsafe { neon_runtime::buffer::new_external(env, data) }; Handle::new_internal(JsBuffer(value)) } } impl Managed for JsBuffer { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_env: Env, h: raw::Local) -> Self { JsBuffer(h) } + fn from_raw(_env: Env, h: raw::Local) -> Self { + JsBuffer(h) + } } impl ValueInternal for JsBuffer { - fn name() -> String { "Buffer".to_string() } + fn name() -> String { + "Buffer".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_buffer(env.to_raw(), other.to_raw()) } } } -impl Value for JsBuffer { } +impl Value for JsBuffer {} -impl Object for JsBuffer { } +impl Object for JsBuffer {} /// The standard JS [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) type. #[repr(C)] @@ -78,42 +88,48 @@ pub struct JsArrayBuffer(raw::Local); impl JsArrayBuffer { /// Constructs a new `ArrayBuffer` object with the given size, in bytes. pub fn new<'a, C: Context<'a>>(cx: &mut C, size: u32) -> JsResult<'a, JsArrayBuffer> { - build(cx.env(), |out| { unsafe { neon_runtime::arraybuffer::new(out, mem::transmute(cx.env()), size) } }) + build(cx.env(), |out| unsafe { + neon_runtime::arraybuffer::new(out, mem::transmute(cx.env()), size) + }) } #[cfg(feature = "napi-1")] /// Construct a new `ArrayBuffer` from bytes allocated by Rust pub fn external<'a, C, T>(cx: &mut C, data: T) -> Handle<'a, JsArrayBuffer> - where - C: Context<'a>, - T: AsMut<[u8]> + Send, + where + C: Context<'a>, + T: AsMut<[u8]> + Send, { let env = cx.env().to_raw(); - let value = unsafe { - neon_runtime::arraybuffer::new_external(env, data) - }; + let value = unsafe { neon_runtime::arraybuffer::new_external(env, data) }; Handle::new_internal(JsArrayBuffer(value)) } } impl Managed for JsArrayBuffer { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_env: Env, h: raw::Local) -> Self { JsArrayBuffer(h) } + fn from_raw(_env: Env, h: raw::Local) -> Self { + JsArrayBuffer(h) + } } impl ValueInternal for JsArrayBuffer { - fn name() -> String { "ArrayBuffer".to_string() } + fn name() -> String { + "ArrayBuffer".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_arraybuffer(env.to_raw(), other.to_raw()) } } } -impl Value for JsArrayBuffer { } +impl Value for JsArrayBuffer {} -impl Object for JsArrayBuffer { } +impl Object for JsArrayBuffer {} /// A reference to the internal backing buffer data of a `Buffer` or `ArrayBuffer` object, which can be accessed via the `Borrow` and `BorrowMut` traits. #[derive(Clone, Copy)] @@ -121,7 +137,7 @@ impl Object for JsArrayBuffer { } pub struct BinaryData<'a> { base: *mut c_void, size: usize, - phantom: PhantomData<&'a ()> + phantom: PhantomData<&'a ()>, } unsafe impl<'a> Pointer for BinaryData<'a> { @@ -135,25 +151,24 @@ unsafe impl<'a> Pointer for BinaryData<'a> { } /// The trait for element types by which a buffer's binary data can be indexed. -pub trait BinaryViewType: Sized { } - -impl BinaryViewType for u8 { } -impl BinaryViewType for i8 { } -impl BinaryViewType for u16 { } -impl BinaryViewType for i16 { } -impl BinaryViewType for u32 { } -impl BinaryViewType for i32 { } -impl BinaryViewType for u64 { } -impl BinaryViewType for i64 { } -impl BinaryViewType for f32 { } -impl BinaryViewType for f64 { } +pub trait BinaryViewType: Sized {} + +impl BinaryViewType for u8 {} +impl BinaryViewType for i8 {} +impl BinaryViewType for u16 {} +impl BinaryViewType for i16 {} +impl BinaryViewType for u32 {} +impl BinaryViewType for i32 {} +impl BinaryViewType for u64 {} +impl BinaryViewType for i64 {} +impl BinaryViewType for f32 {} +impl BinaryViewType for f64 {} impl<'a> BinaryData<'a> { - /// Produces an immutable slice as a view into the contents of this buffer. - /// + /// /// # Example: - /// + /// /// ```no_run /// # use neon::prelude::*; /// # fn get_x_and_y(mut cx: FunctionContext) -> JsResult { @@ -177,9 +192,9 @@ impl<'a> BinaryData<'a> { } /// Produces a mutable slice as a view into the contents of this buffer. - /// + /// /// # Example: - /// + /// /// ```no_run /// # use neon::prelude::*; /// # fn modify_buffer(mut cx: FunctionContext) -> JsResult { @@ -222,13 +237,12 @@ impl<'a> Borrow for &'a JsBuffer { // Initialize pointer unsafe { let pointer = data.as_mut_ptr(); - (*pointer).size = neon_runtime::buffer::data(guard.env.to_raw(), &mut (*pointer).base, self.to_raw()); + (*pointer).size = + neon_runtime::buffer::data(guard.env.to_raw(), &mut (*pointer).base, self.to_raw()); } // UB if pointer is not initialized! - unsafe { - Ref::new(guard, data.assume_init()) - } + unsafe { Ref::new(guard, data.assume_init()) } } } @@ -241,19 +255,21 @@ impl<'a> Borrow for &'a mut JsBuffer { } impl<'a> BorrowMut for &'a mut JsBuffer { - fn try_borrow_mut<'b>(self, guard: &'b Lock<'b>) -> Result, LoanError> { + fn try_borrow_mut<'b>( + self, + guard: &'b Lock<'b>, + ) -> Result, LoanError> { let mut data = MaybeUninit::::uninit(); // Initialize pointer unsafe { let pointer = data.as_mut_ptr(); - (*pointer).size = neon_runtime::buffer::data(guard.env.to_raw(), &mut (*pointer).base, self.to_raw()); + (*pointer).size = + neon_runtime::buffer::data(guard.env.to_raw(), &mut (*pointer).base, self.to_raw()); } // UB if pointer is not initialized! - unsafe { - RefMut::new(guard, data.assume_init()) - } + unsafe { RefMut::new(guard, data.assume_init()) } } } @@ -266,13 +282,15 @@ impl<'a> Borrow for &'a JsArrayBuffer { // Initialize pointer unsafe { let pointer = data.as_mut_ptr(); - (*pointer).size = neon_runtime::arraybuffer::data(guard.env.to_raw(), &mut (*pointer).base, self.to_raw()); + (*pointer).size = neon_runtime::arraybuffer::data( + guard.env.to_raw(), + &mut (*pointer).base, + self.to_raw(), + ); } // UB if pointer is not initialized! - unsafe { - Ref::new(guard, data.assume_init()) - } + unsafe { Ref::new(guard, data.assume_init()) } } } @@ -285,18 +303,23 @@ impl<'a> Borrow for &'a mut JsArrayBuffer { } impl<'a> BorrowMut for &'a mut JsArrayBuffer { - fn try_borrow_mut<'b>(self, guard: &'b Lock<'b>) -> Result, LoanError> { + fn try_borrow_mut<'b>( + self, + guard: &'b Lock<'b>, + ) -> Result, LoanError> { let mut data = MaybeUninit::::uninit(); // Initialize pointer unsafe { let pointer = data.as_mut_ptr(); - (*pointer).size = neon_runtime::arraybuffer::data(guard.env.to_raw(), &mut (*pointer).base, self.to_raw()); + (*pointer).size = neon_runtime::arraybuffer::data( + guard.env.to_raw(), + &mut (*pointer).base, + self.to_raw(), + ); } // UB if pointer is not initialized! - unsafe { - RefMut::new(guard, data.assume_init()) - } + unsafe { RefMut::new(guard, data.assume_init()) } } } diff --git a/src/types/boxed.rs b/src/types/boxed.rs index 3b9e6378a..281dea522 100644 --- a/src/types/boxed.rs +++ b/src/types/boxed.rs @@ -1,12 +1,12 @@ use std::any::{self, Any}; use std::ops::Deref; -use neon_runtime::raw; use neon_runtime::external; +use neon_runtime::raw; -use crate::context::{Context, FinalizeContext}; use crate::context::internal::Env; -use crate::handle::{Managed, Handle}; +use crate::context::{Context, FinalizeContext}; +use crate::handle::{Handle, Managed}; use crate::types::internal::ValueInternal; use crate::types::Value; @@ -89,38 +89,38 @@ type BoxAny = Box; /// pub fn new(name: String) -> Self { /// Person { name } /// } -/// +/// /// pub fn set_name(&mut self, name: String) { /// self.name = name; /// } -/// +/// /// pub fn greet(&self) -> String { /// format!("Hello, {}!", self.name) /// } /// } -/// +/// /// fn person_new(mut cx: FunctionContext) -> JsResult { /// let name = cx.argument::(0)?.value(&mut cx); /// let person = RefCell::new(Person::new(name)); -/// +/// /// Ok(cx.boxed(person)) /// } -/// +/// /// fn person_set_name(mut cx: FunctionContext) -> JsResult { /// let person = cx.argument::(0)?; /// let mut person = person.borrow_mut(); /// let name = cx.argument::(1)?.value(&mut cx); -/// +/// /// person.set_name(name); -/// +/// /// Ok(cx.undefined()) /// } -/// +/// /// fn person_greet(mut cx: FunctionContext) -> JsResult { /// let person = cx.argument::(0)?; /// let person = person.borrow(); /// let greeting = person.greet(); -/// +/// /// Ok(cx.string(greeting)) /// } pub struct JsBox { @@ -146,8 +146,7 @@ impl std::fmt::Debug for JsBox { // Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny> /// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`. unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> { - external::deref::(env.to_raw(), local) - .map(|v| &*v) + external::deref::(env.to_raw(), local).map(|v| &*v) } // Custom `Clone` implementation since `T` might not be `Clone` @@ -162,7 +161,7 @@ impl Clone for JsBox { impl Copy for JsBox {} -impl Value for JsBox { } +impl Value for JsBox {} impl Managed for JsBox { fn to_raw(self) -> raw::Local { @@ -175,10 +174,7 @@ impl Managed for JsBox { .downcast_ref() .expect("Failed to downcast Any"); - Self { - local, - raw_data, - } + Self { local, raw_data } } } @@ -199,10 +195,7 @@ impl ValueInternal for JsBox { // Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>` data.and_then(|v| v.downcast_ref()) - .map(|raw_data| Self { - local, - raw_data, - }) + .map(|raw_data| Self { local, raw_data }) } } @@ -239,23 +232,15 @@ impl JsBox { let data = *data.downcast::().unwrap(); let env = unsafe { std::mem::transmute(env) }; - FinalizeContext::with( - env, - move |mut cx| data.finalize(&mut cx), - ); + FinalizeContext::with(env, move |mut cx| data.finalize(&mut cx)); } let v = Box::new(value) as BoxAny; // Since this value was just constructed, we know it is `T` let raw_data = &*v as *const dyn Any as *const T; - let local = unsafe { - external::create(cx.env().to_raw(), v, finalizer::) - }; - - Handle::new_internal(Self { - local, - raw_data, - }) + let local = unsafe { external::create(cx.env().to_raw(), v, finalizer::) }; + + Handle::new_internal(Self { local, raw_data }) } } diff --git a/src/types/date.rs b/src/types/date.rs index 0e96643e0..53cbed682 100644 --- a/src/types/date.rs +++ b/src/types/date.rs @@ -1,26 +1,30 @@ -use std::fmt; -use std::fmt::Debug; -use std::error::Error; +use super::{Value, ValueInternal}; +use context::internal::Env; +use context::Context; +use handle::{Handle, Managed}; use neon_runtime; use neon_runtime::raw; -use context::{Context}; -use context::internal::Env; +use object::Object; use result::{JsResult, JsResultExt}; -use object::{Object}; -use handle::{Handle, Managed}; -use super::{Value, ValueInternal}; +use std::error::Error; +use std::fmt; +use std::fmt::Debug; /// A JavaScript Date object #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct JsDate(raw::Local); -impl Value for JsDate { } +impl Value for JsDate {} impl Managed for JsDate { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsDate(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsDate(h) + } } /// The Error struct for a Date @@ -72,19 +76,20 @@ impl JsDate { /// Creates a new Date. It errors when `value` is outside the range of valid JavaScript Date values. When `value` /// is `NaN`, the operation will succeed but with an invalid Date - pub fn new<'a, C: Context<'a>, T: Into>(cx: &mut C, value: T) -> Result, DateError> { + pub fn new<'a, C: Context<'a>, T: Into>( + cx: &mut C, + value: T, + ) -> Result, DateError> { let env = cx.env().to_raw(); let time = value.into(); if time > JsDate::MAX_VALUE { - return Err(DateError(DateErrorKind::Overflow)) + return Err(DateError(DateErrorKind::Overflow)); } else if time < JsDate::MIN_VALUE { - return Err(DateError(DateErrorKind::Underflow)) + return Err(DateError(DateErrorKind::Underflow)); } - let local = unsafe { - neon_runtime::date::new_date(env, time) - }; + let local = unsafe { neon_runtime::date::new_date(env, time) }; let date = Handle::new_internal(JsDate(local)); Ok(date) } @@ -93,18 +98,14 @@ impl JsDate { /// values will be treated as NaN pub fn new_lossy<'a, C: Context<'a>, V: Into>(cx: &mut C, value: V) -> Handle<'a, JsDate> { let env = cx.env().to_raw(); - let local = unsafe { - neon_runtime::date::new_date(env, value.into()) - }; + let local = unsafe { neon_runtime::date::new_date(env, value.into()) }; Handle::new_internal(JsDate(local)) } /// Gets the Date's value. An invalid Date will return `std::f64::NaN` pub fn value<'a, C: Context<'a>>(self, cx: &mut C) -> f64 { let env = cx.env().to_raw(); - unsafe { - neon_runtime::date::value(env, self.to_raw()) - } + unsafe { neon_runtime::date::value(env, self.to_raw()) } } /// Checks if the Date's value is valid. A Date is valid if its value is between @@ -116,11 +117,13 @@ impl JsDate { } impl ValueInternal for JsDate { - fn name() -> String { "object".to_string() } + fn name() -> String { + "object".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_date(env.to_raw(), other.to_raw()) } } } -impl Object for JsDate { } +impl Object for JsDate {} diff --git a/src/types/error.rs b/src/types/error.rs index db5f60a0f..de81ea9d1 100644 --- a/src/types/error.rs +++ b/src/types/error.rs @@ -1,16 +1,16 @@ //! Types and traits representing JavaScript error values. -use std::panic::{UnwindSafe, catch_unwind}; +use std::panic::{catch_unwind, UnwindSafe}; use neon_runtime; use neon_runtime::raw; -use context::Context; use context::internal::Env; +use context::Context; use result::{NeonResult, Throw}; -use types::{Value, Object, Handle, Managed, build}; use types::internal::ValueInternal; use types::utf8::Utf8; +use types::{build, Handle, Managed, Object, Value}; /// A JS `Error` object. #[repr(C)] @@ -18,26 +18,35 @@ use types::utf8::Utf8; pub struct JsError(raw::Local); impl Managed for JsError { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsError(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsError(h) + } } impl ValueInternal for JsError { - fn name() -> String { "Error".to_string() } + fn name() -> String { + "Error".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_error(env.to_raw(), other.to_raw()) } } } -impl Value for JsError { } +impl Value for JsError {} -impl Object for JsError { } +impl Object for JsError {} impl JsError { /// Creates a direct instance of the [`Error`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error) class. - pub fn error<'a, C: Context<'a>, S: AsRef>(cx: &mut C, msg: S) -> NeonResult> { + pub fn error<'a, C: Context<'a>, S: AsRef>( + cx: &mut C, + msg: S, + ) -> NeonResult> { let msg = cx.string(msg.as_ref()); build(cx.env(), |out| unsafe { neon_runtime::error::new_error(cx.env().to_raw(), out, msg.to_raw()); @@ -46,7 +55,10 @@ impl JsError { } /// Creates an instance of the [`TypeError`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypeError) class. - pub fn type_error<'a, C: Context<'a>, S: AsRef>(cx: &mut C, msg: S) -> NeonResult> { + pub fn type_error<'a, C: Context<'a>, S: AsRef>( + cx: &mut C, + msg: S, + ) -> NeonResult> { let msg = cx.string(msg.as_ref()); build(cx.env(), |out| unsafe { neon_runtime::error::new_type_error(cx.env().to_raw(), out, msg.to_raw()); @@ -55,7 +67,10 @@ impl JsError { } /// Creates an instance of the [`RangeError`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RangeError) class. - pub fn range_error<'a, C: Context<'a>, S: AsRef>(cx: &mut C, msg: S) -> NeonResult> { + pub fn range_error<'a, C: Context<'a>, S: AsRef>( + cx: &mut C, + msg: S, + ) -> NeonResult> { let msg = cx.string(msg.as_ref()); build(cx.env(), |out| unsafe { neon_runtime::error::new_range_error(cx.env().to_raw(), out, msg.to_raw()); @@ -64,8 +79,11 @@ impl JsError { } } -pub(crate) fn convert_panics NeonResult>(env: Env, f: F) -> NeonResult { - match catch_unwind(|| { f() }) { +pub(crate) fn convert_panics NeonResult>( + env: Env, + f: F, +) -> NeonResult { + match catch_unwind(|| f()) { Ok(result) => result, Err(panic) => { let msg = if let Some(string) = panic.downcast_ref::() { diff --git a/src/types/internal.rs b/src/types/internal.rs index 1f26c121a..f2b384a21 100644 --- a/src/types/internal.rs +++ b/src/types/internal.rs @@ -1,14 +1,14 @@ -use std::mem; -use std::os::raw::c_void; +use super::Value; +use context::internal::Env; +use context::{CallbackInfo, FunctionContext}; use neon_runtime; use neon_runtime::call::CCallback; use neon_runtime::raw; -use context::{CallbackInfo, FunctionContext}; -use context::internal::Env; -use types::error::convert_panics; -use types::{JsObject, Handle, Managed}; use result::JsResult; -use super::Value; +use std::mem; +use std::os::raw::c_void; +use types::error::convert_panics; +use types::{Handle, JsObject, Managed}; pub trait ValueInternal: Managed + 'static { fn name() -> String; @@ -39,7 +39,7 @@ impl Callback<()> for FunctionCallback { let data = info.data(env); let dynamic_callback: fn(FunctionContext) -> JsResult = mem::transmute(neon_runtime::fun::get_dynamic_callback(env.to_raw(), data)); - if let Ok(value) = convert_panics(env, || { dynamic_callback(cx) }) { + if let Ok(value) = convert_panics(env, || dynamic_callback(cx)) { info.set_return(value); } }) @@ -59,7 +59,7 @@ impl Callback for FunctionCallback { let data = info.data(env); let dynamic_callback: fn(FunctionContext) -> JsResult = mem::transmute(neon_runtime::fun::get_dynamic_callback(env.to_raw(), data)); - if let Ok(value) = convert_panics(env, || { dynamic_callback(cx) }) { + if let Ok(value) = convert_panics(env, || dynamic_callback(cx)) { value.to_raw() } else { // We do not have a Js Value to return, most likely due to an exception. @@ -109,7 +109,7 @@ pub(crate) trait Callback: Sized { let invoke = Self::invoke_compat; CCallback { static_callback: unsafe { mem::transmute(invoke as usize) }, - dynamic_callback: self.into_ptr() + dynamic_callback: self.into_ptr(), } } } diff --git a/src/types/mod.rs b/src/types/mod.rs index b46548ee5..048005b93 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -3,38 +3,41 @@ pub(crate) mod binary; #[cfg(feature = "napi-1")] pub(crate) mod boxed; -pub(crate) mod error; #[cfg(feature = "napi-5")] pub(crate) mod date; +pub(crate) mod error; pub(crate) mod internal; pub(crate) mod utf8; -use std::fmt; -use std::os::raw::c_void; -use std::marker::PhantomData; -use std::fmt::Debug; +use self::internal::{FunctionCallback, ValueInternal}; +use self::utf8::Utf8; +use context::internal::Env; +use context::{Context, FunctionContext}; +use handle::internal::SuperType; +use handle::{Handle, Managed}; use neon_runtime; use neon_runtime::raw; -use context::{Context, FunctionContext}; -use context::internal::Env; -use result::{NeonResult, JsResult, Throw, JsResultExt}; use object::{Object, This}; -use handle::{Handle, Managed}; -use handle::internal::SuperType; -use types::internal::Callback; +use result::{JsResult, JsResultExt, NeonResult, Throw}; use smallvec::SmallVec; -use self::internal::{ValueInternal, FunctionCallback}; -use self::utf8::Utf8; +use std::fmt; +use std::fmt::Debug; +use std::marker::PhantomData; +use std::os::raw::c_void; +use types::internal::Callback; -pub use self::binary::{JsBuffer, JsArrayBuffer, BinaryData, BinaryViewType}; +pub use self::binary::{BinaryData, BinaryViewType, JsArrayBuffer, JsBuffer}; #[cfg(feature = "napi-1")] pub use self::boxed::JsBox; -pub use self::error::JsError; #[cfg(feature = "napi-5")] -pub use self::date::{JsDate, DateError, DateErrorKind}; +pub use self::date::{DateError, DateErrorKind, JsDate}; +pub use self::error::JsError; -pub(crate) fn build<'a, T: Managed, F: FnOnce(&mut raw::Local) -> bool>(env: Env, init: F) -> JsResult<'a, T> { +pub(crate) fn build<'a, T: Managed, F: FnOnce(&mut raw::Local) -> bool>( + env: Env, + init: F, +) -> JsResult<'a, T> { unsafe { let mut local: raw::Local = std::mem::zeroed(); if init(&mut local) { @@ -61,8 +64,8 @@ impl SuperType for JsObject { pub trait Value: ValueInternal { fn to_string<'a, C: Context<'a>>(self, cx: &mut C) -> JsResult<'a, JsString> { let env = cx.env(); - build(env, |out| { - unsafe { neon_runtime::convert::to_string(out, env.to_raw(), self.to_raw()) } + build(env, |out| unsafe { + neon_runtime::convert::to_string(out, env.to_raw(), self.to_raw()) }) } @@ -76,16 +79,22 @@ pub trait Value: ValueInternal { #[derive(Clone, Copy)] pub struct JsValue(raw::Local); -impl Value for JsValue { } +impl Value for JsValue {} impl Managed for JsValue { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsValue(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsValue(h) + } } impl ValueInternal for JsValue { - fn name() -> String { "any".to_string() } + fn name() -> String { + "any".to_string() + } fn is_typeof(_env: Env, _other: Other) -> bool { true @@ -144,12 +153,16 @@ impl JsUndefined { } } -impl Value for JsUndefined { } +impl Value for JsUndefined {} impl Managed for JsUndefined { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsUndefined(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsUndefined(h) + } } unsafe impl This for JsUndefined { @@ -165,7 +178,9 @@ unsafe impl This for JsUndefined { } impl ValueInternal for JsUndefined { - fn name() -> String { "undefined".to_string() } + fn name() -> String { + "undefined".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_undefined(env.to_raw(), other.to_raw()) } @@ -197,16 +212,22 @@ impl JsNull { } } -impl Value for JsNull { } +impl Value for JsNull {} impl Managed for JsNull { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsNull(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsNull(h) + } } impl ValueInternal for JsNull { - fn name() -> String { "null".to_string() } + fn name() -> String { + "null".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_null(env.to_raw(), other.to_raw()) } @@ -233,30 +254,32 @@ impl JsBoolean { #[cfg(feature = "legacy-runtime")] pub fn value(self) -> bool { - unsafe { - neon_runtime::primitive::boolean_value(self.to_raw()) - } + unsafe { neon_runtime::primitive::boolean_value(self.to_raw()) } } #[cfg(feature = "napi-1")] pub fn value<'a, C: Context<'a>>(self, cx: &mut C) -> bool { let env = cx.env().to_raw(); - unsafe { - neon_runtime::primitive::boolean_value(env, self.to_raw()) - } + unsafe { neon_runtime::primitive::boolean_value(env, self.to_raw()) } } } -impl Value for JsBoolean { } +impl Value for JsBoolean {} impl Managed for JsBoolean { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsBoolean(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsBoolean(h) + } } impl ValueInternal for JsBoolean { - fn name() -> String { "boolean".to_string() } + fn name() -> String { + "boolean".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_boolean(env.to_raw(), other.to_raw()) } @@ -285,21 +308,27 @@ impl<'a> JsResultExt<'a, JsString> for StringResult<'a> { fn or_throw<'b, C: Context<'b>>(self, cx: &mut C) -> JsResult<'a, JsString> { match self { Ok(v) => Ok(v), - Err(e) => cx.throw_range_error(&e.to_string()) + Err(e) => cx.throw_range_error(&e.to_string()), } } } -impl Value for JsString { } +impl Value for JsString {} impl Managed for JsString { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsString(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsString(h) + } } impl ValueInternal for JsString { - fn name() -> String { "string".to_string() } + fn name() -> String { + "string".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_string(env.to_raw(), other.to_raw()) } @@ -309,18 +338,14 @@ impl ValueInternal for JsString { impl JsString { #[cfg(feature = "legacy-runtime")] pub fn size(self) -> isize { - unsafe { - neon_runtime::string::utf8_len(self.to_raw()) - } + unsafe { neon_runtime::string::utf8_len(self.to_raw()) } } #[cfg(feature = "napi-1")] pub fn size<'a, C: Context<'a>>(self, cx: &mut C) -> isize { let env = cx.env().to_raw(); - unsafe { - neon_runtime::string::utf8_len(env, self.to_raw()) - } + unsafe { neon_runtime::string::utf8_len(env, self.to_raw()) } } #[cfg(feature = "legacy-runtime")] @@ -357,7 +382,7 @@ impl JsString { let val = val.as_ref(); match JsString::new_internal(cx.env(), val) { Some(s) => Ok(s), - None => Err(StringOverflow(val.len())) + None => Err(StringOverflow(val.len())), } } @@ -399,30 +424,32 @@ impl JsNumber { #[cfg(feature = "legacy-runtime")] pub fn value(self) -> f64 { - unsafe { - neon_runtime::primitive::number_value(self.to_raw()) - } + unsafe { neon_runtime::primitive::number_value(self.to_raw()) } } #[cfg(feature = "napi-1")] pub fn value<'a, C: Context<'a>>(self, cx: &mut C) -> f64 { let env = cx.env().to_raw(); - unsafe { - neon_runtime::primitive::number_value(env, self.to_raw()) - } + unsafe { neon_runtime::primitive::number_value(env, self.to_raw()) } } } -impl Value for JsNumber { } +impl Value for JsNumber {} impl Managed for JsNumber { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsNumber(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsNumber(h) + } } impl ValueInternal for JsNumber { - fn name() -> String { "number".to_string() } + fn name() -> String { + "number".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_number(env.to_raw(), other.to_raw()) } @@ -434,12 +461,16 @@ impl ValueInternal for JsNumber { #[derive(Clone, Copy)] pub struct JsObject(raw::Local); -impl Value for JsObject { } +impl Value for JsObject {} impl Managed for JsObject { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsObject(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsObject(h) + } } unsafe impl This for JsObject { @@ -455,14 +486,16 @@ unsafe impl This for JsObject { } impl ValueInternal for JsObject { - fn name() -> String { "object".to_string() } + fn name() -> String { + "object".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_object(env.to_raw(), other.to_raw()) } } } -impl Object for JsObject { } +impl Object for JsObject {} impl JsObject { pub fn new<'a, C: Context<'a>>(c: &mut C) -> Handle<'a, JsObject> { @@ -470,9 +503,7 @@ impl JsObject { } pub(crate) fn new_internal<'a>(env: Env) -> Handle<'a, JsObject> { - JsObject::build(|out| { - unsafe { neon_runtime::object::new(out, env.to_raw()) } - }) + JsObject::build(|out| unsafe { neon_runtime::object::new(out, env.to_raw()) }) } pub(crate) fn build<'a, F: FnOnce(&mut raw::Local)>(init: F) -> Handle<'a, JsObject> { @@ -518,9 +549,7 @@ impl JsArray { } fn len_inner(self, env: Env) -> u32 { - unsafe { - neon_runtime::array::len(env.to_raw(), self.to_raw()) - } + unsafe { neon_runtime::array::len(env.to_raw(), self.to_raw()) } } #[cfg(feature = "legacy-runtime")] @@ -544,39 +573,49 @@ impl JsArray { } } -impl Value for JsArray { } +impl Value for JsArray {} impl Managed for JsArray { - fn to_raw(self) -> raw::Local { self.0 } + fn to_raw(self) -> raw::Local { + self.0 + } - fn from_raw(_: Env, h: raw::Local) -> Self { JsArray(h) } + fn from_raw(_: Env, h: raw::Local) -> Self { + JsArray(h) + } } impl ValueInternal for JsArray { - fn name() -> String { "Array".to_string() } + fn name() -> String { + "Array".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_array(env.to_raw(), other.to_raw()) } } } -impl Object for JsArray { } +impl Object for JsArray {} /// A JavaScript function object. #[repr(C)] #[derive(Clone, Copy)] -pub struct JsFunction { +pub struct JsFunction { raw: raw::Local, - marker: PhantomData + marker: PhantomData, } -impl Object for JsFunction { } +impl Object for JsFunction {} // Maximum number of function arguments in V8. const V8_ARGC_LIMIT: usize = 65535; -unsafe fn prepare_call<'a, 'b, C: Context<'a>, A>(cx: &mut C, args: &mut [Handle<'b, A>]) -> NeonResult<(i32, *mut c_void)> - where A: Value + 'b +unsafe fn prepare_call<'a, 'b, C: Context<'a>, A>( + cx: &mut C, + args: &mut [Handle<'b, A>], +) -> NeonResult<(i32, *mut c_void)> +where + A: Value + 'b, { let argv = args.as_mut_ptr(); let argc = args.len(); @@ -587,9 +626,13 @@ unsafe fn prepare_call<'a, 'b, C: Context<'a>, A>(cx: &mut C, args: &mut [Handle } impl JsFunction { - pub fn new<'a, C, U>(cx: &mut C, f: fn(FunctionContext) -> JsResult) -> JsResult<'a, JsFunction> - where C: Context<'a>, - U: Value + pub fn new<'a, C, U>( + cx: &mut C, + f: fn(FunctionContext) -> JsResult, + ) -> JsResult<'a, JsFunction> + where + C: Context<'a>, + U: Value, { build(cx.env(), |out| { let env = cx.env().to_raw(); @@ -602,51 +645,58 @@ impl JsFunction { } impl JsFunction { - pub fn call<'a, 'b, C: Context<'a>, T, A, AS>(self, cx: &mut C, this: Handle<'b, T>, args: AS) -> JsResult<'a, JsValue> - where T: Value, - A: Value + 'b, - AS: IntoIterator> + pub fn call<'a, 'b, C: Context<'a>, T, A, AS>( + self, + cx: &mut C, + this: Handle<'b, T>, + args: AS, + ) -> JsResult<'a, JsValue> + where + T: Value, + A: Value + 'b, + AS: IntoIterator>, { - let mut args = args.into_iter().collect::>(); + let mut args = args.into_iter().collect::>(); let (argc, argv) = unsafe { prepare_call(cx, &mut args) }?; let env = cx.env().to_raw(); - build(cx.env(), |out| { - unsafe { - neon_runtime::fun::call(out, env, self.to_raw(), this.to_raw(), argc, argv) - } + build(cx.env(), |out| unsafe { + neon_runtime::fun::call(out, env, self.to_raw(), this.to_raw(), argc, argv) }) } pub fn construct<'a, 'b, C: Context<'a>, A, AS>(self, cx: &mut C, args: AS) -> JsResult<'a, CL> - where A: Value + 'b, - AS: IntoIterator> + where + A: Value + 'b, + AS: IntoIterator>, { - let mut args = args.into_iter().collect::>(); + let mut args = args.into_iter().collect::>(); let (argc, argv) = unsafe { prepare_call(cx, &mut args) }?; let env = cx.env().to_raw(); - build(cx.env(), |out| { - unsafe { - neon_runtime::fun::construct(out, env, self.to_raw(), argc, argv) - } + build(cx.env(), |out| unsafe { + neon_runtime::fun::construct(out, env, self.to_raw(), argc, argv) }) } } -impl Value for JsFunction { } +impl Value for JsFunction {} impl Managed for JsFunction { - fn to_raw(self) -> raw::Local { self.raw } + fn to_raw(self) -> raw::Local { + self.raw + } fn from_raw(_: Env, h: raw::Local) -> Self { JsFunction { raw: h, - marker: PhantomData + marker: PhantomData, } } } impl ValueInternal for JsFunction { - fn name() -> String { "function".to_string() } + fn name() -> String { + "function".to_string() + } fn is_typeof(env: Env, other: Other) -> bool { unsafe { neon_runtime::tag::is_function(env.to_raw(), other.to_raw()) } diff --git a/src/types/utf8.rs b/src/types/utf8.rs index 4b1d0f8e3..b12b8cb9b 100644 --- a/src/types/utf8.rs +++ b/src/types/utf8.rs @@ -7,7 +7,7 @@ const SMALL_MAX: usize = std::i32::MAX as usize; /// signed integers. This type represents a UTF-8 string that contains no /// more than `i32::MAX` bytes of code units. pub struct SmallUtf8<'a> { - contents: Cow<'a, str> + contents: Cow<'a, str>, } impl<'a> SmallUtf8<'a> { @@ -19,13 +19,13 @@ impl<'a> SmallUtf8<'a> { /// A UTF-8 string that can be lowered to a representation usable for V8 /// APIs. pub struct Utf8<'a> { - contents: Cow<'a, str> + contents: Cow<'a, str>, } impl<'a> From<&'a str> for Utf8<'a> { fn from(s: &'a str) -> Self { Utf8 { - contents: Cow::from(s) + contents: Cow::from(s), } } } @@ -38,7 +38,7 @@ impl<'a> Utf8<'a> { pub fn into_small(self) -> Option> { if self.size() < SMALL_MAX { Some(SmallUtf8 { - contents: self.contents + contents: self.contents, }) } else { None @@ -62,8 +62,6 @@ impl<'a> Utf8<'a> { s.push_str("..."); } - SmallUtf8 { - contents, - } + SmallUtf8 { contents } } } diff --git a/test/dynamic/native/src/js/classes.rs b/test/dynamic/native/src/js/classes.rs index 54cc839fa..5d4e8f66e 100644 --- a/test/dynamic/native/src/js/classes.rs +++ b/test/dynamic/native/src/js/classes.rs @@ -1,10 +1,10 @@ use neon::prelude::*; pub struct User { - id: i32, - first_name: String, - last_name: String, - email: String, + id: i32, + first_name: String, + last_name: String, + email: String, } type Unit = (); diff --git a/test/dynamic/native/src/js/eventhandler.rs b/test/dynamic/native/src/js/eventhandler.rs index 53835bdc9..df612a6ae 100644 --- a/test/dynamic/native/src/js/eventhandler.rs +++ b/test/dynamic/native/src/js/eventhandler.rs @@ -1,11 +1,11 @@ use neon::prelude::*; -use std::thread; use std::sync::mpsc; +use std::thread; use std::time::Duration; pub struct Emitter { - cb: Option, + cb: Option, } declare_types! { @@ -78,7 +78,7 @@ declare_types! { } pub struct TestEmitter { - cb: Option, + cb: Option, } declare_types! { @@ -116,7 +116,7 @@ declare_types! { let cmd = match result { Ok(v) => { if let Ok(number) = v.downcast::() { - if number.value() == 12f64 { + if (number.value() - 12f64).abs() < f64::EPSILON { "done".into() } else { "wrong number".into() diff --git a/test/dynamic/native/src/js/functions.rs b/test/dynamic/native/src/js/functions.rs index 68b1bb117..cafc80715 100644 --- a/test/dynamic/native/src/js/functions.rs +++ b/test/dynamic/native/src/js/functions.rs @@ -1,5 +1,5 @@ -use neon::prelude::*; use neon::object::This; +use neon::prelude::*; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult { @@ -15,16 +15,24 @@ pub fn call_js_function(mut cx: FunctionContext) -> JsResult { let f = cx.argument::(0)?; let args: Vec> = vec![cx.number(16.0)]; let null = cx.null(); - f.call(&mut cx, null, args)?.downcast::().or_throw(&mut cx) + f.call(&mut cx, null, args)? + .downcast::() + .or_throw(&mut cx) } pub fn construct_js_function(mut cx: FunctionContext) -> JsResult { let f = cx.argument::(0)?; let zero = cx.number(0.0); let o = f.construct(&mut cx, vec![zero])?; - let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::().or_throw(&mut cx)?; + let get_utc_full_year_method = o + .get(&mut cx, "getUTCFullYear")? + .downcast::() + .or_throw(&mut cx)?; let args: Vec> = vec![]; - get_utc_full_year_method.call(&mut cx, o.upcast::(), args)?.downcast::().or_throw(&mut cx) + get_utc_full_year_method + .call(&mut cx, o.upcast::(), args)? + .downcast::() + .or_throw(&mut cx) } trait CheckArgument<'a> { @@ -48,7 +56,8 @@ pub fn panic(_: FunctionContext) -> JsResult { } pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult { - cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err(); + cx.throw_range_error::<_, ()>("entering throw state with a RangeError") + .unwrap_err(); panic!("this should override the RangeError") } @@ -102,37 +111,40 @@ pub fn compute_scoped(mut cx: FunctionContext) -> JsResult { } pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult { - let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast()); + let v = cx + .argument_opt(0) + .unwrap_or_else(|| cx.undefined().upcast()); cx.try_catch(|cx| cx.throw(v)) .map(|_: ()| Ok(cx.string("unreachable").upcast())) - .unwrap_or_else(|err| Ok(err)) + .unwrap_or_else(Ok) } pub fn call_and_catch(mut cx: FunctionContext) -> JsResult { let f: Handle = cx.argument(0)?; - Ok(cx.try_catch(|cx| { - let global = cx.global(); - let args: Vec> = vec![]; - f.call(cx, global, args) - }).unwrap_or_else(|err| err)) + Ok(cx + .try_catch(|cx| { + let global = cx.global(); + let args: Vec> = vec![]; + f.call(cx, global, args) + }) + .unwrap_or_else(|err| err)) } pub fn get_number_or_default(mut cx: FunctionContext) -> JsResult { - let n = cx.try_catch(|cx| Ok(cx.argument::(0)?.value())) + let n = cx + .try_catch(|cx| Ok(cx.argument::(0)?.value())) .unwrap_or(0.0); Ok(cx.number(n)) } pub fn panic_and_catch(mut cx: FunctionContext) -> JsResult { - Ok(cx.try_catch(|_| { panic!("oh no") }) - .unwrap_or_else(|err| err)) + Ok(cx.try_catch(|_| panic!("oh no")).unwrap_or_else(|err| err)) } pub fn unexpected_throw_and_catch(mut cx: FunctionContext) -> JsResult { - Ok(cx.try_catch(|_| { Err(Throw) }) - .unwrap_or_else(|err| err)) + Ok(cx.try_catch(|_| Err(Throw)).unwrap_or_else(|err| err)) } pub fn downcast_error(mut cx: FunctionContext) -> JsResult { diff --git a/test/dynamic/native/src/js/objects.rs b/test/dynamic/native/src/js/objects.rs index cdf6cfbfd..2704bbbc5 100644 --- a/test/dynamic/native/src/js/objects.rs +++ b/test/dynamic/native/src/js/objects.rs @@ -51,13 +51,13 @@ pub fn read_array_buffer_with_lock(mut cx: FunctionContext) -> JsResult JsResult { let b: Handle = cx.argument(0)?; let i = cx.argument::(1)?.value() as u32 as usize; - let x = cx.borrow(&b, |data| { data.as_slice::()[i] }); + let x = cx.borrow(&b, |data| data.as_slice::()[i]); Ok(cx.number(x)) } pub fn sum_array_buffer_with_borrow(mut cx: FunctionContext) -> JsResult { let b: Handle = cx.argument(0)?; - let x: u8 = cx.borrow(&b, |data| { data.as_slice::().iter().sum() }); + let x: u8 = cx.borrow(&b, |data| data.as_slice::().iter().sum()); Ok(cx.number(x)) } @@ -78,13 +78,17 @@ pub fn write_array_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult = cx.argument(0)?; let i = cx.argument::(1)?.value() as u32 as usize; let x = cx.argument::(2)?.value() as u32; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::()[i] = x; }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::()[i] = x; + }); Ok(cx.undefined()) } pub fn increment_array_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult { let mut b: Handle = cx.argument(0)?; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); + }); Ok(cx.undefined()) } @@ -108,13 +112,13 @@ pub fn read_buffer_with_lock(mut cx: FunctionContext) -> JsResult { pub fn read_buffer_with_borrow(mut cx: FunctionContext) -> JsResult { let b: Handle = cx.argument(0)?; let i = cx.argument::(1)?.value() as u32 as usize; - let x = cx.borrow(&b, |data| { data.as_slice::()[i] }); + let x = cx.borrow(&b, |data| data.as_slice::()[i]); Ok(cx.number(x)) } pub fn sum_buffer_with_borrow(mut cx: FunctionContext) -> JsResult { let b: Handle = cx.argument(0)?; - let x: u8 = cx.borrow(&b, |data| { data.as_slice::().iter().sum() }); + let x: u8 = cx.borrow(&b, |data| data.as_slice::().iter().sum()); Ok(cx.number(x)) } @@ -135,12 +139,16 @@ pub fn write_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult = cx.argument(0)?; let i = cx.argument::(1)?.value() as u32 as usize; let x = cx.argument::(2)?.value() as u32; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::()[i] = x; }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::()[i] = x; + }); Ok(cx.undefined()) } pub fn increment_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult { let mut b: Handle = cx.argument(0)?; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); + }); Ok(cx.undefined()) } diff --git a/test/dynamic/native/src/js/tasks.rs b/test/dynamic/native/src/js/tasks.rs index 40e6b5d87..fee3bb5a5 100644 --- a/test/dynamic/native/src/js/tasks.rs +++ b/test/dynamic/native/src/js/tasks.rs @@ -11,7 +11,11 @@ impl Task for SuccessTask { Ok(17) } - fn complete(self, mut cx: TaskContext, result: Result) -> JsResult { + fn complete( + self, + mut cx: TaskContext, + result: Result, + ) -> JsResult { Ok(cx.number(result.unwrap())) } } @@ -30,10 +34,14 @@ impl Task for FailureTask { type JsEvent = JsNumber; fn perform(&self) -> Result { - Err(format!("I am a failing task")) + Err(String::from("I am a failing task")) } - fn complete(self, mut cx: TaskContext, result: Result) -> JsResult { + fn complete( + self, + mut cx: TaskContext, + result: Result, + ) -> JsResult { cx.throw_error(&result.unwrap_err()) } } diff --git a/test/dynamic/native/src/lib.rs b/test/dynamic/native/src/lib.rs index f12702c7e..eac6fda18 100644 --- a/test/dynamic/native/src/lib.rs +++ b/test/dynamic/native/src/lib.rs @@ -1,24 +1,24 @@ use neon::prelude::*; mod js { - pub mod strings; - pub mod numbers; pub mod arrays; - pub mod objects; - pub mod functions; pub mod classes; - pub mod tasks; pub mod eventhandler; + pub mod functions; + pub mod numbers; + pub mod objects; + pub mod strings; + pub mod tasks; } -use js::strings::return_js_string; -use js::numbers::*; use js::arrays::*; -use js::objects::*; -use js::functions::*; use js::classes::*; -use js::tasks::*; use js::eventhandler::*; +use js::functions::*; +use js::numbers::*; +use js::objects::*; +use js::strings::return_js_string; +use js::tasks::*; #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { @@ -28,11 +28,23 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("return_large_js_number", return_large_js_number)?; cx.export_function("return_negative_js_number", return_negative_js_number)?; cx.export_function("return_float_js_number", return_float_js_number)?; - cx.export_function("return_negative_float_js_number", return_negative_float_js_number)?; + cx.export_function( + "return_negative_float_js_number", + return_negative_float_js_number, + )?; cx.export_function("accept_and_return_js_number", accept_and_return_js_number)?; - cx.export_function("accept_and_return_large_js_number", accept_and_return_large_js_number)?; - cx.export_function("accept_and_return_float_js_number", accept_and_return_float_js_number)?; - cx.export_function("accept_and_return_negative_js_number", accept_and_return_negative_js_number)?; + cx.export_function( + "accept_and_return_large_js_number", + accept_and_return_large_js_number, + )?; + cx.export_function( + "accept_and_return_float_js_number", + accept_and_return_float_js_number, + )?; + cx.export_function( + "accept_and_return_negative_js_number", + accept_and_return_negative_js_number, + )?; cx.export_function("return_js_array", return_js_array)?; cx.export_function("return_js_array_with_number", return_js_array_with_number)?; @@ -42,21 +54,36 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("return_js_object", return_js_object)?; cx.export_function("return_js_object_with_number", return_js_object_with_number)?; cx.export_function("return_js_object_with_string", return_js_object_with_string)?; - cx.export_function("return_js_object_with_mixed_content", return_js_object_with_mixed_content)?; + cx.export_function( + "return_js_object_with_mixed_content", + return_js_object_with_mixed_content, + )?; cx.export_function("return_array_buffer", return_array_buffer)?; cx.export_function("read_array_buffer_with_lock", read_array_buffer_with_lock)?; - cx.export_function("read_array_buffer_with_borrow", read_array_buffer_with_borrow)?; + cx.export_function( + "read_array_buffer_with_borrow", + read_array_buffer_with_borrow, + )?; cx.export_function("sum_array_buffer_with_borrow", sum_array_buffer_with_borrow)?; cx.export_function("write_array_buffer_with_lock", write_array_buffer_with_lock)?; - cx.export_function("write_array_buffer_with_borrow_mut", write_array_buffer_with_borrow_mut)?; - cx.export_function("increment_array_buffer_with_borrow_mut", increment_array_buffer_with_borrow_mut)?; + cx.export_function( + "write_array_buffer_with_borrow_mut", + write_array_buffer_with_borrow_mut, + )?; + cx.export_function( + "increment_array_buffer_with_borrow_mut", + increment_array_buffer_with_borrow_mut, + )?; cx.export_function("return_buffer", return_buffer)?; cx.export_function("read_buffer_with_lock", read_buffer_with_lock)?; cx.export_function("read_buffer_with_borrow", read_buffer_with_borrow)?; cx.export_function("sum_buffer_with_borrow", sum_buffer_with_borrow)?; cx.export_function("write_buffer_with_lock", write_buffer_with_lock)?; cx.export_function("write_buffer_with_borrow_mut", write_buffer_with_borrow_mut)?; - cx.export_function("increment_buffer_with_borrow_mut", increment_buffer_with_borrow_mut)?; + cx.export_function( + "increment_buffer_with_borrow_mut", + increment_buffer_with_borrow_mut, + )?; cx.export_function("return_js_function", return_js_function)?; cx.export_function("call_js_function", call_js_function)?; diff --git a/test/napi/src/js/boxed.rs b/test/napi/src/js/boxed.rs index 6a5630936..1c24e6c45 100644 --- a/test/napi/src/js/boxed.rs +++ b/test/napi/src/js/boxed.rs @@ -10,7 +10,9 @@ impl Finalize for Person {} impl Person { fn new(name: impl ToString) -> Self { - Self { name: name.to_string() } + Self { + name: name.to_string(), + } } fn greet(&self) -> String { diff --git a/test/napi/src/js/date.rs b/test/napi/src/js/date.rs index a882a6d39..0ba9bf224 100644 --- a/test/napi/src/js/date.rs +++ b/test/napi/src/js/date.rs @@ -1,4 +1,4 @@ -use std::{f64::NAN}; +use std::f64::NAN; use neon::prelude::*; use neon::types::JsDate; @@ -32,8 +32,14 @@ pub fn try_new_date(mut cx: FunctionContext) -> JsResult { pub fn try_new_lossy_date(mut cx: FunctionContext) -> JsResult { let date_overflow = JsDate::new(&mut cx, JsDate::MAX_VALUE + 1.0); let date_underflow = JsDate::new(&mut cx, JsDate::MIN_VALUE - 1.0); - assert_eq!(date_overflow.unwrap_err().kind(), neon::types::DateErrorKind::Overflow); - assert_eq!(date_underflow.unwrap_err().kind(), neon::types::DateErrorKind::Underflow); + assert_eq!( + date_overflow.unwrap_err().kind(), + neon::types::DateErrorKind::Overflow + ); + assert_eq!( + date_underflow.unwrap_err().kind(), + neon::types::DateErrorKind::Underflow + ); Ok(cx.undefined()) } diff --git a/test/napi/src/js/functions.rs b/test/napi/src/js/functions.rs index 6de26f522..5a8bd819c 100644 --- a/test/napi/src/js/functions.rs +++ b/test/napi/src/js/functions.rs @@ -1,5 +1,5 @@ -use neon::prelude::*; use neon::object::This; +use neon::prelude::*; fn add1(mut cx: FunctionContext) -> JsResult { let x = cx.argument::(0)?.value(&mut cx); @@ -14,16 +14,24 @@ pub fn call_js_function(mut cx: FunctionContext) -> JsResult { let f = cx.argument::(0)?; let args: Vec> = vec![cx.number(16.0)]; let null = cx.null(); - f.call(&mut cx, null, args)?.downcast::(&mut cx).or_throw(&mut cx) + f.call(&mut cx, null, args)? + .downcast::(&mut cx) + .or_throw(&mut cx) } pub fn construct_js_function(mut cx: FunctionContext) -> JsResult { let f = cx.argument::(0)?; let zero = cx.number(0.0); let o = f.construct(&mut cx, vec![zero])?; - let get_utc_full_year_method = o.get(&mut cx, "getUTCFullYear")?.downcast::(&mut cx).or_throw(&mut cx)?; + let get_utc_full_year_method = o + .get(&mut cx, "getUTCFullYear")? + .downcast::(&mut cx) + .or_throw(&mut cx)?; let args: Vec> = vec![]; - get_utc_full_year_method.call(&mut cx, o.upcast::(), args)?.downcast::(&mut cx).or_throw(&mut cx) + get_utc_full_year_method + .call(&mut cx, o.upcast::(), args)? + .downcast::(&mut cx) + .or_throw(&mut cx) } trait CheckArgument<'a> { @@ -47,7 +55,8 @@ pub fn panic(_: FunctionContext) -> JsResult { } pub fn panic_after_throw(mut cx: FunctionContext) -> JsResult { - cx.throw_range_error::<_, ()>("entering throw state with a RangeError").unwrap_err(); + cx.throw_range_error::<_, ()>("entering throw state with a RangeError") + .unwrap_err(); panic!("this should override the RangeError") } @@ -103,7 +112,9 @@ pub fn compute_scoped(mut cx: FunctionContext) -> JsResult { } pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult { - let v = cx.argument_opt(0).unwrap_or_else(|| cx.undefined().upcast()); + let v = cx + .argument_opt(0) + .unwrap_or_else(|| cx.undefined().upcast()); cx.try_catch(|cx| cx.throw(v)) .map(|_: ()| Ok(cx.string("unreachable").upcast())) @@ -112,15 +123,18 @@ pub fn throw_and_catch(mut cx: FunctionContext) -> JsResult { pub fn call_and_catch(mut cx: FunctionContext) -> JsResult { let f: Handle = cx.argument(0)?; - Ok(cx.try_catch(|cx| { - let global = cx.global(); - let args: Vec> = vec![]; - f.call(cx, global, args) - }).unwrap_or_else(|err| err)) + Ok(cx + .try_catch(|cx| { + let global = cx.global(); + let args: Vec> = vec![]; + f.call(cx, global, args) + }) + .unwrap_or_else(|err| err)) } pub fn get_number_or_default(mut cx: FunctionContext) -> JsResult { - let n = cx.try_catch(|cx| Ok(cx.argument::(0)?.value(cx))) + let n = cx + .try_catch(|cx| Ok(cx.argument::(0)?.value(cx))) .unwrap_or(0.0); Ok(cx.number(n)) diff --git a/test/napi/src/js/objects.rs b/test/napi/src/js/objects.rs index ae83d9895..dbb4db792 100644 --- a/test/napi/src/js/objects.rs +++ b/test/napi/src/js/objects.rs @@ -51,13 +51,13 @@ pub fn read_array_buffer_with_lock(mut cx: FunctionContext) -> JsResult JsResult { let b: Handle = cx.argument(0)?; let i = cx.argument::(1)?.value(&mut cx) as u32 as usize; - let x = cx.borrow(&b, |data| { data.as_slice::()[i] }); + let x = cx.borrow(&b, |data| data.as_slice::()[i]); Ok(cx.number(x)) } pub fn sum_array_buffer_with_borrow(mut cx: FunctionContext) -> JsResult { let b: Handle = cx.argument(0)?; - let x: u8 = cx.borrow(&b, |data| { data.as_slice::().iter().sum() }); + let x: u8 = cx.borrow(&b, |data| data.as_slice::().iter().sum()); Ok(cx.number(x)) } @@ -78,13 +78,17 @@ pub fn write_array_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult = cx.argument(0)?; let i = cx.argument::(1)?.value(&mut cx) as u32 as usize; let x = cx.argument::(2)?.value(&mut cx) as u32; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::()[i] = x; }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::()[i] = x; + }); Ok(cx.undefined()) } pub fn increment_array_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult { let mut b: Handle = cx.argument(0)?; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); + }); Ok(cx.undefined()) } @@ -127,13 +131,13 @@ pub fn read_buffer_with_lock(mut cx: FunctionContext) -> JsResult { pub fn read_buffer_with_borrow(mut cx: FunctionContext) -> JsResult { let b: Handle = cx.argument(0)?; let i = cx.argument::(1)?.value(&mut cx) as u32 as usize; - let x = cx.borrow(&b, |data| { data.as_slice::()[i] }); + let x = cx.borrow(&b, |data| data.as_slice::()[i]); Ok(cx.number(x)) } pub fn sum_buffer_with_borrow(mut cx: FunctionContext) -> JsResult { let b: Handle = cx.argument(0)?; - let x: u8 = cx.borrow(&b, |data| { data.as_slice::().iter().sum() }); + let x: u8 = cx.borrow(&b, |data| data.as_slice::().iter().sum()); Ok(cx.number(x)) } @@ -154,12 +158,16 @@ pub fn write_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult = cx.argument(0)?; let i = cx.argument::(1)?.value(&mut cx) as u32 as usize; let x = cx.argument::(2)?.value(&mut cx) as u32; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::()[i] = x; }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::()[i] = x; + }); Ok(cx.undefined()) } pub fn increment_buffer_with_borrow_mut(mut cx: FunctionContext) -> JsResult { let mut b: Handle = cx.argument(0)?; - cx.borrow_mut(&mut b, |data| { data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); }); + cx.borrow_mut(&mut b, |data| { + data.as_mut_slice::().iter_mut().for_each(|x| *x += 1); + }); Ok(cx.undefined()) } diff --git a/test/napi/src/js/threads.rs b/test/napi/src/js/threads.rs index b0926b473..9bfea27a8 100644 --- a/test/napi/src/js/threads.rs +++ b/test/napi/src/js/threads.rs @@ -15,15 +15,17 @@ pub fn thread_callback(mut cx: FunctionContext) -> JsResult { let callback = cx.argument::(0)?.root(&mut cx); let queue = cx.queue(); - std::thread::spawn(move || queue.send(move |mut cx| { - let callback = callback.into_inner(&mut cx); - let this = cx.undefined(); - let args = Vec::>::new(); + std::thread::spawn(move || { + queue.send(move |mut cx| { + let callback = callback.into_inner(&mut cx); + let this = cx.undefined(); + let args = Vec::>::new(); - callback.call(&mut cx, this, args)?; + callback.call(&mut cx, this, args)?; - Ok(()) - })); + Ok(()) + }) + }); Ok(cx.undefined()) } @@ -37,15 +39,17 @@ pub fn multi_threaded_callback(mut cx: FunctionContext) -> JsResult let callback = callback.clone(&mut cx); let queue = Arc::clone(&queue); - std::thread::spawn(move || queue.send(move |mut cx| { - let callback = callback.into_inner(&mut cx); - let this = cx.undefined(); - let args = vec![cx.number(i as f64)]; + std::thread::spawn(move || { + queue.send(move |mut cx| { + let callback = callback.into_inner(&mut cx); + let this = cx.undefined(); + let args = vec![cx.number(i as f64)]; - callback.call(&mut cx, this, args)?; + callback.call(&mut cx, this, args)?; - Ok(()) - })); + Ok(()) + }) + }); } callback.drop(&mut cx); @@ -68,15 +72,17 @@ impl AsyncGreeter { let callback = self.callback.clone(&mut cx); let queue = Arc::clone(&self.queue); - std::thread::spawn(move || queue.send(|mut cx| { - let callback = callback.into_inner(&mut cx); - let this = cx.undefined(); - let args = vec![cx.string(greeting)]; + std::thread::spawn(move || { + queue.send(|mut cx| { + let callback = callback.into_inner(&mut cx); + let this = cx.undefined(); + let args = vec![cx.string(greeting)]; - callback.call(&mut cx, this, args)?; + callback.call(&mut cx, this, args)?; - Ok(()) - })); + Ok(()) + }) + }); Ok(cx.undefined()) } @@ -84,7 +90,9 @@ impl AsyncGreeter { impl Finalize for AsyncGreeter { fn finalize<'a, C: Context<'a>>(self, cx: &mut C) { - let Self { callback, shutdown, .. } = self; + let Self { + callback, shutdown, .. + } = self; if let Some(shutdown) = shutdown { let shutdown = shutdown.into_inner(cx); diff --git a/test/napi/src/lib.rs b/test/napi/src/lib.rs index 88cedc4ac..8f15aba59 100644 --- a/test/napi/src/lib.rs +++ b/test/napi/src/lib.rs @@ -4,27 +4,27 @@ mod js { pub mod arrays; pub mod boxed; pub mod coercions; + pub mod date; pub mod errors; pub mod functions; pub mod numbers; pub mod objects; - pub mod types; pub mod strings; pub mod threads; - pub mod date; + pub mod types; } use js::arrays::*; use js::boxed::*; use js::coercions::*; +use js::date::*; use js::errors::*; use js::functions::*; use js::numbers::*; use js::objects::*; -use js::types::*; use js::strings::*; use js::threads::*; -use js::date::*; +use js::types::*; #[neon::main] fn main(mut cx: ModuleContext) -> NeonResult<()> { @@ -70,20 +70,34 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> { rust_created.set(&mut cx, "whatever", whatever)?; } - assert!(({ - let v: Handle = rust_created.get(&mut cx, "a")?.downcast_or_throw(&mut cx)?; - v.value(&mut cx) - } - 1.0f64).abs() < f64::EPSILON); - assert!(({ - let v: Handle = rust_created.get(&mut cx, 0)?.downcast_or_throw(&mut cx)?; - v.value(&mut cx) - } - 1.0f64).abs() < f64::EPSILON); - assert_eq!({ - let v: Handle = rust_created.get(&mut cx, "whatever")?.downcast_or_throw(&mut cx)?; - v.value(&mut cx) - }, true); - - let property_names = rust_created.get_own_property_names(&mut cx)? + assert!( + ({ + let v: Handle = rust_created.get(&mut cx, "a")?.downcast_or_throw(&mut cx)?; + v.value(&mut cx) + } - 1.0f64) + .abs() + < f64::EPSILON + ); + assert!( + ({ + let v: Handle = rust_created.get(&mut cx, 0)?.downcast_or_throw(&mut cx)?; + v.value(&mut cx) + } - 1.0f64) + .abs() + < f64::EPSILON + ); + assert_eq!( + { + let v: Handle = rust_created + .get(&mut cx, "whatever")? + .downcast_or_throw(&mut cx)?; + v.value(&mut cx) + }, + true + ); + + let property_names = rust_created + .get_own_property_names(&mut cx)? .to_vec(&mut cx)? .into_iter() .map(|value| { @@ -108,11 +122,23 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("return_large_js_number", return_large_js_number)?; cx.export_function("return_negative_js_number", return_negative_js_number)?; cx.export_function("return_float_js_number", return_float_js_number)?; - cx.export_function("return_negative_float_js_number", return_negative_float_js_number)?; + cx.export_function( + "return_negative_float_js_number", + return_negative_float_js_number, + )?; cx.export_function("accept_and_return_js_number", accept_and_return_js_number)?; - cx.export_function("accept_and_return_large_js_number", accept_and_return_large_js_number)?; - cx.export_function("accept_and_return_float_js_number", accept_and_return_float_js_number)?; - cx.export_function("accept_and_return_negative_js_number", accept_and_return_negative_js_number)?; + cx.export_function( + "accept_and_return_large_js_number", + accept_and_return_large_js_number, + )?; + cx.export_function( + "accept_and_return_float_js_number", + accept_and_return_float_js_number, + )?; + cx.export_function( + "accept_and_return_negative_js_number", + accept_and_return_negative_js_number, + )?; cx.export_function("return_js_function", return_js_function)?; cx.export_function("call_js_function", call_js_function)?; @@ -137,15 +163,27 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("return_js_object", return_js_object)?; cx.export_function("return_js_object_with_number", return_js_object_with_number)?; cx.export_function("return_js_object_with_string", return_js_object_with_string)?; - cx.export_function("return_js_object_with_mixed_content", return_js_object_with_mixed_content)?; + cx.export_function( + "return_js_object_with_mixed_content", + return_js_object_with_mixed_content, + )?; cx.export_function("return_array_buffer", return_array_buffer)?; cx.export_function("read_array_buffer_with_lock", read_array_buffer_with_lock)?; - cx.export_function("read_array_buffer_with_borrow", read_array_buffer_with_borrow)?; + cx.export_function( + "read_array_buffer_with_borrow", + read_array_buffer_with_borrow, + )?; cx.export_function("sum_array_buffer_with_borrow", sum_array_buffer_with_borrow)?; cx.export_function("write_array_buffer_with_lock", write_array_buffer_with_lock)?; - cx.export_function("write_array_buffer_with_borrow_mut", write_array_buffer_with_borrow_mut)?; - cx.export_function("increment_array_buffer_with_borrow_mut", increment_array_buffer_with_borrow_mut)?; + cx.export_function( + "write_array_buffer_with_borrow_mut", + write_array_buffer_with_borrow_mut, + )?; + cx.export_function( + "increment_array_buffer_with_borrow_mut", + increment_array_buffer_with_borrow_mut, + )?; cx.export_function("return_uninitialized_buffer", return_uninitialized_buffer)?; cx.export_function("return_buffer", return_buffer)?; cx.export_function("return_external_buffer", return_external_buffer)?; @@ -155,7 +193,10 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> { cx.export_function("sum_buffer_with_borrow", sum_buffer_with_borrow)?; cx.export_function("write_buffer_with_lock", write_buffer_with_lock)?; cx.export_function("write_buffer_with_borrow_mut", write_buffer_with_borrow_mut)?; - cx.export_function("increment_buffer_with_borrow_mut", increment_buffer_with_borrow_mut)?; + cx.export_function( + "increment_buffer_with_borrow_mut", + increment_buffer_with_borrow_mut, + )?; cx.export_function("create_date", create_date)?; cx.export_function("get_date_value", get_date_value)?; diff --git a/test/static/tests/run_all.rs b/test/static/tests/run_all.rs index 0fb8d2e53..377cf7bd4 100644 --- a/test/static/tests/run_all.rs +++ b/test/static/tests/run_all.rs @@ -3,7 +3,10 @@ extern crate trybuild; #[test] fn run_all() { // Pass the `neon_profile` cfg flag down into trybuild's nested calls to cargo. - std::env::set_var("RUSTFLAGS", &format!("--cfg neon_profile={:?}", neon::meta::BUILD_PROFILE)); + std::env::set_var( + "RUSTFLAGS", + &format!("--cfg neon_profile={:?}", neon::meta::BUILD_PROFILE), + ); let t = trybuild::TestCases::new(); t.compile_fail("tests/compile-fail/*.rs");