Skip to main content

hyprstream_rpc/
platform.rs

1//! Platform-adaptive concurrency primitives.
2//!
3//! Provides type aliases for cross-platform concurrency primitives:
4//! - Native: parking_lot (multi-threaded)
5//! - WASM: RefCell/Cell (single-threaded worker)
6//!
7//! Designed for future migration to SharedArrayBuffer when Rust wasm atomics stabilize.
8
9#[cfg(not(target_arch = "wasm32"))]
10pub use native::*;
11#[cfg(target_arch = "wasm32")]
12pub use wasm::*;
13
14#[cfg(not(target_arch = "wasm32"))]
15mod native {
16    pub type Lock<T> = parking_lot::RwLock<T>;
17    pub type Counter = std::sync::atomic::AtomicU64;
18
19    pub fn counter_next(c: &Counter) -> u64 {
20        c.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
21    }
22}
23
24#[cfg(target_arch = "wasm32")]
25mod wasm {
26    use std::cell::{Cell, RefCell};
27
28    /// RefCell-based lock for single-threaded WASM workers.
29    ///
30    /// Each Web Worker runs one WASM instance — no concurrent access.
31    pub type Lock<T> = RefCell<T>;
32
33    /// Cell-based counter for single-threaded WASM workers.
34    pub type Counter = Cell<u64>;
35
36    pub fn counter_next(c: &Counter) -> u64 {
37        let v = c.get();
38        c.set(v + 1);
39        v
40    }
41}