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