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
13use std::sync::Arc;
14
15use parking_lot::Mutex;
16
17use crate::{
18    functions::macros::impl_function_debug_display,
19    macros::{
20        impl_arc_conversions,
21        impl_closure_trait,
22        impl_common_name_methods,
23        impl_common_new_methods,
24    },
25    tasks::runnable_with::{
26        BoxRunnableWith,
27        RcRunnableWith,
28        RunnableWith,
29    },
30};
31
32type ArcRunnableWithFn<T, E> = Arc<Mutex<dyn FnMut(&mut T) -> Result<(), E> + Send>>;
33
34/// Thread-safe shared runnable with mutable input.
35///
36/// `ArcRunnableWith<T, E>` stores an
37/// `Arc<Mutex<dyn FnMut(&mut T) -> Result<(), E> + Send>>`.
38///
39pub struct ArcRunnableWith<T, E> {
40    /// The stateful closure executed by this runnable.
41    pub(super) function: ArcRunnableWithFn<T, E>,
42    /// The optional name of this runnable.
43    pub(super) name: Option<String>,
44}
45
46impl<T, E> Clone for ArcRunnableWith<T, E> {
47    #[inline]
48    fn clone(&self) -> Self {
49        Self {
50            function: Arc::clone(&self.function),
51            name: self.name.clone(),
52        }
53    }
54}
55
56impl<T, E> ArcRunnableWith<T, E> {
57    impl_common_new_methods!(
58        (FnMut(&mut T) -> Result<(), E> + Send + 'static),
59        |function| Arc::new(Mutex::new(function)),
60        "runnable-with"
61    );
62
63    impl_common_name_methods!("runnable-with");
64}
65
66impl<T, E> RunnableWith<T, E> for ArcRunnableWith<T, E> {
67    /// Executes the thread-safe runnable with mutable input.
68    #[inline]
69    fn run_with(&mut self, input: &mut T) -> Result<(), E> {
70        (self.function.lock())(input)
71    }
72
73    impl_arc_conversions!(
74        ArcRunnableWith<T, E>,
75        BoxRunnableWith,
76        RcRunnableWith,
77        FnMut(input: &mut T) -> Result<(), E>
78    );
79}
80
81impl_closure_trait!(
82    RunnableWith<T, E>,
83    run_with,
84    FnMut(input: &mut T) -> Result<(), E>
85);
86
87impl_function_debug_display!(BoxRunnableWith<T, E>);
88impl_function_debug_display!(RcRunnableWith<T, E>);
89impl_function_debug_display!(ArcRunnableWith<T, E>);