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

use std::cell::RefCell;
use std::rc::Rc;

use crate::Predicate;
use crate::RcConditionalStatefulTransformer;
use crate::StatefulTransformer;
use crate::transformers::macros::impl_shared_transformer_methods;
use crate::transformers::macros::impl_transformer_clone;
use crate::transformers::macros::impl_transformer_common_methods;
use crate::transformers::macros::impl_transformer_constant_method;
use crate::transformers::macros::impl_transformer_debug_display;

// ============================================================================
// RcStatefulTransformer - Rc<RefCell<dyn FnMut(T) -> R>>
// ============================================================================

/// RcStatefulTransformer - single-threaded transformer wrapper
///
/// A single-threaded, clonable transformer wrapper optimized for scenarios
/// that require sharing without thread-safety overhead.
///
/// # Features
///
/// - **Based on**: `Rc<RefCell<dyn FnMut(T) -> R>>`
/// - **Ownership**: Shared ownership via reference counting (non-atomic)
/// - **Reusability**: Can be called multiple times (each call consumes its
///   input)
/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
/// - **Clonable**: Cheap cloning via `Rc::clone`
/// - **Statefulness**: Can modify internal state between calls
///
/// # Type Parameters
///
/// * `T` - The input type consumed by the wrapped callback.
/// * `R` - The output type produced by the wrapped callback.
///
/// # Examples
///
/// ```
/// use qubit_function::{RcStatefulTransformer, StatefulTransformer};
///
/// let mut transformer = RcStatefulTransformer::new(|value: i32| value * 2);
/// assert_eq!(transformer.apply(3), 6);
/// ```
/// # Borrowing and reentrancy
///
/// Each call holds a mutable `RefCell` borrow while the user callback runs.
/// Synchronous re-entry through the same shared wrapper panics with a borrow
/// error. Mutations completed before a panic are not rolled back.
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct RcStatefulTransformer<T, R> {
    /// The wrapped callback implementation.
    pub(super) function: Rc<RefCell<dyn FnMut(T) -> R>>,
    /// Diagnostic metadata associated with this callback.
    pub(super) metadata: crate::internal::CallbackMetadata,
}

// Implement RcStatefulTransformer
impl<T, R> RcStatefulTransformer<T, R> {
    impl_transformer_common_methods!(
        RcStatefulTransformer<T, R>,
        (FnMut(T) -> R + 'static),
        |f| Rc::new(RefCell::new(f))
    );

    impl_shared_transformer_methods!(
        RcStatefulTransformer<T, R>,
        RcConditionalStatefulTransformer,
        RcPredicate,
        StatefulTransformer,
        predicate_bounds = ('static),
        chained_bounds = ('static)
    );
}

// Implement constant method for RcStatefulTransformer
impl_transformer_constant_method!(stateful RcStatefulTransformer<T, R>);

// Implement Debug and Display for RcStatefulTransformer
impl_transformer_debug_display!(RcStatefulTransformer<T, R>);

// Implement Clone for RcStatefulTransformer
impl_transformer_clone!(RcStatefulTransformer<T, R>);

// Implement StatefulTransformer trait for RcStatefulTransformer
impl<T, R> StatefulTransformer<T, R> for RcStatefulTransformer<T, R> {
    #[inline]
    fn apply(&mut self, input: T) -> R {
        let mut self_fn = self.function.borrow_mut();
        self_fn(input)
    }
}