use super::error::JournalError;
use super::journal::{Journal, JournalEntry, JournalReadIter};
use super::types::SequencerEvent;
use serde::{Deserialize, Serialize};
use std::sync::RwLock;
#[derive(Debug)]
pub struct InMemoryJournal<T> {
events: RwLock<Vec<SequencerEvent<T>>>,
}
impl<T> Default for InMemoryJournal<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> InMemoryJournal<T> {
#[must_use]
pub fn new() -> Self {
Self {
events: RwLock::new(Vec::new()),
}
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
events: RwLock::new(Vec::with_capacity(capacity)),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.events.read().map(|e| e.len()).unwrap_or(0)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.events.read().map(|e| e.is_empty()).unwrap_or(true)
}
}
impl<T> Journal<T> for InMemoryJournal<T>
where
T: Serialize + for<'de> Deserialize<'de> + Clone + Send + Sync + 'static,
{
fn append(&self, event: &SequencerEvent<T>) -> Result<(), JournalError> {
self.events
.write()
.map_err(|_| JournalError::Io {
message: "failed to acquire write lock".to_string(),
path: None,
})?
.push(event.clone());
Ok(())
}
fn read_from(&self, sequence: u64) -> Result<JournalReadIter<T>, JournalError> {
let events = self.events.read().map_err(|_| JournalError::Io {
message: "failed to acquire read lock".to_string(),
path: None,
})?;
let filtered: Vec<_> = events
.iter()
.filter(|e| e.sequence_num >= sequence)
.map(|event| {
Ok(JournalEntry {
event: event.clone(),
stored_crc: 0, })
})
.collect();
Ok(Box::new(filtered.into_iter()))
}
fn last_sequence(&self) -> Option<u64> {
self.events.read().ok()?.last().map(|e| e.sequence_num)
}
fn verify_integrity(&self) -> Result<(), JournalError> {
Ok(())
}
}