prism3_function/mutators/
mutator.rs

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