abci_storage/
lib.rs

1pub mod rocksdb;
2
3use lazy_static::lazy_static;
4use mockall::automock;
5use owning_ref::MutexGuardRefMut;
6use std::sync::Mutex;
7
8lazy_static! {
9    static ref ABCI_STORAGE_INSTANCE: Mutex<Option<AbciStorageType>> = Mutex::new(None);
10}
11
12type AbciStorageType = Box<dyn AbciStorage + Send>;
13type CustomStorageResult<T> = Result<T, Box<dyn std::error::Error>>;
14
15#[automock]
16pub trait AbciStorage {
17    fn write(&mut self, key: Vec<u8>, data: Vec<u8>) -> CustomStorageResult<()>;
18
19    fn get(&mut self, key: Vec<u8>) -> CustomStorageResult<Option<Vec<u8>>>;
20}
21
22/// Method that set abci instance.
23pub fn set_abci_storage_instance<'ret>(
24    new_instance: AbciStorageType,
25) -> Result<
26    MutexGuardRefMut<'ret, Option<AbciStorageType>, AbciStorageType>,
27    Box<dyn std::error::Error>,
28> {
29    let mut instance = ABCI_STORAGE_INSTANCE.lock()?;
30    *instance = Some(new_instance);
31    // Here we create a ref to the inner value of the mutex guard.
32    // Unwrap should never panic as we set it previously.
33    let res = MutexGuardRefMut::new(instance).map_mut(|mg| mg.as_mut().unwrap());
34    Ok(res)
35}
36
37/// Method that return abci instance.
38pub fn get_abci_storage_instance<'ret>() -> Result<
39    MutexGuardRefMut<'ret, Option<AbciStorageType>, AbciStorageType>,
40    Box<dyn std::error::Error>,
41> {
42    let instance = ABCI_STORAGE_INSTANCE.lock()?;
43    if instance.is_none() {
44        // TODO return an error
45        panic!("abci storage instance has not been set, execute set_storage_instance before calling this function");
46    }
47    // Here we create a ref to the inner value of the mutex guard.
48    // Unwrap should never panic as we set it previously.
49    let res = MutexGuardRefMut::new(instance).map_mut(|mg| mg.as_mut().unwrap());
50    Ok(res)
51}