Improve Process impl

This commit is contained in:
NicolasCantu 2025-01-09 17:29:14 +01:00
parent cd1ab95a94
commit 0a6bc4e970

View File

@ -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<OutPoint> {
Ok(self.states.last().ok_or(anyhow::Error::msg("Empty state list"))?.commited_in)
}
pub fn get_last_unspent_outpoint(&self) -> anyhow::Result<OutPoint> {
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);
}