rquickjs_core/
safe_ref.rs1#[cfg(not(feature = "parallel"))]
2use std::cell::RefCell as Cell;
3
4#[cfg(feature = "parallel")]
5use std::sync::Mutex as Cell;
6
7#[cfg(not(feature = "parallel"))]
8pub use std::{
9 cell::RefMut as Lock,
10 rc::{Rc as Ref, Weak},
11};
12
13#[cfg(feature = "parallel")]
14pub use std::sync::{Arc as Ref, MutexGuard as Lock, Weak};
15
16#[repr(transparent)]
17pub struct Mut<T: ?Sized>(Cell<T>);
18
19impl<T> Mut<T> {
20 pub fn new(inner: T) -> Self {
21 Self(Cell::new(inner))
22 }
23}
24
25impl<T: Default> Default for Mut<T> {
26 fn default() -> Self {
27 Mut::new(T::default())
28 }
29}
30
31impl<T: ?Sized> Mut<T> {
32 pub fn lock(&self) -> Lock<T> {
33 #[cfg(not(feature = "parallel"))]
34 {
35 self.0.borrow_mut()
36 }
37
38 #[cfg(feature = "parallel")]
39 {
40 self.0.lock().unwrap()
41 }
42 }
43
44 pub fn try_lock(&self) -> Option<Lock<T>> {
45 #[cfg(not(feature = "parallel"))]
46 {
47 self.0.try_borrow_mut().ok()
48 }
49
50 #[cfg(feature = "parallel")]
51 {
52 self.0.lock().ok()
53 }
54 }
55}