### Use Rayon Parallel Iterators in Rust Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Utilize Rayon iterators like par_iter() for parallel computation. This example sums elements of an i32 slice using all available threads. ```rust #[wasm_bindgen] pub fn sum(numbers: &[i32]) -> i32 { numbers.par_iter().sum() } ``` -------------------------------- ### Initialize and Use Parallel Functions in JavaScript Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Initializes the WebAssembly module and the Rayon thread pool, then calls exported parallel functions. Requires `await init()` and `await initThreadPool()` before use. ```javascript import init, { initThreadPool, sum, square_all, generate_image } from './pkg/my_lib.js'; await init(); await initThreadPool(navigator.hardwareConcurrency); console.log(sum(new Int32Array([1, 2, 3, 4, 5]))); // => 15 const squared = square_all(new Float64Array([1, 2, 3, 4])); console.log(Array.from(squared)); // => [1, 4, 9, 16] const pixels = generate_image(512, 512); // runs on all threads const imgData = new ImageData(new Uint8ClampedArray(pixels), 512, 512); document.querySelector('canvas').getContext('2d').putImageData(imgData, 0, 0); ``` -------------------------------- ### Initialize Rayon Thread Pool in JavaScript Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Call `init` and then `initThreadPool` from JavaScript before executing any parallel Rust code. Initialize with `navigator.hardwareConcurrency` to use all logical CPU cores. ```javascript import init, { initThreadPool, parallel_sum } from './pkg/my_lib.js'; await init(); // Initialize with all logical CPU cores await initThreadPool(navigator.hardwareConcurrency); // Now Rayon iterators run across all worker threads const numbers = new Int32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); const result = parallel_sum(numbers); console.log(result); // => 55 ``` -------------------------------- ### Worker initialization and entry point invocation in JS Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt JavaScript code demonstrating how the JS side invokes `wbg_rayon_start_worker` after initializing the Wasm module. It waits for an initialization message, shares the module and memory, posts a ready message, and then calls the Rust function to enter the Rayon event loop. ```javascript if (name === "wasm_bindgen_worker") { waitForMsgType(self, 'wasm_bindgen_worker_init').then(async data => { initSync(data.init); // Share module + memory postMessage({ type: 'wasm_bindgen_worker_ready' }); wbg_rayon_start_worker(data.receiver); // Enter Rayon event loop }); } ``` -------------------------------- ### HTML Structure for 'no-bundler' Usage Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Include the necessary COOP/COEP headers on your server. The JavaScript code initializes the thread pool and calls the parallel function, with the worker script being blob-fetched internally. ```html ``` -------------------------------- ### Build with wasm-pack for Web Target Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Standard command to build your Wasm module using `wasm-pack` with the `--target web` flag after configuring your toolchain and Cargo. ```sh wasm-pack build --target web [...normal wasm-pack params...] ``` -------------------------------- ### Worker-side thread entry point (`wbg_rayon_start_worker`) Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Internal function for worker threads to initialize the Wasm module and enter Rayon's work-stealing loop. It blocks on a channel receiver for a `ThreadBuilder` message from the main thread. This function is managed by JS helpers and should not be called directly. ```rust #[wasm_bindgen] pub fn wbg_rayon_start_worker(receiver: *const Receiver) { // Safe: pointer originates from PoolBuilder on the heap, // kept alive until all threads are running. let receiver = unsafe { &*receiver }; // Blocks until PoolBuilder::build() sends a ThreadBuilder, // then runs Rayon's internal work-stealing loop. receiver.recv().unwrap_throw().run() } ``` -------------------------------- ### Build Wasm Threads with Command-Line Flags Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md This command passes all necessary flags directly to `rustup` and `wasm-pack`, including enabling target features, linking arguments, specifying the nightly toolchain, and enabling `build-std`. ```sh RUSTFLAGS='-C target-feature=+atomics,+bulk-memory -Clink-arg=--shared-memory -Clink-arg=--max-memory=1073741824 -Clink-arg=--import-memory -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Clink-arg=--export=__tls_align -Clink-arg=--export=__tls_base' \ rustup run nightly-2025-11-15 \ wasm-pack build --target web [...] \ -- -Z build-std=panic_abort,std ``` -------------------------------- ### Rust toolchain and target configuration for threaded Wasm Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Configuration files for `rust-toolchain.toml` and `.cargo/config.toml` required for compiling Wasm with threads. This includes specifying a nightly toolchain, `rust-src` component, `wasm32-unknown-unknown` target, and enabling `atomics` and `bulk-memory` features via `rustflags` and `link-arg`. ```toml [toolchain] channel = "nightly-2025-11-15" components = ["rust-src"] targets = ["wasm32-unknown-unknown"] profile = "minimal" ``` ```toml [target.wasm32-unknown-unknown] rustflags = [ "-C", "target-feature=+atomics,+bulk-memory", "-C", "link-arg=--shared-memory", "-C", "link-arg=--max-memory=1073741824", "-C", "link-arg=--import-memory", "-C", "link-arg=--export=__wasm_init_tls", "-C", "link-arg=--export=__tls_size", "-C", "link-arg=--export=__tls_align", "-C", "link-arg=--export=__tls_base" ] [unstable] build-std = ["panic_abort", "std"] ``` -------------------------------- ### Configure Cargo for Wasm Threads Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md This `.cargo/config.toml` configuration enables Wasm atomics and bulk memory features, and links shared memory for Wasm threads. It also sets up `build-std` for the panic_abort and std libraries. ```toml [target.wasm32-unknown-unknown] rustflags = [ "-C", "target-feature=+atomics,+bulk-memory", "-C", "link-arg=--shared-memory", "-C", "link-arg=--max-memory=1073741824", "-C", "link-arg=--import-memory", "-C", "link-arg=--export=__wasm_init_tls", "-C", "link-arg=--export=__tls_size", "-C", "link-arg=--export=__tls_align", "-C", "link-arg=--export=__tls_base" ] [unstable] build-std = ["panic_abort", "std"] ``` -------------------------------- ### Initialize Thread Pool in JavaScript Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Invoke the async initThreadPool function right after instantiating your Wasm module to prepare the thread pool before calling library functions. Pass navigator.hardwareConcurrency to use all available cores. ```javascript import init, { initThreadPool /* ... */ } from './pkg/index.js'; // Regular wasm-bindgen initialization. await init(); // Thread pool initialization with the given number of threads // (pass `navigator.hardwareConcurrency` if you want to use all cores). await initThreadPool(navigator.hardwareConcurrency); // ...now you can invoke any exported functions as you normally would ``` -------------------------------- ### Enable 'no-bundler' Feature for wasm-bindgen-rayon Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Add this to your `Cargo.toml` to enable the `no-bundler` feature if you are not using a bundler and need direct browser usage. ```toml wasm-bindgen-rayon = { version = "1.2", features = ["no-bundler"] } ``` -------------------------------- ### Basic JavaScript Integration with Webpack 5 Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt A simple JavaScript entry point that initializes the Wasm module and thread pool, then calls an exported sum function. This works directly with the provided Webpack 5 configuration. ```javascript import init, { initThreadPool, sum } from './pkg/my_lib.js'; await init(); await initThreadPool(navigator.hardwareConcurrency); console.log(sum(new Int32Array([10, 20, 30]))); // => 60 ``` -------------------------------- ### init_thread_pool Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Initializes the Rayon thread pool from JavaScript. This is the single public entry point of the crate and must be called before invoking any parallel Rust functions. It spawns a specified number of Web Workers, shares the Wasm module and memory, and wires them into Rayon's global thread pool. ```APIDOC ## init_thread_pool ### Description Initializes the Rayon thread pool from JavaScript. This is the single public entry point of the crate and must be called before invoking any parallel Rust functions. It spawns a specified number of Web Workers, shares the Wasm module and memory, and wires them into Rayon's global thread pool. ### Method Signature `init_thread_pool(num_threads: usize)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (Rust re-export) ```rust // src/lib.rs use wasm_bindgen_rayon::init_thread_pool; #[wasm_bindgen(start)] pub async fn main() { // Initialize with a specific number of threads, e.g., 4 init_thread_pool(4).await; } ``` ### Request Example (JavaScript) ```js // index.js import init, { initThreadPool } from './pkg/my_lib.js'; await init(); // Initialize with all logical CPU cores await initThreadPool(navigator.hardwareConcurrency); ``` ### Response #### Success Response (200) None (asynchronous operation) #### Response Example None ``` -------------------------------- ### Add wasm-bindgen-rayon Dependencies Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Add wasm-bindgen, rayon, and wasm-bindgen-rayon as dependencies in your Cargo.toml file. ```toml [dependencies] wasm-bindgen = "0.2" rayon = "1.8" wasm-bindgen-rayon = "1.2" ``` -------------------------------- ### Configure Rust Toolchain for Wasm Threads Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Use this TOML configuration in `rust-toolchain.toml` to specify a nightly toolchain with Wasm targets and rust-src, which is necessary for `build-std`. ```toml [toolchain] channel = "nightly-2025-11-15" components = ["rust-src"] targets = ["wasm32-unknown-unknown"] ``` -------------------------------- ### Wasm-pack build command for threaded Wasm Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt The `wasm-pack build` command for producing threaded Wasm output with `--target web`. It shows how to configure `RUSTFLAGS` and use `rustup run` with a specific nightly toolchain when not using configuration files. ```sh # Build command — produces ./pkg/ with --target web output wasm-pack build --target web # Or, without config files, pass everything inline: RUSTFLAGS='-C target-feature=+atomics,+bulk-memory \ -Clink-arg=--shared-memory -Clink-arg=--max-memory=1073741824 \ -Clink-arg=--import-memory -Clink-arg=--export=__wasm_init_tls \ -Clink-arg=--export=__tls_size -Clink-arg=--export=__tls_align \ -Clink-arg=--export=__tls_base' \ rustup run nightly-2025-11-15 \ wasm-pack build --target web \ -- -Z build-std=panic_abort,std ``` -------------------------------- ### Initialize Rayon Thread Pool in Rust Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Re-export the `init_thread_pool` function from wasm-bindgen-rayon to expose `initThreadPool` in the JS glue. This function must be called before invoking any parallel Rust functions. ```rust use wasm_bindgen::prelude::*; // Re-export so wasm-bindgen generates initThreadPool in the JS glue. pub use wasm_bindgen_rayon::init_thread_pool; #[wasm_bindgen] pub fn parallel_sum(numbers: &[i32]) -> i32 { use rayon::prelude::*; numbers.par_iter().sum() } ``` -------------------------------- ### Enable 'no-bundler' Feature in Cargo.toml Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt To use wasm-bindgen-rayon without a JavaScript bundler, enable the `no-bundler` feature in your Cargo.toml file. This switches the internal worker helper to load the worker script dynamically. ```toml [dependencies] wasm-bindgen = "0.2" rayon = "1.8" wasm-bindgen-rayon = { version = "1.2", features = ["no-bundler"] } ``` -------------------------------- ### Webpack 5 Configuration for Wasm Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Configuration for Webpack 5 to handle Wasm modules and workers automatically. No special worker plugins are needed for Webpack versions 5.25.1 and above. ```javascript import CopyPlugin from 'copy-webpack-plugin'; import { dirname } from 'path'; import { fileURLToPath } from 'url'; const __dirname = dirname(fileURLToPath(import.meta.url)); export default { mode: 'production', entry: './index.js', output: { path: __dirname + '/dist', filename: 'index.js' }, plugins: [new CopyPlugin({ patterns: ['index.html'] })], module: { rules: [{ test: \".m?js$\", resolve: { fullySpecified: false } }] } // No special Worker plugin needed — Webpack 5 handles it automatically }; ``` -------------------------------- ### Feature detection for thread support and dynamic build loading Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt JavaScript code that uses `wasm-feature-detect` to check for `SharedArrayBuffer` support. It dynamically imports either a threaded or single-threaded Wasm build. Rayon's `into_par_iter()` automatically degrades to sequential iteration when compiled without the `atomics` target feature, ensuring the same Rust logic works in both builds. ```javascript import { threads } from 'wasm-feature-detect'; let wasmPkg; if (await threads()) { // Threaded build: compiled with +atomics,+bulk-memory wasmPkg = await import('./pkg-parallel/my_lib.js'); await wasmPkg.default(); await wasmPkg.initThreadPool(navigator.hardwareConcurrency); console.log('Running with', navigator.hardwareConcurrency, 'threads'); } else { // Fallback build: compiled normally, Rayon runs single-threaded wasmPkg = await import('./pkg/my_lib.js'); await wasmPkg.default(); console.log('Running single-threaded (no SharedArrayBuffer support)'); } // Same API regardless of threading mode const result = wasmPkg.parallel_sum(new Int32Array([1, 2, 3, 4, 5])); console.log(result); // => 15 ``` -------------------------------- ### Export Parallel Rayon Functions in Rust Source: https://context7.com/rreverser/wasm-bindgen-rayon/llms.txt Defines parallel iterator functions for use in WebAssembly. Ensure `target-feature=+atomics` is enabled during build. ```rust use rayon::prelude::*; use wasm_bindgen::prelude::*; pub use wasm_bindgen_rayon::init_thread_pool; /// Parallel sum of an Int32Array passed from JavaScript. #[wasm_bindgen] pub fn sum(numbers: &[i32]) -> i32 { numbers.par_iter().sum() } /// Parallel map — square every element, return a new Vec. #[wasm_bindgen] pub fn square_all(numbers: &[f64]) -> Vec { numbers.par_iter().map(|x| x * x).collect() } /// Parallel Mandelbrot row generation (CPU-intensive work distributed /// across all available hardware threads). #[wasm_bindgen] pub fn generate_image(width: u32, height: u32) -> Vec { (0..height) .into_par_iter() .flat_map_iter(|y| { (0..width).flat_map(move |x| { let r = (x * 255 / width) as u8; let g = (y * 255 / height) as u8; [r, g, 128u8, 255u8] }) }) .collect() } ``` -------------------------------- ### Reexport init_thread_pool Function Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md Reexport the init_thread_pool function from wasm_bindgen_rayon to expose an async initThreadPool function in JavaScript. ```rust pub use wasm_bindgen_rayon::init_thread_pool; // ... ``` -------------------------------- ### Feature Detect WebAssembly Threads in JavaScript Source: https://github.com/rreverser/wasm-bindgen-rayon/blob/main/README.md This JavaScript code uses `wasm-feature-detect` to check for WebAssembly thread support. It dynamically imports either a thread-enabled or a non-thread-enabled Wasm package based on the detection result. ```js import { threads } from 'wasm-feature-detect'; let wasmPkg; if (await threads()) { wasmPkg = await import('./pkg-with-threads/index.js'); await wasmPkg.default(); await wasmPkg.initThreadPool(navigator.hardwareConcurrency); } else { wasmPkg = await import('./pkg-without-threads/index.js'); await wasmPkg.default(); } wasmPkg.nowCallAnyExportedFuncs(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.