From 0a6bc4e9700b0828a0640ab5ae42de777bbb6340 Mon Sep 17 00:00:00 2001 From: NicolasCantu Date: Thu, 9 Jan 2025 17:29:14 +0100 Subject: [PATCH] Improve Process impl --- src/process.rs | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/src/process.rs b/src/process.rs index a731aad..a555792 100644 --- a/src/process.rs +++ b/src/process.rs @@ -269,6 +269,10 @@ impl Process { Ok(self.states.get(0).ok_or(anyhow::Error::msg("Empty state list"))?.commited_in) } + pub fn get_process_tip(&self) -> anyhow::Result { + Ok(self.states.last().ok_or(anyhow::Error::msg("Empty state list"))?.commited_in) + } + pub fn get_last_unspent_outpoint(&self) -> anyhow::Result { if self.states.is_empty() { return Err(anyhow::Error::msg("Empty Process")); } let last_state = self.states.last().unwrap(); @@ -337,21 +341,30 @@ impl Process { self.states.last_mut() } - pub fn get_previous_state(&self, current_state: &ProcessState) -> Option<&ProcessState> { - // Find the index of the current state - let current_index = self - .states - .iter() - .position(|state| state == current_state)?; + /// If `state` is a concurrent state, parent is the last commited one + /// Otherwise it's just the state commited before + /// If it's the initial state we return `None` + pub fn get_parent_state(&self, target_commited_in: &OutPoint) -> Option<&ProcessState> { + let tip = self.get_process_tip().ok()?; // Use `?` for cleaner error handling. - // Check if there is a previous state - if current_index > 0 { - // Create a new Process with the previous state - let previous_state = self.get_state_at(current_index - 1).unwrap(); - Some(&previous_state) - } else { - None // No previous state exists + // If the target is the current tip, return the last committed state. + if tip == *target_commited_in { + return self.get_latest_commited_state(); } + + // Iterate over the states to find the parent. + let mut parent_state = None; + for state in &self.states { + // Check if the current state's `commited_in` matches the target. + if state.commited_in == *target_commited_in { + return parent_state; // Return the parent state if found. + } + // Update the parent_state to the current state. + parent_state = Some(state); + } + + // Return `None` if no matching state is found. + None } pub fn get_state_for_id(&self, state_id: &str) -> anyhow::Result<&ProcessState> { @@ -360,7 +373,7 @@ impl Process { return Err(anyhow::Error::msg("process is empty".to_owned())); } - for p in self.get_latest_concurrent_states()? { + for p in &self.states { if state_id == p.state_id.as_str() { return Ok(p); } @@ -375,7 +388,7 @@ impl Process { return Err(anyhow::Error::msg("process is empty".to_owned())); } - for p in self.get_latest_concurrent_states_mut()? { + for p in &mut self.states { if state_id == p.state_id.as_str() { return Ok(p); }