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
use casper_types::ProtocolVersion;
use lmdb::{Database, DatabaseFlags};

use crate::storage::{
    error,
    protocol_data::ProtocolData,
    protocol_data_store::{self, ProtocolDataStore},
    store::Store,
    transaction_source::lmdb::LmdbEnvironment,
};

/// An LMDB-backed protocol data store.
///
/// Wraps [`lmdb::Database`].
#[derive(Debug, Clone)]
pub struct LmdbProtocolDataStore {
    db: Database,
}

impl LmdbProtocolDataStore {
    pub fn new(
        env: &LmdbEnvironment,
        maybe_name: Option<&str>,
        flags: DatabaseFlags,
    ) -> Result<Self, error::Error> {
        let name = Self::name(maybe_name);
        let db = env.env().create_db(Some(&name), flags)?;
        Ok(LmdbProtocolDataStore { db })
    }

    pub fn open(env: &LmdbEnvironment, maybe_name: Option<&str>) -> Result<Self, error::Error> {
        let name = Self::name(maybe_name);
        let db = env.env().open_db(Some(&name))?;
        Ok(LmdbProtocolDataStore { db })
    }

    fn name(maybe_name: Option<&str>) -> String {
        maybe_name
            .map(|name| format!("{}-{}", protocol_data_store::NAME, name))
            .unwrap_or_else(|| String::from(protocol_data_store::NAME))
    }
}

impl Store<ProtocolVersion, ProtocolData> for LmdbProtocolDataStore {
    type Error = error::Error;

    type Handle = Database;

    fn handle(&self) -> Self::Handle {
        self.db
    }
}

impl ProtocolDataStore for LmdbProtocolDataStore {}