Skip to main content

qubit_function/tasks/runnable_with/
rc_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 `RcRunnableWith` public type.
12
13use std::cell::RefCell;
14use std::rc::Rc;
15
16use crate::{
17    macros::{
18        impl_common_name_methods,
19        impl_common_new_methods,
20        impl_rc_conversions,
21    },
22    tasks::runnable_with::{
23        BoxRunnableWith,
24        RunnableWith,
25    },
26};
27
28type RcRunnableWithFn<T, E> = Rc<RefCell<dyn FnMut(&mut T) -> Result<(), E>>>;
29
30/// Single-threaded shared runnable with mutable input.
31///
32/// `RcRunnableWith<T, E>` stores a
33/// `Rc<RefCell<dyn FnMut(&mut T) -> Result<(), E>>>`.
34///
35pub struct RcRunnableWith<T, E> {
36    /// The stateful closure executed by this runnable.
37    pub(super) function: RcRunnableWithFn<T, E>,
38    /// The optional name of this runnable.
39    pub(super) name: Option<String>,
40}
41
42impl<T, E> Clone for RcRunnableWith<T, E> {
43    #[inline]
44    fn clone(&self) -> Self {
45        Self {
46            function: Rc::clone(&self.function),
47            name: self.name.clone(),
48        }
49    }
50}
51
52impl<T, E> RcRunnableWith<T, E> {
53    impl_common_new_methods!(
54        (FnMut(&mut T) -> Result<(), E> + 'static),
55        |function| Rc::new(RefCell::new(function)),
56        "runnable-with"
57    );
58
59    impl_common_name_methods!("runnable-with");
60}
61
62impl<T, E> RunnableWith<T, E> for RcRunnableWith<T, E> {
63    /// Executes the shared runnable with mutable input.
64    #[inline]
65    fn run_with(&mut self, input: &mut T) -> Result<(), E> {
66        (self.function.borrow_mut())(input)
67    }
68
69    impl_rc_conversions!(
70        RcRunnableWith<T, E>,
71        BoxRunnableWith,
72        FnMut(input: &mut T) -> Result<(), E>
73    );
74}