Skip to main content

qubit_function/tasks/runnable_with/
arc_runnable_with.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 *    SPDX-License-Identifier: Apache-2.0
6 *
7 *    Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10// qubit-style: allow explicit-imports
11//! Defines the `ArcRunnableWith` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17/// Thread-safe shared runnable with mutable input.
18///
19/// `ArcRunnableWith<T, E>` stores an
20/// `Arc<Mutex<dyn FnMut(&mut T) -> Result<(), E> + Send>>`.
21///
22pub struct ArcRunnableWith<T, E> {
23    /// The stateful closure executed by this runnable.
24    pub(super) function: Arc<Mutex<dyn FnMut(&mut T) -> Result<(), E> + Send>>,
25    /// The optional name of this runnable.
26    pub(super) name: Option<String>,
27}
28
29impl<T, E> Clone for ArcRunnableWith<T, E> {
30    #[inline]
31    fn clone(&self) -> Self {
32        Self {
33            function: Arc::clone(&self.function),
34            name: self.name.clone(),
35        }
36    }
37}
38
39impl<T, E> ArcRunnableWith<T, E> {
40    impl_common_new_methods!(
41        (FnMut(&mut T) -> Result<(), E> + Send + 'static),
42        |function| Arc::new(Mutex::new(function)),
43        "runnable-with"
44    );
45
46    impl_common_name_methods!("runnable-with");
47}
48
49impl<T, E> RunnableWith<T, E> for ArcRunnableWith<T, E> {
50    /// Executes the thread-safe runnable with mutable input.
51    #[inline]
52    fn run_with(&mut self, input: &mut T) -> Result<(), E> {
53        (self.function.lock())(input)
54    }
55
56    impl_arc_conversions!(
57        ArcRunnableWith<T, E>,
58        BoxRunnableWith,
59        RcRunnableWith,
60        FnMut(input: &mut T) -> Result<(), E>
61    );
62}
63
64impl_closure_trait!(
65    RunnableWith<T, E>,
66    run_with,
67    FnMut(input: &mut T) -> Result<(), E>
68);
69
70impl_function_debug_display!(BoxRunnableWith<T, E>);
71impl_function_debug_display!(RcRunnableWith<T, E>);
72impl_function_debug_display!(ArcRunnableWith<T, E>);