use std::ptr;
use parking_lot::{Condvar, Mutex, MutexGuard};
use crate::db::GuardedDbFields;
use crate::errors::RainDBResult;
use crate::Batch;
struct WriterInner {
pub operation_completed: bool,
pub operation_result: Option<RainDBResult<()>>,
}
pub(crate) struct Writer {
maybe_batch: Option<Batch>,
synchronous_write: bool,
inner: Mutex<WriterInner>,
thread_signaller: Condvar,
}
impl PartialEq for Writer {
fn eq(&self, other: &Self) -> bool {
self.maybe_batch == other.maybe_batch
&& self.synchronous_write == other.synchronous_write
&& ptr::eq(&self.inner, &other.inner)
}
}
impl Writer {
pub fn new(maybe_batch: Option<Batch>, synchronous_write: bool) -> Self {
let inner = WriterInner {
operation_completed: false,
operation_result: None,
};
Self {
maybe_batch,
synchronous_write,
inner: Mutex::new(inner),
thread_signaller: Condvar::new(),
}
}
pub fn is_synchronous_write(&self) -> bool {
self.synchronous_write
}
pub fn maybe_batch(&self) -> Option<&Batch> {
self.maybe_batch.as_ref()
}
pub fn wait_for_turn(&self, database_mutex_guard: &mut MutexGuard<GuardedDbFields>) {
self.thread_signaller.wait(database_mutex_guard)
}
pub fn notify_writer(&self) -> bool {
self.thread_signaller.notify_one()
}
pub fn is_operation_complete(&self) -> bool {
self.inner.lock().operation_completed
}
pub fn set_operation_completed(&self, is_complete: bool) -> bool {
let mut mutex_guard = self.inner.lock();
mutex_guard.operation_completed = is_complete;
mutex_guard.operation_completed
}
pub fn get_operation_result(&self) -> Option<RainDBResult<()>> {
self.inner.lock().operation_result.clone()
}
pub fn set_operation_result(&self, operation_result: RainDBResult<()>) {
let mut mutex_guard = self.inner.lock();
mutex_guard.operation_result = Some(operation_result);
}
}