use crate::Result as StorageResult;
#[cfg_attr(feature = "test-helpers", mockall::automock(type Storage = crate::test_helpers::EmptyStorage;))]
pub trait Transactional {
type Storage: ?Sized;
fn transaction(&self) -> StorageTransaction<Self::Storage>;
}
pub trait Transaction<Storage: ?Sized>:
AsRef<Storage> + AsMut<Storage> + Send + Sync
{
fn commit(&mut self) -> StorageResult<()>;
}
pub struct StorageTransaction<Storage: ?Sized> {
transaction: Box<dyn Transaction<Storage>>,
}
impl<Storage> StorageTransaction<Storage> {
pub fn new<T: Transaction<Storage> + 'static>(t: T) -> Self {
Self {
transaction: Box::new(t),
}
}
}
impl<Storage: ?Sized> Transaction<Storage> for StorageTransaction<Storage> {
fn commit(&mut self) -> StorageResult<()> {
self.transaction.commit()
}
}
impl<Storage: ?Sized + core::fmt::Debug> core::fmt::Debug
for StorageTransaction<Storage>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("StorageTransaction")
.field("database", &self.transaction.as_ref().as_ref())
.finish()
}
}
impl<Storage: ?Sized> AsRef<Storage> for StorageTransaction<Storage> {
fn as_ref(&self) -> &Storage {
(*self.transaction).as_ref()
}
}
impl<Storage: ?Sized> AsMut<Storage> for StorageTransaction<Storage> {
fn as_mut(&mut self) -> &mut Storage {
(*self.transaction).as_mut()
}
}
impl<Storage: ?Sized> StorageTransaction<Storage> {
pub fn commit(mut self) -> StorageResult<()> {
self.transaction.commit()
}
}