Skip to content

Commit 06491c1

Browse files
committed
Implement dummy RwLock
1 parent b06630d commit 06491c1

File tree

1 file changed

+57
-3
lines changed

1 file changed

+57
-3
lines changed

lightning/src/sync.rs

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
pub use ::std::sync::{RwLock, RwLockReadGuard};
21
pub use ::alloc::sync::Arc;
32
use core::ops::{Deref, DerefMut};
43
use core::time::Duration;
5-
use core::cell::{RefCell, RefMut};
4+
use core::cell::{RefCell, Ref, RefMut};
65

76
pub type LockResult<Guard> = Result<Guard, ()>;
87

@@ -64,4 +63,59 @@ impl Condvar {
6463
}
6564

6665
pub fn notify_all(&self) {}
67-
}
66+
}
67+
68+
/// This no_std version of RwLock actually only allows one lock at a time, because
69+
/// we are not expecting reentrancy in our straight-line code.
70+
pub struct RwLock<T: ?Sized> {
71+
inner: RefCell<T>
72+
}
73+
74+
pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
75+
lock: Ref<'a, T>,
76+
}
77+
78+
pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
79+
lock: RefMut<'a, T>,
80+
}
81+
82+
impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
83+
type Target = T;
84+
85+
fn deref(&self) -> &T {
86+
&self.lock.deref()
87+
}
88+
}
89+
90+
impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
91+
type Target = T;
92+
93+
fn deref(&self) -> &T {
94+
&self.lock.deref()
95+
}
96+
}
97+
98+
impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
99+
fn deref_mut(&mut self) -> &mut T {
100+
self.lock.deref_mut()
101+
}
102+
}
103+
104+
impl<T> RwLock<T> {
105+
pub fn new(inner: T) -> RwLock<T> {
106+
RwLock { inner: RefCell::new(inner) }
107+
}
108+
109+
pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>> {
110+
Ok(RwLockReadGuard { lock: self.inner.borrow() })
111+
}
112+
113+
pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
114+
Ok(RwLockWriteGuard { lock: self.inner.borrow_mut() })
115+
}
116+
117+
pub fn try_write(&self) -> LockResult<RwLockWriteGuard<'_, T>> {
118+
// There is no try, grasshopper - only used for tests and expected to fail
119+
Err(())
120+
}
121+
}

0 commit comments

Comments
 (0)