Skip to main content

qubit_function/functions/
stateful_mutating_function.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # StatefulMutatingFunction Types
10//!
11//! Provides Java-like `StatefulMutatingFunction` interface implementations
12//! for performing operations that accept a mutable reference, potentially
13//! modify internal state, and return a result.
14//!
15//! It is similar to the `FnMut(&mut T) -> R` trait in the standard library.
16//!
17//! This module provides a unified `StatefulMutatingFunction` trait and three
18//! concrete implementations based on different ownership models:
19//!
20//! - **`BoxStatefulMutatingFunction<T, R>`**: Box-based single ownership
21//!   implementation
22//! - **`ArcStatefulMutatingFunction<T, R>`**: Arc<Mutex<>>-based thread-safe
23//!   shared ownership implementation
24//! - **`RcStatefulMutatingFunction<T, R>`**: Rc<RefCell<>>-based
25//!   single-threaded shared ownership implementation
26//!
27//! # Design Philosophy
28//!
29//! `StatefulMutatingFunction` extends `MutatingFunction` with the ability to
30//! maintain internal state:
31//!
32//! - **MutatingFunction**: `Fn(&mut T) -> R` - stateless, immutable self
33//! - **StatefulMutatingFunction**: `FnMut(&mut T) -> R` - stateful, mutable
34//!   self
35//!
36//! ## Comparison with Related Types
37//!
38//! | Type | Self | Input | Modifies Self? | Modifies Input? | Returns? |
39//! |------|------|-------|----------------|-----------------|----------|
40//! | **StatefulFunction** | `&mut self` | `&T` | ✅ | ❌ | ✅ |
41//! | **StatefulMutator** | `&mut self` | `&mut T` | ✅ | ✅ | ❌ |
42//! | **StatefulMutatingFunction** | `&mut self` | `&mut T` | ✅ | ✅ | ✅ |
43//!
44//! **Key Insight**: Use `StatefulMutatingFunction` when you need to:
45//! - Maintain internal state (counters, accumulators, etc.)
46//! - Modify the input value
47//! - Return information about the operation
48//!
49//! # Comparison Table
50//!
51//! | Feature          | Box | Arc | Rc |
52//! |------------------|-----|-----|----|
53//! | Ownership        | Single | Shared | Shared |
54//! | Cloneable        | ❌ | ✅ | ✅ |
55//! | Thread-Safe      | ❌ | ✅ | ❌ |
56//! | Interior Mut.    | N/A | Mutex | RefCell |
57//! | `and_then` API   | `self` | `&self` | `&self` |
58//! | Lock Overhead    | None | Yes | None |
59//!
60//! # Use Cases
61//!
62//! ## Common Scenarios
63//!
64//! - **Stateful counters**: Increment and track modification count
65//! - **Accumulators**: Collect statistics while modifying data
66//! - **Rate limiters**: Track calls and conditionally modify
67//! - **Validators**: Accumulate errors while fixing data
68//! - **Stateful transformers**: Apply transformations based on history
69//!
70//! # Examples
71//!
72//! ## Basic Usage
73//!
74//! ```rust
75//! use qubit_function::{BoxStatefulMutatingFunction,
76//!                       StatefulMutatingFunction};
77//!
78//! // Counter that increments value and tracks calls
79//! let mut counter = {
80//!     let mut call_count = 0;
81//!     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
82//!         call_count += 1;
83//!         *x += 1;
84//!         call_count
85//!     })
86//! };
87//!
88//! let mut value = 5;
89//! assert_eq!(counter.apply(&mut value), 1);
90//! assert_eq!(value, 6);
91//! assert_eq!(counter.apply(&mut value), 2);
92//! assert_eq!(value, 7);
93//! ```
94//!
95//! ## Accumulator Pattern
96//!
97//! ```rust
98//! use qubit_function::{BoxStatefulMutatingFunction,
99//!                       StatefulMutatingFunction};
100//!
101//! // Accumulate sum while doubling values
102//! let mut accumulator = {
103//!     let mut sum = 0;
104//!     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
105//!         *x *= 2;
106//!         sum += *x;
107//!         sum
108//!     })
109//! };
110//!
111//! let mut value = 5;
112//! assert_eq!(accumulator.apply(&mut value), 10);
113//! assert_eq!(value, 10);
114//!
115//! let mut value2 = 3;
116//! assert_eq!(accumulator.apply(&mut value2), 16); // 10 + 6
117//! assert_eq!(value2, 6);
118//! ```
119//!
120//! # Author
121//!
122//! Haixing Hu
123use std::cell::RefCell;
124use std::rc::Rc;
125use std::sync::Arc;
126
127use parking_lot::Mutex;
128
129use crate::functions::{
130    function::Function,
131    macros::{
132        impl_box_conditional_function,
133        impl_box_function_methods,
134        impl_conditional_function_clone,
135        impl_conditional_function_debug_display,
136        impl_fn_ops_trait,
137        impl_function_clone,
138        impl_function_common_methods,
139        impl_function_debug_display,
140        impl_function_identity_method,
141        impl_shared_conditional_function,
142        impl_shared_function_methods,
143    },
144    mutating_function_once::BoxMutatingFunctionOnce,
145};
146use crate::macros::{
147    impl_arc_conversions,
148    impl_box_conversions,
149    impl_rc_conversions,
150};
151use crate::predicates::predicate::{
152    ArcPredicate,
153    BoxPredicate,
154    Predicate,
155    RcPredicate,
156};
157
158// =======================================================================
159// 1. StatefulMutatingFunction Trait - Unified Interface
160// =======================================================================
161
162/// StatefulMutatingFunction trait - Unified stateful mutating function
163/// interface
164///
165/// It is similar to the `FnMut(&mut T) -> R` trait in the standard library.
166///
167/// Defines the core behavior of all stateful mutating function types.
168/// Performs operations that accept a mutable reference, potentially modify
169/// both the function's internal state and the input, and return a result.
170///
171/// This trait is automatically implemented by:
172/// - All closures implementing `FnMut(&mut T) -> R`
173/// - `BoxStatefulMutatingFunction<T, R>`,
174///   `ArcStatefulMutatingFunction<T, R>`, and
175///   `RcStatefulMutatingFunction<T, R>`
176///
177/// # Design Rationale
178///
179/// The trait provides a unified abstraction over different ownership models
180/// for operations that need to maintain state while modifying input and
181/// returning results. This is useful for scenarios where you need to:
182/// - Track statistics or counts during modifications
183/// - Accumulate information across multiple calls
184/// - Implement stateful validators or transformers
185///
186/// # Features
187///
188/// - **Unified Interface**: All stateful mutating function types share the
189///   same `apply` method signature
190/// - **Automatic Implementation**: Closures automatically implement this
191///   trait
192/// - **Type Conversions**: Easy conversion between ownership models
193/// - **Generic Programming**: Write functions that work with any stateful
194///   mutating function type
195///
196/// # Examples
197///
198/// ## Generic Function
199///
200/// ```rust
201/// use qubit_function::{StatefulMutatingFunction,
202///                       BoxStatefulMutatingFunction};
203///
204/// fn apply_and_log<F: StatefulMutatingFunction<i32, i32>>(
205///     func: &mut F,
206///     value: i32
207/// ) -> i32 {
208///     let mut val = value;
209///     let result = func.apply(&mut val);
210///     println!("Modified: {} -> {}, returned: {}", value, val, result);
211///     result
212/// }
213///
214/// let mut counter = {
215///     let mut count = 0;
216///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
217///         count += 1;
218///         *x += 1;
219///         count
220///     })
221/// };
222/// assert_eq!(apply_and_log(&mut counter, 5), 1);
223/// ```
224///
225/// ## Type Conversion
226///
227/// ```rust
228/// use qubit_function::StatefulMutatingFunction;
229///
230/// let mut count = 0;
231/// let closure = move |x: &mut i32| {
232///     count += 1;
233///     *x *= 2;
234///     count
235/// };
236///
237/// // Convert to different ownership models
238/// let mut box_func = closure.into_box();
239/// // let mut rc_func = closure.into_rc();  // closure moved
240/// // let mut arc_func = closure.into_arc(); // closure moved
241/// ```
242///
243/// # Author
244///
245/// Haixing Hu
246pub trait StatefulMutatingFunction<T, R> {
247    /// Applies the function to the mutable reference and returns a result
248    ///
249    /// Executes an operation on the given mutable reference, potentially
250    /// modifying both the function's internal state and the input, and
251    /// returns a result value.
252    ///
253    /// # Parameters
254    ///
255    /// * `t` - A mutable reference to the input value
256    ///
257    /// # Returns
258    ///
259    /// The computed result value
260    ///
261    /// # Examples
262    ///
263    /// ```rust
264    /// use qubit_function::{StatefulMutatingFunction,
265    ///                       BoxStatefulMutatingFunction};
266    ///
267    /// let mut counter = {
268    ///     let mut count = 0;
269    ///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
270    ///         count += 1;
271    ///         let old = *x;
272    ///         *x += 1;
273    ///         (old, count)
274    ///     })
275    /// };
276    ///
277    /// let mut value = 5;
278    /// let (old_value, call_count) = counter.apply(&mut value);
279    /// assert_eq!(old_value, 5);
280    /// assert_eq!(call_count, 1);
281    /// assert_eq!(value, 6);
282    /// ```
283    fn apply(&mut self, t: &mut T) -> R;
284
285    /// Convert this function into a `BoxStatefulMutatingFunction<T, R>`.
286    ///
287    /// This consuming conversion takes ownership of `self` and returns a
288    /// boxed implementation that forwards calls to the original function.
289    /// Types that can provide a more efficient conversion may override the
290    /// default implementation.
291    ///
292    /// # Consumption
293    ///
294    /// This method consumes the function: the original value will no longer
295    /// be available after the call. For cloneable functions call `.clone()`
296    /// before converting if you need to retain the original instance.
297    ///
298    /// # Returns
299    ///
300    /// A `BoxStatefulMutatingFunction<T, R>` that forwards to the original
301    /// function.
302    ///
303    /// # Examples
304    ///
305    /// ```rust
306    /// use qubit_function::StatefulMutatingFunction;
307    ///
308    /// let mut count = 0;
309    /// let closure = move |x: &mut i32| {
310    ///     count += 1;
311    ///     *x *= 2;
312    ///     count
313    /// };
314    /// let mut boxed = closure.into_box();
315    /// let mut value = 5;
316    /// assert_eq!(boxed.apply(&mut value), 1);
317    /// ```
318    fn into_box(mut self) -> BoxStatefulMutatingFunction<T, R>
319    where
320        Self: Sized + 'static,
321        T: 'static,
322        R: 'static,
323    {
324        BoxStatefulMutatingFunction::new(move |t| self.apply(t))
325    }
326
327    /// Convert this function into an `RcStatefulMutatingFunction<T, R>`.
328    ///
329    /// This consuming conversion takes ownership of `self` and returns an
330    /// `Rc`-backed function that forwards calls to the original. Override to
331    /// provide a more direct or efficient conversion when available.
332    ///
333    /// # Consumption
334    ///
335    /// This method consumes the function. If you need to keep the original
336    /// instance, clone it prior to calling this method.
337    ///
338    /// # Returns
339    ///
340    /// An `RcStatefulMutatingFunction<T, R>` forwarding to the original
341    /// function.
342    ///
343    /// # Examples
344    ///
345    /// ```rust
346    /// use qubit_function::StatefulMutatingFunction;
347    ///
348    /// let mut count = 0;
349    /// let closure = move |x: &mut i32| {
350    ///     count += 1;
351    ///     *x *= 2;
352    ///     count
353    /// };
354    /// let mut rc = closure.into_rc();
355    /// let mut value = 5;
356    /// assert_eq!(rc.apply(&mut value), 1);
357    /// ```
358    fn into_rc(mut self) -> RcStatefulMutatingFunction<T, R>
359    where
360        Self: Sized + 'static,
361        T: 'static,
362        R: 'static,
363    {
364        RcStatefulMutatingFunction::new(move |t| self.apply(t))
365    }
366
367    /// Convert this function into an `ArcStatefulMutatingFunction<T, R>`.
368    ///
369    /// This consuming conversion takes ownership of `self` and returns an
370    /// `Arc`-wrapped, thread-safe function. Types may override the default
371    /// implementation to provide a more efficient conversion.
372    ///
373    /// # Consumption
374    ///
375    /// This method consumes the function. Clone the instance first if you
376    /// need to retain the original for further use.
377    ///
378    /// # Returns
379    ///
380    /// An `ArcStatefulMutatingFunction<T, R>` that forwards to the original
381    /// function.
382    ///
383    /// # Examples
384    ///
385    /// ```rust
386    /// use qubit_function::StatefulMutatingFunction;
387    ///
388    /// let mut count = 0;
389    /// let closure = move |x: &mut i32| {
390    ///     count += 1;
391    ///     *x *= 2;
392    ///     count
393    /// };
394    /// let mut arc = closure.into_arc();
395    /// let mut value = 5;
396    /// assert_eq!(arc.apply(&mut value), 1);
397    /// ```
398    fn into_arc(mut self) -> ArcStatefulMutatingFunction<T, R>
399    where
400        Self: Sized + Send + 'static,
401        T: Send + 'static,
402        R: Send + 'static,
403    {
404        ArcStatefulMutatingFunction::new(move |t| self.apply(t))
405    }
406
407    /// Consume the function and return an `FnMut(&mut T) -> R` closure.
408    ///
409    /// The returned closure forwards calls to the original function and is
410    /// suitable for use with iterator adapters or other contexts expecting
411    /// closures.
412    ///
413    /// # Consumption
414    ///
415    /// This method consumes the function. The original instance will not be
416    /// available after calling this method.
417    ///
418    /// # Returns
419    ///
420    /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
421    /// original function.
422    ///
423    /// # Examples
424    ///
425    /// ```rust
426    /// use qubit_function::{StatefulMutatingFunction,
427    ///                       BoxStatefulMutatingFunction};
428    ///
429    /// let func = {
430    ///     let mut sum = 0;
431    ///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
432    ///         *x *= 2;
433    ///         sum += *x;
434    ///         sum
435    ///     })
436    /// };
437    /// let mut closure = func.into_fn();
438    /// let mut value = 5;
439    /// assert_eq!(closure(&mut value), 10);
440    /// ```
441    fn into_fn(mut self) -> impl FnMut(&mut T) -> R
442    where
443        Self: Sized + 'static,
444    {
445        move |t| self.apply(t)
446    }
447
448    /// Create a non-consuming `BoxStatefulMutatingFunction<T, R>` that
449    /// forwards to `self`.
450    ///
451    /// The default implementation clones `self` (requires `Clone`) and
452    /// returns a boxed function that calls the cloned instance. Override this
453    /// method if a more efficient conversion exists.
454    ///
455    /// # Returns
456    ///
457    /// A `BoxStatefulMutatingFunction<T, R>` that forwards to a clone of
458    /// `self`.
459    fn to_box(&self) -> BoxStatefulMutatingFunction<T, R>
460    where
461        Self: Sized + Clone + 'static,
462        T: 'static,
463        R: 'static,
464    {
465        self.clone().into_box()
466    }
467
468    /// Create a non-consuming `RcStatefulMutatingFunction<T, R>` that
469    /// forwards to `self`.
470    ///
471    /// The default implementation clones `self` (requires `Clone`) and
472    /// returns an `Rc`-backed function that forwards calls to the clone.
473    /// Override to provide a more direct or efficient conversion if needed.
474    ///
475    /// # Returns
476    ///
477    /// An `RcStatefulMutatingFunction<T, R>` that forwards to a clone of
478    /// `self`.
479    fn to_rc(&self) -> RcStatefulMutatingFunction<T, R>
480    where
481        Self: Sized + Clone + 'static,
482        T: 'static,
483        R: 'static,
484    {
485        self.clone().into_rc()
486    }
487
488    /// Create a non-consuming `ArcStatefulMutatingFunction<T, R>` that
489    /// forwards to `self`.
490    ///
491    /// The default implementation clones `self` (requires
492    /// `Clone + Send`) and returns an `Arc`-wrapped function that forwards
493    /// calls to the clone. Override when a more efficient conversion is
494    /// available.
495    ///
496    /// # Returns
497    ///
498    /// An `ArcStatefulMutatingFunction<T, R>` that forwards to a clone of
499    /// `self`.
500    fn to_arc(&self) -> ArcStatefulMutatingFunction<T, R>
501    where
502        Self: Sized + Clone + Send + 'static,
503        T: Send + 'static,
504        R: Send + 'static,
505    {
506        self.clone().into_arc()
507    }
508
509    /// Create a boxed `FnMut(&mut T) -> R` closure that forwards to `self`.
510    ///
511    /// The default implementation clones `self` (requires `Clone`) and
512    /// returns a boxed closure that invokes the cloned instance. Override to
513    /// provide a more efficient conversion when possible.
514    ///
515    /// # Returns
516    ///
517    /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
518    /// original function.
519    fn to_fn(&self) -> impl FnMut(&mut T) -> R
520    where
521        Self: Sized + Clone + 'static,
522    {
523        self.clone().into_fn()
524    }
525
526    /// Convert to StatefulMutatingFunctionOnce
527    ///
528    /// **⚠️ Consumes `self`**: The original function will be unavailable
529    /// after calling this method.
530    ///
531    /// Converts a reusable stateful mutating function to a one-time function
532    /// that consumes itself on use. This enables passing `StatefulMutatingFunction`
533    /// to functions that require `StatefulMutatingFunctionOnce`.
534    ///
535    /// # Returns
536    ///
537    /// Returns a `BoxMutatingFunctionOnce<T, R>`
538    ///
539    /// # Examples
540    ///
541    /// ```rust
542    /// use qubit_function::{StatefulMutatingFunctionOnce,
543    ///                       StatefulMutatingFunction,
544    ///                       BoxStatefulMutatingFunction};
545    ///
546    /// fn takes_once<F: StatefulMutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
547    ///     let result = func.apply(value);
548    ///     println!("Result: {}", result);
549    /// }
550    ///
551    /// let func = BoxStatefulMutatingFunction::new(|x: &mut i32| {
552    ///     *x *= 2;
553    ///     *x
554    /// });
555    /// let mut value = 5;
556    /// takes_once(func.into_once(), &mut value);
557    /// ```
558    fn into_once(mut self) -> BoxMutatingFunctionOnce<T, R>
559    where
560        Self: Sized + 'static,
561        T: 'static,
562        R: 'static,
563    {
564        BoxMutatingFunctionOnce::new(move |t| self.apply(t))
565    }
566
567    /// Convert to StatefulMutatingFunctionOnce without consuming self
568    ///
569    /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
570    /// Clones the current function and converts the clone to a one-time function.
571    ///
572    /// # Returns
573    ///
574    /// Returns a `BoxMutatingFunctionOnce<T, R>`
575    ///
576    /// # Examples
577    ///
578    /// ```rust
579    /// use qubit_function::{StatefulMutatingFunctionOnce,
580    ///                       StatefulMutatingFunction,
581    ///                       BoxStatefulMutatingFunction};
582    ///
583    /// fn takes_once<F: StatefulMutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
584    ///     let result = func.apply(value);
585    ///     println!("Result: {}", result);
586    /// }
587    ///
588    /// let func = BoxStatefulMutatingFunction::new(|x: &mut i32| {
589    ///     *x *= 2;
590    ///     *x
591    /// });
592    /// let mut value = 5;
593    /// takes_once(func.to_once(), &mut value);
594    /// ```
595    fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
596    where
597        Self: Clone + 'static,
598        T: 'static,
599        R: 'static,
600    {
601        self.clone().into_once()
602    }
603}
604
605// =======================================================================
606// 2. Type Aliases
607// =======================================================================
608
609/// Type alias for Arc-wrapped stateful mutating function
610type ArcStatefulMutatingFunctionFn<T, R> = Arc<Mutex<dyn FnMut(&mut T) -> R + Send + 'static>>;
611
612/// Type alias for Rc-wrapped stateful mutating function
613type RcStatefulMutatingFunctionFn<T, R> = Rc<RefCell<dyn FnMut(&mut T) -> R>>;
614
615// =======================================================================
616// 3. BoxStatefulMutatingFunction - Single Ownership Implementation
617// =======================================================================
618
619/// BoxStatefulMutatingFunction struct
620///
621/// A stateful mutating function implementation based on
622/// `Box<dyn FnMut(&mut T) -> R>` for single ownership scenarios. This is the
623/// simplest and most efficient stateful mutating function type when sharing
624/// is not required.
625///
626/// # Features
627///
628/// - **Single Ownership**: Not cloneable, ownership moves on use
629/// - **Zero Overhead**: No reference counting or locking
630/// - **Stateful**: Can modify captured environment (uses `FnMut`)
631/// - **Builder Pattern**: Method chaining consumes `self` naturally
632/// - **Factory Methods**: Convenient constructors for common patterns
633///
634/// # Use Cases
635///
636/// Choose `BoxStatefulMutatingFunction` when:
637/// - The function needs to maintain internal state
638/// - Building pipelines where ownership naturally flows
639/// - No need to share the function across contexts
640/// - Performance is critical and no sharing overhead is acceptable
641///
642/// # Performance
643///
644/// `BoxStatefulMutatingFunction` has the best performance among the three
645/// function types:
646/// - No reference counting overhead
647/// - No lock acquisition or runtime borrow checking
648/// - Direct function call through vtable
649/// - Minimal memory footprint (single pointer)
650///
651/// # Examples
652///
653/// ```rust
654/// use qubit_function::{StatefulMutatingFunction,
655///                       BoxStatefulMutatingFunction};
656///
657/// let mut counter = {
658///     let mut count = 0;
659///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
660///         count += 1;
661///         *x *= 2;
662///         count
663///     })
664/// };
665/// let mut value = 5;
666/// assert_eq!(counter.apply(&mut value), 1);
667/// assert_eq!(value, 10);
668/// ```
669///
670/// # Author
671///
672/// Haixing Hu
673pub struct BoxStatefulMutatingFunction<T, R> {
674    function: Box<dyn FnMut(&mut T) -> R>,
675    name: Option<String>,
676}
677
678impl<T, R> BoxStatefulMutatingFunction<T, R> {
679    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
680    impl_function_common_methods!(
681        BoxStatefulMutatingFunction<T, R>,
682        (FnMut(&mut T) -> R + 'static),
683        |f| Box::new(f)
684    );
685
686    // Generates: when(), and_then(), compose()
687    impl_box_function_methods!(
688        BoxStatefulMutatingFunction<T, R>,
689        BoxConditionalStatefulMutatingFunction,
690        Function        // chains a non-mutating function after this mutating function
691    );
692}
693
694// Generates: Debug and Display implementations for BoxStatefulMutatingFunction<T, R>
695impl_function_debug_display!(BoxStatefulMutatingFunction<T, R>);
696
697// Generates: identity() method for BoxStatefulMutatingFunction<T, T>
698impl_function_identity_method!(BoxStatefulMutatingFunction<T, T>, mutating);
699
700// Implement StatefulMutatingFunction trait for BoxStatefulMutatingFunction<T, R>
701impl<T, R> StatefulMutatingFunction<T, R> for BoxStatefulMutatingFunction<T, R> {
702    fn apply(&mut self, t: &mut T) -> R {
703        (self.function)(t)
704    }
705
706    // Generates: into_box(), into_rc(), into_fn(), into_once()
707    impl_box_conversions!(
708        BoxStatefulMutatingFunction<T, R>,
709        RcStatefulMutatingFunction,
710        FnMut(&mut T) -> R,
711        BoxMutatingFunctionOnce
712    );
713}
714
715// =======================================================================
716// 4. RcStatefulMutatingFunction - Single-Threaded Shared Ownership
717// =======================================================================
718
719/// RcStatefulMutatingFunction struct
720///
721/// A stateful mutating function implementation based on
722/// `Rc<RefCell<dyn FnMut(&mut T) -> R>>` for single-threaded shared
723/// ownership scenarios. This type allows multiple references to the same
724/// function without the overhead of thread safety.
725///
726/// # Features
727///
728/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
729/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
730/// - **Stateful**: Can modify captured environment (uses `FnMut`)
731/// - **Chainable**: Method chaining via `&self` (non-consuming)
732/// - **Performance**: More efficient than `ArcStatefulMutatingFunction` (no
733///   locking)
734///
735/// # Use Cases
736///
737/// Choose `RcStatefulMutatingFunction` when:
738/// - The function needs to be shared within a single thread for stateful
739///   operations
740/// - Thread safety is not required
741/// - Performance is important (avoiding lock overhead)
742///
743/// # Examples
744///
745/// ```rust
746/// use qubit_function::{StatefulMutatingFunction,
747///                       RcStatefulMutatingFunction};
748///
749/// let counter = {
750///     let mut count = 0;
751///     RcStatefulMutatingFunction::new(move |x: &mut i32| {
752///         count += 1;
753///         *x *= 2;
754///         count
755///     })
756/// };
757/// let mut clone = counter.clone();
758///
759/// let mut value = 5;
760/// assert_eq!(clone.apply(&mut value), 1);
761/// ```
762///
763/// # Author
764///
765/// Haixing Hu
766pub struct RcStatefulMutatingFunction<T, R> {
767    function: RcStatefulMutatingFunctionFn<T, R>,
768    name: Option<String>,
769}
770
771impl<T, R> RcStatefulMutatingFunction<T, R> {
772    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
773    impl_function_common_methods!(
774        RcStatefulMutatingFunction<T, R>,
775        (FnMut(&mut T) -> R + 'static),
776        |f| Rc::new(RefCell::new(f))
777    );
778
779    // Generates: when(), and_then(), compose()
780    impl_shared_function_methods!(
781        RcStatefulMutatingFunction<T, R>,
782        RcConditionalStatefulMutatingFunction,
783        into_rc,
784        Function,  // chains a non-mutating function after this mutating function
785        'static
786    );
787}
788
789// Generates: Clone implementation for RcStatefulMutatingFunction<T, R>
790impl_function_clone!(RcStatefulMutatingFunction<T, R>);
791
792// Generates: Debug and Display implementations for RcStatefulMutatingFunction<T, R>
793impl_function_debug_display!(RcStatefulMutatingFunction<T, R>);
794
795// Generates: identity() method for RcStatefulMutatingFunction<T, T>
796impl_function_identity_method!(RcStatefulMutatingFunction<T, T>, mutating);
797
798// Implement StatefulMutatingFunction trait for RcStatefulMutatingFunction<T, R>
799impl<T, R> StatefulMutatingFunction<T, R> for RcStatefulMutatingFunction<T, R> {
800    fn apply(&mut self, t: &mut T) -> R {
801        (self.function.borrow_mut())(t)
802    }
803
804    // Use macro to implement conversion methods
805    impl_rc_conversions!(
806        RcStatefulMutatingFunction<T, R>,
807        BoxStatefulMutatingFunction,
808        BoxMutatingFunctionOnce,
809        FnMut(input: &mut T) -> R
810    );
811}
812
813// =======================================================================
814// 5. ArcStatefulMutatingFunction - Thread-Safe Shared Ownership
815// =======================================================================
816
817/// ArcStatefulMutatingFunction struct
818///
819/// A stateful mutating function implementation based on
820/// `Arc<Mutex<dyn FnMut(&mut T) -> R + Send>>` for thread-safe shared
821/// ownership scenarios. This type allows the function to be safely shared
822/// and used across multiple threads.
823///
824/// # Features
825///
826/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
827/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
828/// - **Stateful**: Can modify captured environment (uses `FnMut`)
829/// - **Chainable**: Method chaining via `&self` (non-consuming)
830///
831/// # Use Cases
832///
833/// Choose `ArcStatefulMutatingFunction` when:
834/// - The function needs to be shared across multiple threads for stateful
835///   operations
836/// - Concurrent task processing (e.g., thread pools)
837/// - Thread safety is required (Send + Sync)
838///
839/// # Examples
840///
841/// ```rust
842/// use qubit_function::{StatefulMutatingFunction,
843///                       ArcStatefulMutatingFunction};
844///
845/// let counter = {
846///     let mut count = 0;
847///     ArcStatefulMutatingFunction::new(move |x: &mut i32| {
848///         count += 1;
849///         *x *= 2;
850///         count
851///     })
852/// };
853/// let mut clone = counter.clone();
854///
855/// let mut value = 5;
856/// assert_eq!(clone.apply(&mut value), 1);
857/// ```
858///
859/// # Author
860///
861/// Haixing Hu
862pub struct ArcStatefulMutatingFunction<T, R> {
863    function: ArcStatefulMutatingFunctionFn<T, R>,
864    name: Option<String>,
865}
866
867impl<T, R> ArcStatefulMutatingFunction<T, R> {
868    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
869    impl_function_common_methods!(
870        ArcStatefulMutatingFunction<T, R>,
871        (FnMut(&mut T) -> R + Send + 'static),
872        |f| Arc::new(Mutex::new(f))
873    );
874
875    // Generates: when(), and_then(), compose()
876    impl_shared_function_methods!(
877        ArcStatefulMutatingFunction<T, R>,
878        ArcConditionalStatefulMutatingFunction,
879        into_arc,
880        Function,  // chains a non-mutating function after this mutating function
881        Send + Sync + 'static
882    );
883}
884
885// Generates: Clone implementation for ArcStatefulMutatingFunction<T, R>
886impl_function_clone!(ArcStatefulMutatingFunction<T, R>);
887
888// Generates: Debug and Display implementations for ArcStatefulMutatingFunction<T, R>
889impl_function_debug_display!(ArcStatefulMutatingFunction<T, R>);
890
891// Generates: identity() method for ArcStatefulMutatingFunction<T, T>
892impl_function_identity_method!(ArcStatefulMutatingFunction<T, T>, mutating);
893
894// Implement StatefulMutatingFunction trait for ArcStatefulMutatingFunction<T, R>
895impl<T, R> StatefulMutatingFunction<T, R> for ArcStatefulMutatingFunction<T, R> {
896    fn apply(&mut self, t: &mut T) -> R {
897        (self.function.lock())(t)
898    }
899
900    // Use macro to implement conversion methods
901    impl_arc_conversions!(
902        ArcStatefulMutatingFunction<T, R>,
903        BoxStatefulMutatingFunction,
904        RcStatefulMutatingFunction,
905        BoxMutatingFunctionOnce,
906        FnMut(input: &mut T) -> R
907    );
908}
909
910// =======================================================================
911// 6. Implement StatefulMutatingFunction trait for closures
912// =======================================================================
913
914impl<T, R, F> StatefulMutatingFunction<T, R> for F
915where
916    F: FnMut(&mut T) -> R,
917{
918    fn apply(&mut self, input: &mut T) -> R {
919        self(input)
920    }
921
922    fn into_box(self) -> BoxStatefulMutatingFunction<T, R>
923    where
924        Self: Sized + 'static,
925        T: 'static,
926        R: 'static,
927    {
928        BoxStatefulMutatingFunction::new(self)
929    }
930
931    fn into_rc(self) -> RcStatefulMutatingFunction<T, R>
932    where
933        Self: Sized + 'static,
934        T: 'static,
935        R: 'static,
936    {
937        RcStatefulMutatingFunction::new(self)
938    }
939
940    fn into_arc(self) -> ArcStatefulMutatingFunction<T, R>
941    where
942        Self: Sized + Send + 'static,
943        T: Send + 'static,
944        R: Send + 'static,
945    {
946        ArcStatefulMutatingFunction::new(self)
947    }
948
949    fn into_fn(self) -> impl FnMut(&mut T) -> R
950    where
951        Self: Sized + 'static,
952    {
953        self
954    }
955
956    fn to_box(&self) -> BoxStatefulMutatingFunction<T, R>
957    where
958        Self: Sized + Clone + 'static,
959        T: 'static,
960        R: 'static,
961    {
962        let cloned = self.clone();
963        BoxStatefulMutatingFunction::new(cloned)
964    }
965
966    fn to_rc(&self) -> RcStatefulMutatingFunction<T, R>
967    where
968        Self: Sized + Clone + 'static,
969        T: 'static,
970        R: 'static,
971    {
972        let cloned = self.clone();
973        RcStatefulMutatingFunction::new(cloned)
974    }
975
976    fn to_arc(&self) -> ArcStatefulMutatingFunction<T, R>
977    where
978        Self: Sized + Clone + Send + 'static,
979        T: Send + 'static,
980        R: Send + 'static,
981    {
982        let cloned = self.clone();
983        ArcStatefulMutatingFunction::new(cloned)
984    }
985
986    fn to_fn(&self) -> impl FnMut(&mut T) -> R
987    where
988        Self: Sized + Clone + 'static,
989    {
990        self.clone()
991    }
992
993    fn into_once(self) -> BoxMutatingFunctionOnce<T, R>
994    where
995        Self: Sized + 'static,
996        T: 'static,
997        R: 'static,
998    {
999        BoxMutatingFunctionOnce::new(self)
1000    }
1001
1002    fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
1003    where
1004        Self: Sized + Clone + 'static,
1005        T: 'static,
1006        R: 'static,
1007    {
1008        BoxMutatingFunctionOnce::new(self.clone())
1009    }
1010}
1011
1012// =======================================================================
1013// 7. Provide extension methods for closures
1014// =======================================================================
1015
1016// Generates: FnMutStatefulMutatingFunctionOps trait and blanket implementation
1017impl_fn_ops_trait!(
1018    (FnMut(&mut T) -> R),
1019    FnStatefulMutatingFunctionOps,
1020    BoxStatefulMutatingFunction,
1021    StatefulMutatingFunction,
1022    BoxConditionalStatefulMutatingFunction
1023);
1024
1025// ============================================================================
1026// BoxConditionalStatefulMutatingFunction - Box-based Conditional Stateful Mutating Function
1027// ============================================================================
1028
1029/// BoxConditionalStatefulMutatingFunction struct
1030///
1031/// A conditional function that only executes when a predicate is satisfied.
1032/// Uses `BoxStatefulMutatingFunction` and `BoxPredicate` for single ownership semantics.
1033///
1034/// This type is typically created by calling `BoxStatefulMutatingFunction::when()` and is
1035/// designed to work with the `or_else()` method to create if-then-else logic.
1036///
1037/// # Features
1038///
1039/// - **Single Ownership**: Not cloneable, consumes `self` on use
1040/// - **Conditional Execution**: Only transforms when predicate returns `true`
1041/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1042/// - **Implements Function**: Can be used anywhere a `Function` is expected
1043///
1044/// # Examples
1045///
1046/// ## With or_else Branch
1047///
1048/// ```rust
1049/// use qubit_function::{StatefulMutatingFunction, BoxStatefulMutatingFunction};
1050///
1051/// let double = BoxStatefulMutatingFunction::new(|x: &mut i32| x * 2);
1052/// let negate = BoxStatefulMutatingFunction::new(|x: &mut i32| -x);
1053/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
1054///
1055/// assert_eq!(conditional.apply(5), 10); // when branch executed
1056/// assert_eq!(conditional.apply(-5), 5); // or_else branch executed
1057/// ```
1058///
1059/// # Author
1060///
1061/// Haixing Hu
1062pub struct BoxConditionalStatefulMutatingFunction<T, R> {
1063    function: BoxStatefulMutatingFunction<T, R>,
1064    predicate: BoxPredicate<T>,
1065}
1066
1067// Use macro to generate conditional function implementations
1068impl_box_conditional_function!(
1069    BoxConditionalStatefulMutatingFunction<T, R>,
1070    BoxStatefulMutatingFunction,
1071    StatefulMutatingFunction
1072);
1073
1074// Use macro to generate conditional function debug and display implementations
1075impl_conditional_function_debug_display!(BoxConditionalStatefulMutatingFunction<T, R>);
1076
1077// ============================================================================
1078// RcConditionalStatefulMutatingFunction - Rc-based Conditional Stateful Mutating Function
1079// ============================================================================
1080
1081/// RcConditionalStatefulMutatingFunction struct
1082///
1083/// A single-threaded conditional function that only executes when a
1084/// predicate is satisfied. Uses `RcStatefulMutatingFunction` and `RcPredicate` for shared
1085/// ownership within a single thread.
1086///
1087/// This type is typically created by calling `RcStatefulMutatingFunction::when()` and is
1088/// designed to work with the `or_else()` method to create if-then-else logic.
1089///
1090/// # Features
1091///
1092/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1093/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1094/// - **Conditional Execution**: Only transforms when predicate returns `true`
1095/// - **No Lock Overhead**: More efficient than `ArcConditionalFunction`
1096///
1097/// # Examples
1098///
1099/// ```rust
1100/// use qubit_function::{StatefulMutatingFunction, RcStatefulMutatingFunction};
1101///
1102/// let double = RcStatefulMutatingFunction::new(|x: &mut i32| x * 2);
1103/// let identity = RcStatefulMutatingFunction::<i32, i32>::identity();
1104/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1105///
1106/// let conditional_clone = conditional.clone();
1107///
1108/// assert_eq!(conditional.apply(5), 10);
1109/// assert_eq!(conditional_clone.apply(-5), -5);
1110/// ```
1111///
1112/// # Author
1113///
1114/// Haixing Hu
1115pub struct RcConditionalStatefulMutatingFunction<T, R> {
1116    function: RcStatefulMutatingFunction<T, R>,
1117    predicate: RcPredicate<T>,
1118}
1119
1120// Use macro to generate conditional function implementations
1121impl_shared_conditional_function!(
1122    RcConditionalStatefulMutatingFunction<T, R>,
1123    RcStatefulMutatingFunction,
1124    StatefulMutatingFunction,
1125    'static
1126);
1127
1128// Use macro to generate conditional function clone implementations
1129impl_conditional_function_clone!(RcConditionalStatefulMutatingFunction<T, R>);
1130
1131// Use macro to generate conditional function debug and display implementations
1132impl_conditional_function_debug_display!(RcConditionalStatefulMutatingFunction<T, R>);
1133
1134// ============================================================================
1135// ArcConditionalStatefulMutatingFunction - Arc-based Conditional Stateful Mutating Function
1136// ============================================================================
1137
1138/// ArcConditionalStatefulMutatingFunction struct
1139///
1140/// A thread-safe conditional function that only executes when a predicate is
1141/// satisfied. Uses `ArcStatefulMutatingFunction` and `ArcPredicate` for shared ownership
1142/// across threads.
1143///
1144/// This type is typically created by calling `ArcStatefulMutatingFunction::when()` and is
1145/// designed to work with the `or_else()` method to create if-then-else logic.
1146///
1147/// # Features
1148///
1149/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1150/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1151/// - **Conditional Execution**: Only transforms when predicate returns `true`
1152/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1153///
1154/// # Examples
1155///
1156/// ```rust
1157/// use qubit_function::{StatefulMutatingFunction, ArcStatefulMutatingFunction};
1158///
1159/// let double = ArcStatefulMutatingFunction::new(|x: &mut i32| x * 2);
1160/// let identity = ArcStatefulMutatingFunction::<i32, i32>::identity();
1161/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1162///
1163/// let conditional_clone = conditional.clone();
1164///
1165/// assert_eq!(conditional.apply(5), 10);
1166/// assert_eq!(conditional_clone.apply(-5), -5);
1167/// ```
1168///
1169/// # Author
1170///
1171/// Haixing Hu
1172pub struct ArcConditionalStatefulMutatingFunction<T, R> {
1173    function: ArcStatefulMutatingFunction<T, R>,
1174    predicate: ArcPredicate<T>,
1175}
1176
1177// Use macro to generate conditional function implementations
1178impl_shared_conditional_function!(
1179    ArcConditionalStatefulMutatingFunction<T, R>,
1180    ArcStatefulMutatingFunction,
1181    StatefulMutatingFunction,
1182    Send + Sync + 'static
1183);
1184
1185// Use macro to generate conditional function clone implementations
1186impl_conditional_function_clone!(ArcConditionalStatefulMutatingFunction<T, R>);
1187
1188// Use macro to generate conditional function debug and display implementations
1189impl_conditional_function_debug_display!(ArcConditionalStatefulMutatingFunction<T, R>);