use crate::event::types::EventId;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CausalityContext {
pub parent_ids: Vec<EventId>,
}
impl CausalityContext {
pub fn new() -> Self {
Self {
parent_ids: Vec::new(),
}
}
pub fn with_parent(parent: EventId) -> Self {
Self {
parent_ids: vec![parent],
}
}
pub fn add_parent(mut self, parent: EventId) -> Self {
self.parent_ids.push(parent);
self
}
pub fn is_root(&self) -> bool {
self.parent_ids.is_empty()
}
pub fn parent_count(&self) -> usize {
self.parent_ids.len()
}
pub fn contains_cycle(&self, event_id: &EventId) -> bool {
self.parent_ids.contains(event_id)
}
pub fn full_lineage(&self, event_id: EventId) -> Vec<EventId> {
let mut lineage = vec![event_id];
lineage.extend(self.parent_ids.clone());
lineage
}
pub fn find_cycle(&self, event_id: &EventId) -> Option<Vec<EventId>> {
if let Some(pos) = self.parent_ids.iter().position(|id| id == event_id) {
let mut cycle = self.parent_ids[pos..].to_vec();
cycle.push(*event_id); Some(cycle)
} else {
None
}
}
pub fn depth(&self) -> usize {
self.parent_ids.len()
}
}
impl Default for CausalityContext {
fn default() -> Self {
Self::new()
}
}