use crate::store::{StoreError, StoreResult, MEMORY_LOG};
use redb::{Database, ReadableDatabase, ReadableTable};
use std::sync::Arc;
pub struct MemoryLog {
db: Arc<Database>,
}
impl MemoryLog {
pub fn new(db: Arc<Database>) -> Self {
Self { db }
}
pub fn append(&self, id: u128, data: &[u8]) -> StoreResult<()> {
let txn = self.db.begin_write()?;
{
let mut table = txn.open_table(MEMORY_LOG)?;
if table.get(id)?.is_some() {
return Err(StoreError::RecordExists(id));
}
table.insert(id, data)?;
}
txn.commit()?;
Ok(())
}
pub fn get(&self, id: &u128) -> StoreResult<Option<Vec<u8>>> {
let txn = self.db.begin_read()?;
let table = txn.open_table(MEMORY_LOG)?;
let val = table.get(*id)?;
Ok(val.map(|v| v.value().to_vec()))
}
pub fn read_all(&self) -> StoreResult<Vec<(u128, Vec<u8>)>> {
let txn = self.db.begin_read()?;
let table = txn.open_table(MEMORY_LOG)?;
let mut records = Vec::new();
for entry in table.iter()? {
let (key, value) = entry?;
records.push((key.value(), value.value().to_vec()));
}
Ok(records)
}
}