Add `CondVar::wait_{timeout_,}while` to `debug_sync`
[rust-lightning] / lightning / src / sync / nostd_sync.rs
index e17aa6ab15faa5dc33b66dbc1b80ab79fd36cb18..ee3e375028eba44bbb0ac723b0eb520c398be227 100644 (file)
@@ -8,6 +8,11 @@ pub type LockResult<Guard> = Result<Guard, ()>;
 
 pub struct Condvar {}
 
+pub struct WaitTimeoutResult(bool);
+impl WaitTimeoutResult {
+       pub fn timed_out(&self) -> bool { self.0 }
+}
+
 impl Condvar {
        pub fn new() -> Condvar {
                Condvar { }
@@ -22,6 +27,22 @@ impl Condvar {
                Ok((guard, ()))
        }
 
+       pub fn wait_while<'a, T, F: FnMut(&mut T) -> bool>(&'a self, mut guard: MutexGuard<'a, T>, mut condition: F)
+       -> LockResult<MutexGuard<'a, T>> {
+               assert!(!condition(&mut *guard));
+               Ok(guard)
+       }
+
+       #[allow(unused)]
+       pub fn wait_timeout_while<'a, T, F: FnMut(&mut T) -> bool>(&'a self, mut guard: MutexGuard<'a, T>, dur: Duration, mut condition: F)
+       -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
+               if condition(&mut *guard) {
+                       Ok((guard, WaitTimeoutResult(true)))
+               } else {
+                       Ok((guard, WaitTimeoutResult(false)))
+               }
+       }
+
        pub fn notify_all(&self) {}
 }
 
@@ -60,14 +81,21 @@ impl<T> Mutex<T> {
        pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
                Ok(MutexGuard { lock: self.inner.borrow_mut() })
        }
+
+       pub fn into_inner(self) -> LockResult<T> {
+               Ok(self.inner.into_inner())
+       }
 }
 
-impl<T> LockTestExt for Mutex<T> {
+impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
        #[inline]
        fn held_by_thread(&self) -> LockHeldState {
                if self.lock().is_err() { return LockHeldState::HeldByThread; }
                else { return LockHeldState::NotHeldByThread; }
        }
+       type ExclLock = MutexGuard<'a, T>;
+       #[inline]
+       fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> { self.lock().unwrap() }
 }
 
 pub struct RwLock<T: ?Sized> {
@@ -125,12 +153,15 @@ impl<T> RwLock<T> {
        }
 }
 
-impl<T> LockTestExt for RwLock<T> {
+impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
        #[inline]
        fn held_by_thread(&self) -> LockHeldState {
                if self.write().is_err() { return LockHeldState::HeldByThread; }
                else { return LockHeldState::NotHeldByThread; }
        }
+       type ExclLock = RwLockWriteGuard<'a, T>;
+       #[inline]
+       fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> { self.write().unwrap() }
 }
 
 pub type FairRwLock<T> = RwLock<T>;