use std::ffi::{c_int, c_void};
use std::panic::catch_unwind;
use std::sync::{Condvar, Mutex};
use crate::ffi;
struct UnlockNotification {
cond: Condvar, mutex: Mutex<bool>, }
impl UnlockNotification {
fn new() -> Self {
Self {
cond: Condvar::new(),
mutex: Mutex::new(false),
}
}
fn fired(&self) {
let mut flag = unpoison(self.mutex.lock());
*flag = true;
self.cond.notify_one();
}
fn wait(&self) {
let mut fired = unpoison(self.mutex.lock());
while !*fired {
fired = unpoison(self.cond.wait(fired));
}
}
}
#[inline]
fn unpoison<T>(r: Result<T, std::sync::PoisonError<T>>) -> T {
r.unwrap_or_else(std::sync::PoisonError::into_inner)
}
unsafe extern "C" fn unlock_notify_cb(ap_arg: *mut *mut c_void, n_arg: c_int) {
use std::slice::from_raw_parts;
unsafe {
let args = from_raw_parts(ap_arg as *const &UnlockNotification, n_arg as usize);
for un in args {
drop(catch_unwind(|| un.fired()));
}
}
}
pub unsafe fn is_locked(db: *mut ffi::sqlite3, rc: c_int) -> bool {
unsafe {
rc == ffi::SQLITE_LOCKED_SHAREDCACHE
|| (rc & 0xFF) == ffi::SQLITE_LOCKED
&& ffi::sqlite3_extended_errcode(db) == ffi::SQLITE_LOCKED_SHAREDCACHE
}
}
#[cfg(feature = "unlock_notify")]
pub unsafe fn wait_for_unlock_notify(db: *mut ffi::sqlite3) -> c_int {
let un = UnlockNotification::new();
let rc = unsafe {
ffi::sqlite3_unlock_notify(db, Some(unlock_notify_cb), &raw const un as *mut c_void)
};
debug_assert!(
rc == ffi::SQLITE_LOCKED || rc == ffi::SQLITE_LOCKED_SHAREDCACHE || rc == ffi::SQLITE_OK
);
if rc == ffi::SQLITE_OK {
un.wait();
}
rc
}