Skip to main content

v_shield/sync/
mod.rs

1//! 🛡️ V-Shield Sync Primitives
2//!
3//! Abstracción multiplataforma para primitivas de sincronización.
4//!
5//! # Features
6//!
7//! - `native` (default): Usa `std::sync` para Linux/Windows/macOS
8//! - `wasm`: Usa `wasm-bindgen` + `js-sys` para WASM
9//! - `async-tokio`: Wrappers async con `tokio::sync`
10//!
11//! # Ejemplo
12//!
13//! ```rust
14//! use v_shield::sync::{Mutex, RwLock};
15//!
16//! let lock = Mutex::new(42);
17//! let guard = lock.lock().unwrap();
18//! assert_eq!(*guard, 42);
19//!
20//! let rw = RwLock::new(vec![1, 2, 3]);
21//! let read = rw.read().unwrap();
22//! assert_eq!(read.len(), 3);
23//! ```
24
25pub mod mutex;
26pub mod rwlock;
27
28pub use mutex::Mutex;
29pub use rwlock::RwLock;
30
31// Re-export de condvar y barrier desde std (siempre disponible en native)
32#[cfg(all(feature = "native", not(feature = "async-tokio")))]
33pub use std::sync::{Barrier, Condvar};
34
35// En WASM, Barrier y Condvar no están en std, usamos fallback
36#[cfg(feature = "wasm")]
37pub use wasm_fallback::{Barrier, Condvar};
38
39#[cfg(feature = "wasm")]
40mod wasm_fallback {
41    use std::sync::Mutex as StdMutex;
42    use std::sync::Condvar as StdCondvar;
43
44    /// Fallback de Barrier para WASM (usa Condvar + contador)
45    pub struct Barrier {
46        count: StdMutex<usize>,
47        condvar: StdCondvar,
48        expected: usize,
49    }
50
51    impl Barrier {
52        pub fn new(n: usize) -> Self {
53            Self {
54                count: StdMutex::new(0),
55                condvar: StdCondvar::new(),
56                expected: n,
57            }
58        }
59
60        pub fn wait(&self) {
61            let mut count = self.count.lock().unwrap();
62            *count += 1;
63            if *count >= self.expected {
64                *count = 0;
65                self.condvar.notify_all();
66            } else {
67                drop(count);
68                let _ = self.condvar.wait_while(
69                    self.count.lock().unwrap(),
70                    |c| *c < self.expected,
71                );
72            }
73        }
74    }
75
76    /// Fallback de Condvar para WASM (re-export std)
77    pub type Condvar = StdCondvar;
78}
79
80// Async wrappers (solo con feature async-tokio)
81#[cfg(feature = "async-tokio")]
82pub mod async_wrappers {
83    pub use tokio::sync::{Mutex as AsyncMutex, RwLock as AsyncRwLock};
84}