From d4e217e5c4e3c470b5d1178d8ccdbb9de470b5d9 Mon Sep 17 00:00:00 2001 From: Ian Kettlewell Date: Wed, 16 Oct 2024 18:39:32 -0400 Subject: [PATCH] wasm-bindgen support Add an optional feature that allows wasm-bindgen projects to query hardwareConcurrency --- Cargo.toml | 9 +++++++++ src/lib.rs | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 6c63fbf..0e3b768 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,3 +16,12 @@ libc = "0.2.26" [target.'cfg(target_os = "hermit")'.dependencies] hermit-abi = "0.3.0" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +web-sys = { version = "0.3.0", features = [ + "WorkerNavigator", + "DedicatedWorkerGlobalScope", +], optional = true } + +[features] +wasm-bindgen-support = ["web-sys"] diff --git a/src/lib.rs b/src/lib.rs index fa1267c..9ad2bac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -433,6 +433,22 @@ fn get_num_cpus() -> usize { unsafe { hermit_abi::get_processor_count() } } +#[cfg(feature = "wasm-bindgen-support")] +extern crate web_sys; + +#[cfg(feature = "wasm-bindgen-support")] +fn get_num_cpus() -> usize { + use web_sys::{wasm_bindgen::JsCast, DedicatedWorkerGlobalScope}; + + let global = web_sys::js_sys::global(); + + // DedicatedWorkerGlobalScope is not always the correct type + // but the underlying global will always have access to `navigator` + // either way and this was the simplest way to work with `web_sys`. + let global = global.unchecked_into::(); + global.navigator().hardware_concurrency() as usize +} + #[cfg(not(any( target_os = "nacl", target_os = "macos", @@ -449,6 +465,7 @@ fn get_num_cpus() -> usize { target_os = "netbsd", target_os = "haiku", target_os = "hermit", + feature = "wasm-bindgen-support", windows, )))] fn get_num_cpus() -> usize {