1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! The primitives to work with storage in transactional mode.

use crate::Result as StorageResult;

#[cfg_attr(feature = "test-helpers", mockall::automock(type Storage = crate::test_helpers::EmptyStorage;))]
/// The types is transactional and may create `StorageTransaction`.
pub trait Transactional {
    /// The storage used when creating the transaction.
    type Storage: ?Sized;
    /// Creates and returns the storage transaction.
    fn transaction(&self) -> StorageTransaction<Self::Storage>;
}

/// The type is storage transaction and holds uncommitted state.
pub trait Transaction<Storage: ?Sized>:
    AsRef<Storage> + AsMut<Storage> + Send + Sync
{
    /// Commits the pending state changes into the storage.
    fn commit(&mut self) -> StorageResult<()>;
}

/// The storage transaction for the `Storage` type.
pub struct StorageTransaction<Storage: ?Sized> {
    transaction: Box<dyn Transaction<Storage>>,
}

impl<Storage> StorageTransaction<Storage> {
    /// Create a new storage transaction.
    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> {
    /// Committing of the state consumes `Self`.
    pub fn commit(mut self) -> StorageResult<()> {
        self.transaction.commit()
    }
}