Skip to main content

qubit_function/mutators/
stateful_mutator.rs

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