use crate::proto::{CommandBook, CommandPage, EventBook, EventPage, MergeStrategy, Snapshot};
use super::cover::CoverExt;
use super::pages::{CommandPageExt, EventPageExt};
pub trait EventBookExt: CoverExt {
fn next_sequence(&self) -> u32;
fn is_empty(&self) -> bool;
fn last_page(&self) -> Option<&EventPage>;
fn first_page(&self) -> Option<&EventPage>;
}
pub fn calculate_next_sequence(pages: &[EventPage], snapshot: Option<&Snapshot>) -> u32 {
if let Some(last_page) = pages.last() {
last_page.sequence_num() + 1
} else {
snapshot.map(|s| s.sequence + 1).unwrap_or(0)
}
}
pub fn calculate_set_next_seq(book: &mut EventBook) {
book.next_sequence = calculate_next_sequence(&book.pages, book.snapshot.as_ref());
}
impl EventBookExt for EventBook {
fn next_sequence(&self) -> u32 {
self.next_sequence
}
fn is_empty(&self) -> bool {
self.pages.is_empty()
}
fn last_page(&self) -> Option<&EventPage> {
self.pages.last()
}
fn first_page(&self) -> Option<&EventPage> {
self.pages.first()
}
}
pub trait CommandBookExt: CoverExt {
fn command_sequence(&self) -> u32;
fn first_command(&self) -> Option<&CommandPage>;
fn merge_strategy(&self) -> MergeStrategy;
}
impl CommandBookExt for CommandBook {
fn command_sequence(&self) -> u32 {
self.pages.first().map(|p| p.sequence_num()).unwrap_or(0)
}
fn first_command(&self) -> Option<&CommandPage> {
self.pages.first()
}
fn merge_strategy(&self) -> MergeStrategy {
self.pages
.first()
.map(|p| p.merge_strategy())
.unwrap_or(MergeStrategy::MergeCommutative)
}
}