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 `ArcMutatingFunction` public type.

use std::sync::Arc;

use crate::ArcConditionalMutatingFunction;
use crate::Function;
use crate::MutatingFunction;
use crate::Predicate;
use crate::functions::macros::impl_function_clone;
use crate::functions::macros::impl_function_common_methods;
use crate::functions::macros::impl_function_debug_display;
use crate::functions::macros::impl_function_identity_method;
use crate::functions::macros::impl_shared_function_methods;

// =======================================================================
// 5. ArcMutatingFunction - Thread-Safe Shared Ownership
// =======================================================================

/// A cloneable wrapper around a callback that can mutate an input and return a
/// result.
///
/// The callback is stored in an `Arc` and must implement `Send + Sync`, so the
/// wrapper can be shared across threads. Calls borrow the wrapper immutably
/// and require exclusive access to each input for the duration of the call;
/// any shared state or side effects inside the callback remain the callback's
/// responsibility.
///
/// # Features
///
/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
/// - **Thread-Safe Sharing**: The stored callback must implement `Send + Sync`
/// - **Shared-Receiver Calls**: Uses `Fn`, so invocation borrows the wrapper
///   immutably; callback side effects still depend on its implementation
/// - **Chainable**: Method chaining borrows the wrapper with `&self`
///
/// # Use Cases
///
/// Choose `ArcMutatingFunction` when:
/// - The function needs to be shared across multiple threads for stateless
///   operations
/// - Concurrent task processing (e.g., thread pools)
/// - Thread safety is required (Send + Sync)
///
/// # Examples
///
/// ```rust
/// use qubit_function::{MutatingFunction, ArcMutatingFunction};
///
/// let func = ArcMutatingFunction::new(|x: &mut i32| {
///     *x *= 2;
///     *x
/// });
/// let clone = func.clone();
///
/// let mut value = 5;
/// assert_eq!(func.apply(&mut value), 10);
/// assert_eq!(value, 10);
/// ```
///
/// # Type Parameters
///
/// * `T` - The input type, mutably borrowed by the callback.
/// * `R` - The value returned by the callback after it processes the input.
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct ArcMutatingFunction<T, R> {
    /// The wrapped callback implementation.
    pub(super) function: Arc<dyn Fn(&mut T) -> R + Send + Sync>,
    /// Diagnostic metadata associated with this callback.
    pub(super) metadata: crate::internal::CallbackMetadata,
}

impl<T, R> ArcMutatingFunction<T, R> {
    // Generates: new(), new_with_name(), new_with_optional_name(), name(),
    // set_name()
    impl_function_common_methods!(
        ArcMutatingFunction<T, R>,
        (Fn(&mut T) -> R + Send + Sync + 'static),
        |f| Arc::new(f)
    );

    // Generates: when(), and_then(), compose()
    impl_shared_function_methods!(
        ArcMutatingFunction<T, R>,
        ArcConditionalMutatingFunction,
        ArcPredicate,
        Function,  // chains a non-mutating function after this mutating function
        predicate_bounds = (Send + Sync + 'static),
        chained_bounds = (Send + Sync + 'static)
    );
}

// Generates: Clone implementation for ArcMutatingFunction<T, R>
impl_function_clone!(ArcMutatingFunction<T, R>);

// Generates: Debug and Display implementations for ArcMutatingFunction<T, R>
impl_function_debug_display!(ArcMutatingFunction<T, R>);

// Generates: identity() method for ArcMutatingFunction<T, T>
impl_function_identity_method!(ArcMutatingFunction<T, T>, mutating, MutatingFunction);

impl<T, R> MutatingFunction<T, R> for ArcMutatingFunction<T, R> {
    #[inline(always)]
    fn apply(&self, input: &mut T) -> R {
        (self.function)(input)
    }
}