Skip to content

Commit

Permalink
fix: avoid cloning if there is one reference to the content
Browse files Browse the repository at this point in the history
Signed-off-by: Amin Yahyaabadi <[email protected]>
  • Loading branch information
aminya committed Nov 27, 2023
1 parent c452d49 commit f71c936
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/engine/dag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,17 +354,9 @@ impl Dag {

/// Get the final execution result.
///
/// Note: This method will clone the value. To avoid cloning, use [`Dag::into_result`].
/// Note: This method might clone the value if there are references to the value. To avoid cloning, use [`Dag::into_result`].
pub fn get_result<T: Send + Sync + Clone + 'static>(&self) -> Option<T> {
if self.exe_sequence.is_empty() {
None
} else {
let last_id = self.exe_sequence.last().unwrap();
match self.execute_states[last_id].get_output() {
Some(ref content) => content.get().cloned(),
None => None,
}
}
self.into_result::<T>().map(unwrap_or_clone)
}

/// Get the output of all tasks.
Expand All @@ -382,12 +374,12 @@ impl Dag {

/// Get the output of all tasks.
///
/// Note: This method will clone the value. To avoid cloning, use [`Dag::into_results`].
/// Note: This method might clone the value if there are references to the value. To avoid cloning, use [`Dag::into_results`].
pub fn get_results<T: Send + Sync + Clone + 'static>(&self) -> HashMap<usize, Option<T>> {
let mut hm = HashMap::new();
for (id, state) in &self.execute_states {
let output = match state.get_output() {
Some(ref content) => content.get().cloned(),
Some(content) => content.into_inner().map(unwrap_or_clone),
None => None,
};
hm.insert(*id, output);
Expand All @@ -400,3 +392,9 @@ impl Dag {
self.env = Arc::new(env);
}
}

/// Unwrap an Arc<T> to T if possible, otherwise clone the value.
// This can be removed when Arc::unwrap_or_clone is stabilized.
fn unwrap_or_clone<T: Send + Sync + Clone + 'static>(arc: Arc<T>) -> T {
Arc::try_unwrap(arc).unwrap_or_else(|arc| (*arc).clone())
}

0 comments on commit f71c936

Please sign in to comment.