qubit-function 0.18.2

Functional programming traits and Box/Rc/Arc adapters for Rust, inspired by Java functional interfaces
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Defines the `ArcRunnable` public type.

use std::sync::Arc;

use parking_lot::Mutex;

use crate::internal::CallbackMetadata;
use crate::macros::impl_common_name_methods;
use crate::macros::impl_common_new_methods;
use crate::suppliers::macros::impl_supplier_debug_display;
use crate::suppliers::supplier::Supplier;
use crate::tasks::runnable::Runnable;

// ============================================================================
// ArcRunnable
// ============================================================================

/// Thread-safe runnable.
///
/// `ArcRunnable<E>` stores an `Arc<Mutex<dyn FnMut() -> Result<(), E> + Send>>`
/// and can be called repeatedly across threads.
///
/// # Type Parameters
///
/// * `E` - The error value returned when the action fails.
///
/// # Locking and reentrancy
///
/// Each call acquires a `parking_lot::Mutex` and holds it while the user
/// callback runs. Synchronous re-entry through the same shared wrapper
/// deadlocks. The mutex is not poisoned after a panic, and mutations completed
/// before a panic are not rolled back.
///
/// # Examples
///
/// ```rust
/// use qubit_function::{ArcRunnable, Runnable};
///
/// let mut task = ArcRunnable::new(|| Ok::<(), String>(()));
/// assert_eq!(task.run(), Ok(()));
/// ```
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct ArcRunnable<E> {
    /// The stateful closure executed by this runnable.
    pub(super) function: Arc<Mutex<dyn FnMut() -> Result<(), E> + Send>>,
    /// The optional name of this runnable.
    pub(super) metadata: CallbackMetadata,
}

impl<E> Clone for ArcRunnable<E> {
    /// Clones the shared callback and its diagnostic metadata handle.
    #[inline]
    fn clone(&self) -> Self {
        Self {
            function: Arc::clone(&self.function),
            metadata: self.metadata.clone(),
        }
    }
}

impl<E> ArcRunnable<E> {
    impl_common_new_methods!(
        semantic_mut(Runnable<E> + Send + 'static),
        |source| move || source.run(),
        |function| Arc::new(Mutex::new(function)),
        "runnable"
    );

    /// Creates a thread-safe runnable from a reusable supplier.
    ///
    /// # Parameters
    ///
    /// * `supplier` - The supplier that produces the runnable result.
    ///
    /// # Returns
    ///
    /// A new `ArcRunnable<E>`.
    #[inline]
    pub fn from_supplier<S>(supplier: S) -> Self
    where
        S: Supplier<Result<(), E>> + Send + 'static,
    {
        Self::new(move || supplier.get())
    }

    impl_common_name_methods!("runnable");
}

impl<E> Runnable<E> for ArcRunnable<E> {
    /// Executes the thread-safe runnable.
    #[inline]
    fn run(&mut self) -> Result<(), E> {
        let mut function = self.function.lock();
        function()
    }
}

impl_supplier_debug_display!(ArcRunnable<E>);