prism3_function/
mutator.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism 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//! # Design Philosophy
25//!
26//! Unlike `Consumer` which observes values without modifying them (`FnMut(&T)`),
27//! `Mutator` is designed to **modify input values** using `FnMut(&mut T)`.
28//!
29//! ## Mutator vs Consumer
30//!
31//! | Type | Input | Modifies Input? | Modifies Self? | Use Cases |
32//! |------|-------|----------------|----------------|-----------|
33//! | **Consumer** | `&T` | ❌ | ✅ | Observe, log, count, notify |
34//! | **Mutator** | `&mut T` | ✅ | ✅ | Modify, transform, update |
35//!
36//! **Key Insight**: If you need to modify input values, use `Mutator`.
37//! If you only need to observe or accumulate state, use `Consumer`.
38//!
39//! # Comparison Table
40//!
41//! | Feature          | BoxMutator | ArcMutator | RcMutator |
42//! |------------------|------------|------------|-----------|
43//! | Ownership        | Single     | Shared     | Shared    |
44//! | Cloneable        | ❌         | ✅         | ✅        |
45//! | Thread-Safe      | ❌         | ✅         | ❌        |
46//! | Interior Mut.    | N/A        | Mutex      | RefCell   |
47//! | `and_then` API   | `self`     | `&self`    | `&self`   |
48//! | Lock Overhead    | None       | Yes        | None      |
49//!
50//! # Use Cases
51//!
52//! ## BoxMutator
53//!
54//! - One-time operations that don't require sharing
55//! - Builder patterns where ownership naturally flows
56//! - Simple scenarios with no reuse requirements
57//!
58//! ## ArcMutator
59//!
60//! - Multi-threaded shared operations
61//! - Concurrent task processing (e.g., thread pools)
62//! - Situations requiring the same mutator across threads
63//!
64//! ## RcMutator
65//!
66//! - Single-threaded operations with multiple uses
67//! - Event handling in single-threaded UI frameworks
68//! - Performance-critical single-threaded scenarios
69//!
70//! # Examples
71//!
72//! ## Basic Usage
73//!
74//! ```rust
75//! use prism3_function::{BoxMutator, ArcMutator, RcMutator, Mutator};
76//!
77//! // BoxMutator: Single ownership, consumes self
78//! let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
79//! let mut value = 5;
80//! mutator.mutate(&mut value);
81//! assert_eq!(value, 10);
82//!
83//! // ArcMutator: Shared ownership, cloneable, thread-safe
84//! let shared = ArcMutator::new(|x: &mut i32| *x *= 2);
85//! let clone = shared.clone();
86//! let mut value = 5;
87//! let mut m = shared;
88//! m.mutate(&mut value);
89//! assert_eq!(value, 10);
90//!
91//! // RcMutator: Shared ownership, cloneable, single-threaded
92//! let rc = RcMutator::new(|x: &mut i32| *x *= 2);
93//! let clone = rc.clone();
94//! let mut value = 5;
95//! let mut m = rc;
96//! m.mutate(&mut value);
97//! assert_eq!(value, 10);
98//! ```
99//!
100//! ## Method Chaining
101//!
102//! ```rust
103//! use prism3_function::{Mutator, BoxMutator, ArcMutator};
104//!
105//! // BoxMutator: Consumes self
106//! let mut chained = BoxMutator::new(|x: &mut i32| *x *= 2)
107//!     .and_then(|x: &mut i32| *x += 10);
108//! let mut value = 5;
109//! chained.mutate(&mut value);
110//! assert_eq!(value, 20); // (5 * 2) + 10
111//!
112//! // ArcMutator: Borrows &self, original still usable
113//! let first = ArcMutator::new(|x: &mut i32| *x *= 2);
114//! let second = ArcMutator::new(|x: &mut i32| *x += 10);
115//! let combined = first.and_then(&second);
116//! // first and second are still usable here
117//! ```
118//!
119//! ## Working with Closures
120//!
121//! All closures automatically implement the `Mutator` trait:
122//!
123//! ```rust
124//! use prism3_function::{Mutator, FnMutatorOps};
125//!
126//! // Closures can use .mutate() directly
127//! let mut closure = |x: &mut i32| *x *= 2;
128//! let mut value = 5;
129//! closure.mutate(&mut value);
130//! assert_eq!(value, 10);
131//!
132//! // Closures can be chained, returning BoxMutator
133//! let mut chained = (|x: &mut i32| *x *= 2)
134//!     .and_then(|x: &mut i32| *x += 10);
135//! let mut value = 5;
136//! chained.mutate(&mut value);
137//! assert_eq!(value, 20);
138//! ```
139//!
140//! ## Type Conversions
141//!
142//! ```rust
143//! use prism3_function::Mutator;
144//!
145//! // Convert closure to concrete type
146//! let closure = |x: &mut i32| *x *= 2;
147//! let mut box_mutator = closure.into_box();
148//!
149//! let closure = |x: &mut i32| *x *= 2;
150//! let mut rc_mutator = closure.into_rc();
151//!
152//! let closure = |x: &mut i32| *x *= 2;
153//! let mut arc_mutator = closure.into_arc();
154//! ```
155//!
156//! ## Conditional Execution
157//!
158//! All mutator types support conditional execution through the `when` method,
159//! which returns a `ConditionalMutator`. You can optionally add an `or_else`
160//! branch to create if-then-else logic:
161//!
162//! ```rust
163//! use prism3_function::{Mutator, BoxMutator};
164//!
165//! // Simple conditional (if-then)
166//! let mut conditional = BoxMutator::new(|x: &mut i32| *x *= 2)
167//!     .when(|x: &i32| *x > 0);
168//!
169//! let mut positive = 5;
170//! conditional.mutate(&mut positive);
171//! assert_eq!(positive, 10); // Executed
172//!
173//! let mut negative = -5;
174//! conditional.mutate(&mut negative);
175//! assert_eq!(negative, -5); // Not executed
176//!
177//! // Conditional with else branch (if-then-else)
178//! let mut branched = BoxMutator::new(|x: &mut i32| *x *= 2)
179//!     .when(|x: &i32| *x > 0)
180//!     .or_else(|x: &mut i32| *x -= 1);
181//!
182//! let mut positive = 5;
183//! branched.mutate(&mut positive);
184//! assert_eq!(positive, 10); // when branch
185//!
186//! let mut negative = -5;
187//! branched.mutate(&mut negative);
188//! assert_eq!(negative, -6); // or_else branch
189//! ```
190//!
191//! # Author
192//!
193//! Haixing Hu
194
195use std::cell::RefCell;
196use std::rc::Rc;
197use std::sync::{Arc, Mutex};
198
199use crate::predicate::{ArcPredicate, BoxPredicate, Predicate, RcPredicate};
200
201// ============================================================================
202// 1. Mutator Trait - Unified Mutator Interface
203// ============================================================================
204
205/// Mutator trait - Unified mutator interface
206///
207/// Defines the core behavior of all mutator types. Performs operations that
208/// accept a mutable reference and modify the input value (not just side effects).
209///
210/// This trait is automatically implemented by:
211/// - All closures implementing `FnMut(&mut T)`
212/// - `BoxMutator<T>`, `ArcMutator<T>`, and `RcMutator<T>`
213///
214/// # Design Rationale
215///
216/// The trait provides a unified abstraction over different ownership models,
217/// allowing generic code to work with any mutator type. Type conversion
218/// methods (`into_box`, `into_arc`, `into_rc`) enable flexible ownership
219/// transitions based on usage requirements.
220///
221/// # Features
222///
223/// - **Unified Interface**: All mutator types share the same `mutate`
224///   method signature
225/// - **Automatic Implementation**: Closures automatically implement this
226///   trait with zero overhead
227/// - **Type Conversions**: Easy conversion between ownership models
228/// - **Generic Programming**: Write functions that work with any mutator
229///   type
230///
231/// # Examples
232///
233/// ## Generic Mutator Function
234///
235/// ```rust
236/// use prism3_function::{Mutator, BoxMutator, ArcMutator};
237///
238/// fn apply_mutator<M: Mutator<i32>>(
239///     mutator: &mut M,
240///     value: i32
241/// ) -> i32 {
242///     let mut val = value;
243///     mutator.mutate(&mut val);
244///     val
245/// }
246///
247/// // Works with any mutator type
248/// let mut box_mut = BoxMutator::new(|x: &mut i32| *x *= 2);
249/// assert_eq!(apply_mutator(&mut box_mut, 5), 10);
250///
251/// let mut arc_mut = ArcMutator::new(|x: &mut i32| *x *= 2);
252/// assert_eq!(apply_mutator(&mut arc_mut, 5), 10);
253///
254/// let mut closure = |x: &mut i32| *x *= 2;
255/// assert_eq!(apply_mutator(&mut closure, 5), 10);
256/// ```
257///
258/// ## Type Conversion
259///
260/// ```rust
261/// use prism3_function::Mutator;
262///
263/// let closure = |x: &mut i32| *x *= 2;
264///
265/// // Convert to different ownership models
266/// let box_mutator = closure.into_box();
267/// // let rc_mutator = closure.into_rc();  // closure moved
268/// // let arc_mutator = closure.into_arc(); // closure moved
269/// ```
270///
271/// # Author
272///
273/// Haixing Hu
274pub trait Mutator<T> {
275    /// Performs the mutation operation
276    ///
277    /// Executes an operation on the given mutable reference. The operation
278    /// typically modifies the input value or produces side effects.
279    ///
280    /// # Parameters
281    ///
282    /// * `value` - A mutable reference to the value to be mutated
283    ///
284    /// # Examples
285    ///
286    /// ```rust
287    /// use prism3_function::{Mutator, BoxMutator};
288    ///
289    /// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
290    /// let mut value = 5;
291    /// mutator.mutate(&mut value);
292    /// assert_eq!(value, 10);
293    /// ```
294    fn mutate(&mut self, value: &mut T);
295
296    /// Converts to BoxMutator
297    ///
298    /// **⚠️ Consumes `self`**: The original mutator becomes unavailable
299    /// after calling this method.
300    ///
301    /// Converts the current mutator to `BoxMutator<T>`.
302    ///
303    /// # Ownership
304    ///
305    /// This method **consumes** the mutator (takes ownership of `self`).
306    /// After calling this method, the original mutator is no longer
307    /// available.
308    ///
309    /// **Tip**: For cloneable mutators ([`ArcMutator`], [`RcMutator`]),
310    /// you can call `.clone()` first if you need to keep the original.
311    ///
312    /// # Returns
313    ///
314    /// Returns the wrapped `BoxMutator<T>`
315    ///
316    /// # Examples
317    ///
318    /// ## Basic Conversion
319    ///
320    /// ```rust
321    /// use prism3_function::Mutator;
322    ///
323    /// let closure = |x: &mut i32| *x *= 2;
324    /// let mut box_mutator = closure.into_box();
325    /// let mut value = 5;
326    /// box_mutator.mutate(&mut value);
327    /// assert_eq!(value, 10);
328    /// ```
329    fn into_box(self) -> BoxMutator<T>
330    where
331        Self: Sized + 'static,
332        T: 'static;
333
334    /// Converts to RcMutator
335    ///
336    /// **⚠️ Consumes `self`**: The original mutator becomes unavailable
337    /// after calling this method.
338    ///
339    /// # Returns
340    ///
341    /// Returns the wrapped `RcMutator<T>`
342    ///
343    /// # Examples
344    ///
345    /// ```rust
346    /// use prism3_function::Mutator;
347    ///
348    /// let closure = |x: &mut i32| *x *= 2;
349    /// let mut rc_mutator = closure.into_rc();
350    /// let mut value = 5;
351    /// rc_mutator.mutate(&mut value);
352    /// assert_eq!(value, 10);
353    /// ```
354    fn into_rc(self) -> RcMutator<T>
355    where
356        Self: Sized + 'static,
357        T: 'static;
358
359    /// Converts to ArcMutator
360    ///
361    /// **⚠️ Consumes `self`**: The original mutator becomes unavailable
362    /// after calling this method.
363    ///
364    /// # Returns
365    ///
366    /// Returns the wrapped `ArcMutator<T>`
367    ///
368    /// # Examples
369    ///
370    /// ```rust
371    /// use prism3_function::Mutator;
372    ///
373    /// let closure = |x: &mut i32| *x *= 2;
374    /// let mut arc_mutator = closure.into_arc();
375    /// let mut value = 5;
376    /// arc_mutator.mutate(&mut value);
377    /// assert_eq!(value, 10);
378    /// ```
379    fn into_arc(self) -> ArcMutator<T>
380    where
381        Self: Sized + Send + 'static,
382        T: Send + 'static;
383
384    /// Converts mutator to a closure for use with iterator methods
385    ///
386    /// **⚠️ Consumes `self`**: The original mutator becomes unavailable
387    /// after calling this method.
388    ///
389    /// This method consumes the mutator and returns a closure that can be
390    /// directly used with iterator methods like `for_each()`.
391    ///
392    /// # Returns
393    ///
394    /// Returns a closure that implements `FnMut(&mut T)`
395    ///
396    /// # Examples
397    ///
398    /// ```rust
399    /// use prism3_function::{Mutator, BoxMutator};
400    ///
401    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
402    /// let mut values = vec![1, 2, 3, 4, 5];
403    ///
404    /// values.iter_mut().for_each(mutator.into_fn());
405    ///
406    /// assert_eq!(values, vec![2, 4, 6, 8, 10]);
407    /// ```
408    fn into_fn(self) -> impl FnMut(&mut T)
409    where
410        Self: Sized + 'static,
411        T: 'static;
412}
413
414// ============================================================================
415// 2. Type Aliases
416// ============================================================================
417
418/// Type alias for Arc-wrapped mutable mutator function
419type ArcMutMutatorFn<T> = Arc<Mutex<dyn FnMut(&mut T) + Send>>;
420
421/// Type alias for Rc-wrapped mutable mutator function
422type RcMutMutatorFn<T> = Rc<RefCell<dyn FnMut(&mut T)>>;
423
424// ============================================================================
425// 3. BoxMutator - Single Ownership Implementation
426// ============================================================================
427
428/// BoxMutator struct
429///
430/// A mutator implementation based on `Box<dyn FnMut(&mut T)>` for single
431/// ownership scenarios. This is the simplest and most efficient mutator
432/// type when sharing is not required.
433///
434/// # Features
435///
436/// - **Single Ownership**: Not cloneable, ownership moves on use
437/// - **Zero Overhead**: No reference counting or locking
438/// - **Mutable State**: Can modify captured environment via `FnMut`
439/// - **Builder Pattern**: Method chaining consumes `self` naturally
440/// - **Factory Methods**: Convenient constructors for common patterns
441///
442/// # Use Cases
443///
444/// Choose `BoxMutator` when:
445/// - The mutator is used only once or in a linear flow
446/// - Building pipelines where ownership naturally flows
447/// - No need to share the mutator across contexts
448/// - Performance is critical and no sharing overhead is acceptable
449///
450/// # Performance
451///
452/// `BoxMutator` has the best performance among the three mutator types:
453/// - No reference counting overhead
454/// - No lock acquisition or runtime borrow checking
455/// - Direct function call through vtable
456/// - Minimal memory footprint (single pointer)
457///
458/// # Examples
459///
460/// ```rust
461/// use prism3_function::{Mutator, BoxMutator};
462///
463/// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
464/// let mut value = 5;
465/// mutator.mutate(&mut value);
466/// assert_eq!(value, 10);
467/// ```
468///
469/// # Author
470///
471/// Haixing Hu
472pub struct BoxMutator<T> {
473    func: Box<dyn FnMut(&mut T)>,
474}
475
476impl<T> BoxMutator<T>
477where
478    T: 'static,
479{
480    /// Creates a new BoxMutator
481    ///
482    /// # Parameters
483    ///
484    /// * `f` - The closure to wrap
485    ///
486    /// # Returns
487    ///
488    /// Returns a new `BoxMutator<T>` instance
489    ///
490    /// # Examples
491    ///
492    /// ```rust
493    /// use prism3_function::{Mutator, BoxMutator};
494    ///
495    /// let mut mutator = BoxMutator::new(|x: &mut i32| *x += 1);
496    /// let mut value = 5;
497    /// mutator.mutate(&mut value);
498    /// assert_eq!(value, 6);
499    /// ```
500    pub fn new<F>(f: F) -> Self
501    where
502        F: FnMut(&mut T) + 'static,
503    {
504        BoxMutator { func: Box::new(f) }
505    }
506
507    /// Creates a no-op mutator
508    ///
509    /// Returns a mutator that performs no operation.
510    ///
511    /// # Returns
512    ///
513    /// Returns a no-op mutator
514    ///
515    /// # Examples
516    ///
517    /// ```rust
518    /// use prism3_function::{Mutator, BoxMutator};
519    ///
520    /// let mut noop = BoxMutator::<i32>::noop();
521    /// let mut value = 42;
522    /// noop.mutate(&mut value);
523    /// assert_eq!(value, 42); // Value unchanged
524    /// ```
525    pub fn noop() -> Self {
526        BoxMutator::new(|_| {})
527    }
528
529    /// Chains another mutator in sequence
530    ///
531    /// Returns a new mutator that first executes the current operation, then
532    /// executes the next operation. Consumes self.
533    ///
534    /// # Parameters
535    ///
536    /// * `next` - The mutator to execute after the current operation. **Note:
537    ///   This parameter is passed by value and will transfer ownership.** If you
538    ///   need to preserve the original mutator, clone it first (if it implements
539    ///   `Clone`). Can be:
540    ///   - A closure: `|x: &mut T|`
541    ///   - A `BoxMutator<T>`
542    ///   - An `ArcMutator<T>`
543    ///   - An `RcMutator<T>`
544    ///   - Any type implementing `Mutator<T>`
545    ///
546    /// # Returns
547    ///
548    /// Returns a new composed `BoxMutator<T>`
549    ///
550    /// # Examples
551    ///
552    /// ## Direct value passing (ownership transfer)
553    ///
554    /// ```rust
555    /// use prism3_function::{Mutator, BoxMutator};
556    ///
557    /// let first = BoxMutator::new(|x: &mut i32| *x *= 2);
558    /// let second = BoxMutator::new(|x: &mut i32| *x += 10);
559    ///
560    /// // second is moved here
561    /// let mut chained = first.and_then(second);
562    /// let mut value = 5;
563    /// chained.mutate(&mut value);
564    /// assert_eq!(value, 20);
565    /// // second.mutate(&mut value); // Would not compile - moved
566    /// ```
567    ///
568    /// ## Preserving original with clone
569    ///
570    /// ```rust
571    /// use prism3_function::{Mutator, BoxMutator};
572    ///
573    /// let first = BoxMutator::new(|x: &mut i32| *x *= 2);
574    /// let second = BoxMutator::new(|x: &mut i32| *x += 10);
575    ///
576    /// // Clone to preserve original
577    /// let mut chained = first.and_then(second.clone());
578    /// let mut value = 5;
579    /// chained.mutate(&mut value);
580    /// assert_eq!(value, 20);
581    ///
582    /// // Original still usable
583    /// let mut value2 = 3;
584    /// second.mutate(&mut value2);
585    /// assert_eq!(value2, 13);
586    /// ```
587    pub fn and_then<C>(self, next: C) -> Self
588    where
589        C: Mutator<T> + 'static,
590    {
591        let mut first = self.func;
592        let mut second = next;
593        BoxMutator::new(move |t| {
594            first(t);
595            second.mutate(t);
596        })
597    }
598
599    /// Creates a conditional mutator
600    ///
601    /// Returns a mutator that only executes when a predicate is satisfied.
602    ///
603    /// # Parameters
604    ///
605    /// * `predicate` - The condition to check. **Note: This parameter is passed
606    ///   by value and will transfer ownership.** If you need to preserve the
607    ///   original predicate, clone it first (if it implements `Clone`).
608    ///   Can be:
609    ///   - A closure: `|x: &T| -> bool`
610    ///   - A function pointer: `fn(&T) -> bool`
611    ///   - A `BoxPredicate<T>`
612    ///   - An `RcPredicate<T>`
613    ///   - An `ArcPredicate<T>`
614    ///   - Any type implementing `Predicate<T>`
615    ///
616    /// # Returns
617    ///
618    /// Returns `BoxConditionalMutator<T>`
619    ///
620    /// # Examples
621    ///
622    /// ## Using a closure
623    ///
624    /// ```rust
625    /// use prism3_function::{Mutator, BoxMutator};
626    ///
627    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
628    /// let mut conditional = mutator.when(|x: &i32| *x > 0);
629    ///
630    /// let mut positive = 5;
631    /// conditional.mutate(&mut positive);
632    /// assert_eq!(positive, 10);
633    ///
634    /// let mut negative = -5;
635    /// conditional.mutate(&mut negative);
636    /// assert_eq!(negative, -5); // Unchanged
637    /// ```
638    ///
639    /// ## Using BoxPredicate
640    ///
641    /// ```rust
642    /// use prism3_function::{Mutator, BoxMutator};
643    /// use prism3_function::predicate::{Predicate, BoxPredicate};
644    ///
645    /// let pred = BoxPredicate::new(|x: &i32| *x > 0);
646    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
647    /// let mut conditional = mutator.when(pred);
648    ///
649    /// let mut value = 5;
650    /// conditional.mutate(&mut value);
651    /// assert_eq!(value, 10);
652    /// ```
653    ///
654    /// ## Using composed predicate
655    ///
656    /// ```rust
657    /// use prism3_function::{Mutator, BoxMutator};
658    /// use prism3_function::predicate::{Predicate, FnPredicateOps};
659    ///
660    /// let pred = (|x: &i32| *x > 0).and(|x: &i32| x % 2 == 0);
661    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
662    /// let mut conditional = mutator.when(pred);
663    ///
664    /// let mut value = 4;
665    /// conditional.mutate(&mut value);
666    /// assert_eq!(value, 8); // Positive and even
667    ///
668    /// let mut odd = 3;
669    /// conditional.mutate(&mut odd);
670    /// assert_eq!(odd, 3); // Positive but odd, unchanged
671    /// ```
672    pub fn when<P>(self, predicate: P) -> BoxConditionalMutator<T>
673    where
674        P: Predicate<T> + 'static,
675    {
676        BoxConditionalMutator {
677            mutator: self,
678            predicate: predicate.into_box(),
679        }
680    }
681}
682
683impl<T> Mutator<T> for BoxMutator<T> {
684    fn mutate(&mut self, value: &mut T) {
685        (self.func)(value)
686    }
687
688    fn into_box(self) -> BoxMutator<T>
689    where
690        T: 'static,
691    {
692        self
693    }
694
695    fn into_rc(self) -> RcMutator<T>
696    where
697        T: 'static,
698    {
699        let mut func = self.func;
700        RcMutator::new(move |t| func(t))
701    }
702
703    fn into_arc(self) -> ArcMutator<T>
704    where
705        T: Send + 'static,
706    {
707        panic!(
708            "Cannot convert BoxMutator to ArcMutator: BoxMutator's inner function may not be Send"
709        )
710    }
711
712    fn into_fn(mut self) -> impl FnMut(&mut T)
713    where
714        Self: Sized + 'static,
715        T: 'static,
716    {
717        move |t: &mut T| (self.func)(t)
718    }
719}
720
721// ============================================================================
722// 3. BoxConditionalMutator - Box-based Conditional Mutator
723// ============================================================================
724
725/// BoxConditionalMutator struct
726///
727/// A conditional mutator that only executes when a predicate is satisfied.
728/// Uses `BoxMutator` and `BoxPredicate` for single ownership semantics.
729///
730/// This type is typically created by calling `BoxMutator::when()` and is
731/// designed to work with the `or_else()` method to create if-then-else logic.
732///
733/// # Features
734///
735/// - **Single Ownership**: Not cloneable, consumes `self` on use
736/// - **Conditional Execution**: Only mutates when predicate returns `true`
737/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
738/// - **Implements Mutator**: Can be used anywhere a `Mutator` is expected
739///
740/// # Examples
741///
742/// ## Basic Conditional Execution
743///
744/// ```rust
745/// use prism3_function::{Mutator, BoxMutator};
746///
747/// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
748/// let mut conditional = mutator.when(|x: &i32| *x > 0);
749///
750/// let mut positive = 5;
751/// conditional.mutate(&mut positive);
752/// assert_eq!(positive, 10); // Executed
753///
754/// let mut negative = -5;
755/// conditional.mutate(&mut negative);
756/// assert_eq!(negative, -5); // Not executed
757/// ```
758///
759/// ## With or_else Branch
760///
761/// ```rust
762/// use prism3_function::{Mutator, BoxMutator};
763///
764/// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2)
765///     .when(|x: &i32| *x > 0)
766///     .or_else(|x: &mut i32| *x -= 1);
767///
768/// let mut positive = 5;
769/// mutator.mutate(&mut positive);
770/// assert_eq!(positive, 10); // when branch executed
771///
772/// let mut negative = -5;
773/// mutator.mutate(&mut negative);
774/// assert_eq!(negative, -6); // or_else branch executed
775/// ```
776///
777/// # Author
778///
779/// Haixing Hu
780pub struct BoxConditionalMutator<T> {
781    mutator: BoxMutator<T>,
782    predicate: BoxPredicate<T>,
783}
784impl<T> Mutator<T> for BoxConditionalMutator<T>
785where
786    T: 'static,
787{
788    fn mutate(&mut self, value: &mut T) {
789        if self.predicate.test(value) {
790            self.mutator.mutate(value);
791        }
792    }
793
794    fn into_box(self) -> BoxMutator<T> {
795        let pred = self.predicate;
796        let mut mutator = self.mutator;
797        BoxMutator::new(move |t| {
798            if pred.test(t) {
799                mutator.mutate(t);
800            }
801        })
802    }
803
804    fn into_rc(self) -> RcMutator<T> {
805        let pred = self.predicate.into_rc();
806        let mutator = self.mutator.into_rc();
807        let pred_fn = pred.to_fn();
808        let mut mutator_fn = mutator;
809        RcMutator::new(move |t| {
810            if pred_fn(t) {
811                mutator_fn.mutate(t);
812            }
813        })
814    }
815
816    fn into_arc(self) -> ArcMutator<T>
817    where
818        T: Send + 'static,
819    {
820        panic!(
821            "Cannot convert BoxConditionalMutator to ArcMutator: \
822             predicate and mutator may not be Send + Sync"
823        )
824    }
825
826    fn into_fn(self) -> impl FnMut(&mut T) {
827        let pred = self.predicate;
828        let mut mutator = self.mutator;
829        move |t: &mut T| {
830            if pred.test(t) {
831                mutator.mutate(t);
832            }
833        }
834    }
835}
836impl<T> BoxConditionalMutator<T>
837where
838    T: 'static,
839{
840    /// Chains another mutator in sequence
841    ///
842    /// Combines the current conditional mutator with another mutator into a new
843    /// mutator. The current conditional mutator executes first, followed by the
844    /// next mutator.
845    ///
846    /// # Parameters
847    ///
848    /// * `next` - The next mutator to execute. **Note: This parameter is passed
849    ///   by value and will transfer ownership.** If you need to preserve the
850    ///   original mutator, clone it first (if it implements `Clone`). Can be:
851    ///   - A closure: `|x: &mut T|`
852    ///   - A `BoxMutator<T>`
853    ///   - An `ArcMutator<T>`
854    ///   - An `RcMutator<T>`
855    ///   - Any type implementing `Mutator<T>`
856    ///
857    /// # Returns
858    ///
859    /// Returns a new `BoxMutator<T>`
860    ///
861    /// # Examples
862    ///
863    /// ## Direct value passing (ownership transfer)
864    ///
865    /// ```rust
866    /// use prism3_function::{Mutator, BoxMutator};
867    ///
868    /// let cond1 = BoxMutator::new(|x: &mut i32| *x *= 2).when(|x: &i32| *x > 0);
869    /// let cond2 = BoxMutator::new(|x: &mut i32| *x = 100).when(|x: &i32| *x > 100);
870    ///
871    /// // cond2 is moved here
872    /// let mut chained = cond1.and_then(cond2);
873    /// let mut value = 60;
874    /// chained.mutate(&mut value);
875    /// assert_eq!(value, 100); // First *2 = 120, then capped to 100
876    /// // cond2.mutate(&mut value); // Would not compile - moved
877    /// ```
878    ///
879    /// ## Preserving original with clone
880    ///
881    /// ```rust
882    /// use prism3_function::{Mutator, BoxMutator};
883    ///
884    /// let cond1 = BoxMutator::new(|x: &mut i32| *x *= 2).when(|x: &i32| *x > 0);
885    /// let cond2 = BoxMutator::new(|x: &mut i32| *x = 100).when(|x: &i32| *x > 100);
886    ///
887    /// // Clone to preserve original
888    /// let mut chained = cond1.and_then(cond2.clone());
889    /// let mut value = 60;
890    /// chained.mutate(&mut value);
891    /// assert_eq!(value, 100); // First *2 = 120, then capped to 100
892    ///
893    /// // Original still usable
894    /// let mut value2 = 50;
895    /// cond2.mutate(&mut value2);
896    /// assert_eq!(value2, 100);
897    /// ```
898    pub fn and_then<C>(self, next: C) -> BoxMutator<T>
899    where
900        C: Mutator<T> + 'static,
901    {
902        let mut first = self;
903        let mut second = next;
904        BoxMutator::new(move |t| {
905            first.mutate(t);
906            second.mutate(t);
907        })
908    }
909
910    /// Adds an else branch
911    ///
912    /// Executes the original mutator when the condition is satisfied, otherwise
913    /// executes else_mutator.
914    ///
915    /// # Parameters
916    ///
917    /// * `else_mutator` - The mutator for the else branch. **Note: This parameter
918    ///   is passed by value and will transfer ownership.** If you need to preserve
919    ///   the original mutator, clone it first (if it implements `Clone`). Can be:
920    ///   - A closure: `|x: &mut T|`
921    ///   - A `BoxMutator<T>`
922    ///   - An `RcMutator<T>`
923    ///   - An `ArcMutator<T>`
924    ///   - Any type implementing `Mutator<T>`
925    ///
926    /// # Returns
927    ///
928    /// Returns the composed `BoxMutator<T>`
929    ///
930    /// # Examples
931    ///
932    /// ## Using a closure (recommended)
933    ///
934    /// ```rust
935    /// use prism3_function::{Mutator, BoxMutator};
936    ///
937    /// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2)
938    ///     .when(|x: &i32| *x > 0)
939    ///     .or_else(|x: &mut i32| *x -= 1);
940    ///
941    /// let mut positive = 5;
942    /// mutator.mutate(&mut positive);
943    /// assert_eq!(positive, 10); // Condition satisfied, execute *2
944    ///
945    /// let mut negative = -5;
946    /// mutator.mutate(&mut negative);
947    /// assert_eq!(negative, -6); // Condition not satisfied, execute -1
948    /// ```
949    pub fn or_else<C>(self, else_mutator: C) -> BoxMutator<T>
950    where
951        C: Mutator<T> + 'static,
952    {
953        let pred = self.predicate;
954        let mut then_mut = self.mutator;
955        let mut else_mut = else_mutator;
956        BoxMutator::new(move |t| {
957            if pred.test(t) {
958                then_mut.mutate(t);
959            } else {
960                else_mut.mutate(t);
961            }
962        })
963    }
964}
965
966// ============================================================================
967// 4. RcMutator - Single-Threaded Shared Ownership Implementation
968// ============================================================================
969
970/// RcMutator struct
971///
972/// A mutator implementation based on `Rc<RefCell<dyn FnMut(&mut T)>>` for
973/// single-threaded shared ownership scenarios. This type allows multiple
974/// references to the same mutator without the overhead of thread safety.
975///
976/// # Features
977///
978/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
979/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
980/// - **Interior Mutability**: Uses `RefCell` for runtime borrow checking
981/// - **Mutable State**: Can modify captured environment via `FnMut`
982/// - **Chainable**: Method chaining via `&self` (non-consuming)
983/// - **Performance**: More efficient than `ArcMutator` (no locking)
984///
985/// # Use Cases
986///
987/// Choose `RcMutator` when:
988/// - The mutator needs to be shared within a single thread
989/// - Thread safety is not required
990/// - Performance is important (avoiding lock overhead)
991///
992/// # Examples
993///
994/// ```rust
995/// use prism3_function::{Mutator, RcMutator};
996///
997/// let mutator = RcMutator::new(|x: &mut i32| *x *= 2);
998/// let clone = mutator.clone();
999///
1000/// let mut value = 5;
1001/// let mut m = mutator;
1002/// m.mutate(&mut value);
1003/// assert_eq!(value, 10);
1004/// ```
1005///
1006/// # Author
1007///
1008/// Haixing Hu
1009pub struct RcMutator<T> {
1010    func: RcMutMutatorFn<T>,
1011}
1012
1013impl<T> RcMutator<T>
1014where
1015    T: 'static,
1016{
1017    /// Creates a new RcMutator
1018    ///
1019    /// # Parameters
1020    ///
1021    /// * `f` - The closure to wrap
1022    ///
1023    /// # Returns
1024    ///
1025    /// Returns a new `RcMutator<T>` instance
1026    ///
1027    /// # Examples
1028    ///
1029    /// ```rust
1030    /// use prism3_function::{Mutator, RcMutator};
1031    ///
1032    /// let mutator = RcMutator::new(|x: &mut i32| *x += 1);
1033    /// let mut value = 5;
1034    /// let mut m = mutator;
1035    /// m.mutate(&mut value);
1036    /// assert_eq!(value, 6);
1037    /// ```
1038    pub fn new<F>(f: F) -> Self
1039    where
1040        F: FnMut(&mut T) + 'static,
1041    {
1042        RcMutator {
1043            func: Rc::new(RefCell::new(f)),
1044        }
1045    }
1046
1047    /// Creates a no-op mutator
1048    ///
1049    /// Returns a mutator that performs no operation.
1050    ///
1051    /// # Returns
1052    ///
1053    /// Returns a no-op mutator
1054    ///
1055    /// # Examples
1056    ///
1057    /// ```rust
1058    /// use prism3_function::{Mutator, RcMutator};
1059    ///
1060    /// let noop = RcMutator::<i32>::noop();
1061    /// let mut value = 42;
1062    /// let mut m = noop;
1063    /// m.mutate(&mut value);
1064    /// assert_eq!(value, 42); // Value unchanged
1065    /// ```
1066    pub fn noop() -> Self {
1067        RcMutator::new(|_| {})
1068    }
1069
1070    /// Chains another RcMutator in sequence
1071    ///
1072    /// Returns a new mutator that first executes the current operation, then
1073    /// executes the next operation. Borrows &self, does not consume the
1074    /// original mutator.
1075    ///
1076    /// # Parameters
1077    ///
1078    /// * `next` - The mutator to execute after the current operation
1079    ///
1080    /// # Returns
1081    ///
1082    /// Returns a new composed `RcMutator<T>`
1083    ///
1084    /// # Examples
1085    ///
1086    /// ```rust
1087    /// use prism3_function::{Mutator, RcMutator};
1088    ///
1089    /// let first = RcMutator::new(|x: &mut i32| *x *= 2);
1090    /// let second = RcMutator::new(|x: &mut i32| *x += 10);
1091    ///
1092    /// let chained = first.and_then(&second);
1093    ///
1094    /// // first and second are still usable
1095    /// let mut value = 5;
1096    /// let mut m = chained;
1097    /// m.mutate(&mut value);
1098    /// assert_eq!(value, 20); // (5 * 2) + 10
1099    /// ```
1100    pub fn and_then(&self, next: &RcMutator<T>) -> RcMutator<T> {
1101        let first = Rc::clone(&self.func);
1102        let second = Rc::clone(&next.func);
1103        RcMutator {
1104            func: Rc::new(RefCell::new(move |t: &mut T| {
1105                first.borrow_mut()(t);
1106                second.borrow_mut()(t);
1107            })),
1108        }
1109    }
1110
1111    /// Creates a conditional mutator (single-threaded shared version)
1112    ///
1113    /// Returns a mutator that only executes when a predicate is satisfied.
1114    ///
1115    /// # Parameters
1116    ///
1117    /// * `predicate` - The condition to check. **Note: This parameter is passed
1118    ///   by value and will transfer ownership.** If you need to preserve the
1119    ///   original predicate, clone it first (if it implements `Clone`). Can be:
1120    ///   - A closure: `|x: &T| -> bool`
1121    ///   - A function pointer: `fn(&T) -> bool`
1122    ///   - An `RcPredicate<T>`
1123    ///   - A `BoxPredicate<T>`
1124    ///   - Any type implementing `Predicate<T>`
1125    ///
1126    /// # Returns
1127    ///
1128    /// Returns `RcConditionalMutator<T>`
1129    ///
1130    /// # Examples
1131    ///
1132    /// ```rust
1133    /// use prism3_function::{Mutator, RcMutator};
1134    ///
1135    /// let mutator = RcMutator::new(|x: &mut i32| *x *= 2);
1136    /// let conditional = mutator.when(|x: &i32| *x > 0);
1137    ///
1138    /// let conditional_clone = conditional.clone();
1139    ///
1140    /// let mut positive = 5;
1141    /// let mut m = conditional;
1142    /// m.mutate(&mut positive);
1143    /// assert_eq!(positive, 10);
1144    /// ```
1145    pub fn when<P>(self, predicate: P) -> RcConditionalMutator<T>
1146    where
1147        P: Predicate<T> + 'static,
1148    {
1149        RcConditionalMutator {
1150            mutator: self,
1151            predicate: predicate.into_rc(),
1152        }
1153    }
1154}
1155
1156impl<T> Mutator<T> for RcMutator<T> {
1157    fn mutate(&mut self, value: &mut T) {
1158        (self.func.borrow_mut())(value)
1159    }
1160
1161    fn into_box(self) -> BoxMutator<T>
1162    where
1163        T: 'static,
1164    {
1165        let func = self.func;
1166        BoxMutator::new(move |t| func.borrow_mut()(t))
1167    }
1168
1169    fn into_rc(self) -> RcMutator<T>
1170    where
1171        T: 'static,
1172    {
1173        self
1174    }
1175
1176    fn into_arc(self) -> ArcMutator<T>
1177    where
1178        T: Send + 'static,
1179    {
1180        panic!("Cannot convert RcMutator to ArcMutator (not Send)")
1181    }
1182
1183    fn into_fn(self) -> impl FnMut(&mut T)
1184    where
1185        Self: Sized + 'static,
1186        T: 'static,
1187    {
1188        let func = self.func;
1189        move |t: &mut T| func.borrow_mut()(t)
1190    }
1191}
1192
1193impl<T> Clone for RcMutator<T> {
1194    /// Clones the RcMutator
1195    ///
1196    /// Creates a new RcMutator that shares the underlying function with the
1197    /// original instance.
1198    fn clone(&self) -> Self {
1199        Self {
1200            func: Rc::clone(&self.func),
1201        }
1202    }
1203}
1204
1205// ============================================================================
1206// 5. RcConditionalMutator - Rc-based Conditional Mutator
1207// ============================================================================
1208
1209/// RcConditionalMutator struct
1210///
1211/// A single-threaded conditional mutator that only executes when a predicate is
1212/// satisfied. Uses `RcMutator` and `RcPredicate` for shared ownership within a
1213/// single thread.
1214///
1215/// This type is typically created by calling `RcMutator::when()` and is
1216/// designed to work with the `or_else()` method to create if-then-else logic.
1217///
1218/// # Features
1219///
1220/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1221/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1222/// - **Conditional Execution**: Only mutates when predicate returns `true`
1223/// - **No Lock Overhead**: More efficient than `ArcConditionalMutator`
1224///
1225/// # Examples
1226///
1227/// ```rust
1228/// use prism3_function::{Mutator, RcMutator};
1229///
1230/// let conditional = RcMutator::new(|x: &mut i32| *x *= 2)
1231///     .when(|x: &i32| *x > 0);
1232///
1233/// let conditional_clone = conditional.clone();
1234///
1235/// let mut value = 5;
1236/// let mut m = conditional;
1237/// m.mutate(&mut value);
1238/// assert_eq!(value, 10);
1239/// ```
1240///
1241/// # Author
1242///
1243/// Haixing Hu
1244pub struct RcConditionalMutator<T> {
1245    mutator: RcMutator<T>,
1246    predicate: RcPredicate<T>,
1247}
1248impl<T> Mutator<T> for RcConditionalMutator<T>
1249where
1250    T: 'static,
1251{
1252    fn mutate(&mut self, value: &mut T) {
1253        if self.predicate.test(value) {
1254            self.mutator.mutate(value);
1255        }
1256    }
1257
1258    fn into_box(self) -> BoxMutator<T> {
1259        let pred = self.predicate;
1260        let mut mutator = self.mutator;
1261        BoxMutator::new(move |t| {
1262            if pred.test(t) {
1263                mutator.mutate(t);
1264            }
1265        })
1266    }
1267
1268    fn into_rc(self) -> RcMutator<T> {
1269        let pred = self.predicate;
1270        let mut mutator = self.mutator;
1271        RcMutator::new(move |t| {
1272            if pred.test(t) {
1273                mutator.mutate(t);
1274            }
1275        })
1276    }
1277
1278    fn into_arc(self) -> ArcMutator<T>
1279    where
1280        T: Send + 'static,
1281    {
1282        panic!("Cannot convert RcConditionalMutator to ArcMutator: not Send")
1283    }
1284
1285    fn into_fn(self) -> impl FnMut(&mut T) {
1286        let pred = self.predicate;
1287        let mut mutator = self.mutator;
1288        move |t: &mut T| {
1289            if pred.test(t) {
1290                mutator.mutate(t);
1291            }
1292        }
1293    }
1294}
1295impl<T> RcConditionalMutator<T>
1296where
1297    T: 'static,
1298{
1299    /// Adds an else branch (single-threaded shared version)
1300    ///
1301    /// Executes the original mutator when the condition is satisfied, otherwise
1302    /// executes else_mutator.
1303    ///
1304    /// # Parameters
1305    ///
1306    /// * `else_mutator` - The mutator for the else branch. **Note: This parameter
1307    ///   is passed by value and will transfer ownership.** If you need to preserve
1308    ///   the original mutator, clone it first (if it implements `Clone`). Can be:
1309    ///   - A closure: `|x: &mut T|`
1310    ///   - An `RcMutator<T>`
1311    ///   - A `BoxMutator<T>`
1312    ///   - Any type implementing `Mutator<T>`
1313    ///
1314    /// # Returns
1315    ///
1316    /// Returns the composed `RcMutator<T>`
1317    ///
1318    /// # Examples
1319    ///
1320    /// ## Using a closure (recommended)
1321    ///
1322    /// ```rust
1323    /// use prism3_function::{Mutator, RcMutator};
1324    ///
1325    /// let mut mutator = RcMutator::new(|x: &mut i32| *x *= 2)
1326    ///     .when(|x: &i32| *x > 0)
1327    ///     .or_else(|x: &mut i32| *x -= 1);
1328    ///
1329    /// let mut positive = 5;
1330    /// mutator.mutate(&mut positive);
1331    /// assert_eq!(positive, 10);
1332    ///
1333    /// let mut negative = -5;
1334    /// mutator.mutate(&mut negative);
1335    /// assert_eq!(negative, -6);
1336    /// ```
1337    pub fn or_else<C>(self, else_mutator: C) -> RcMutator<T>
1338    where
1339        C: Mutator<T> + 'static,
1340    {
1341        let pred = self.predicate;
1342        let mut then_mut = self.mutator;
1343        let mut else_mut = else_mutator;
1344
1345        RcMutator::new(move |t: &mut T| {
1346            if pred.test(t) {
1347                then_mut.mutate(t);
1348            } else {
1349                else_mut.mutate(t);
1350            }
1351        })
1352    }
1353}
1354
1355impl<T> Clone for RcConditionalMutator<T> {
1356    /// Clones the conditional mutator
1357    ///
1358    /// Creates a new instance that shares the underlying mutator and predicate
1359    /// with the original instance.
1360    fn clone(&self) -> Self {
1361        Self {
1362            mutator: self.mutator.clone(),
1363            predicate: self.predicate.clone(),
1364        }
1365    }
1366}
1367
1368// ============================================================================
1369// 6. ArcMutator - Thread-Safe Shared Ownership Implementation
1370// ============================================================================
1371
1372/// ArcMutator struct
1373///
1374/// A mutator implementation based on `Arc<Mutex<dyn FnMut(&mut T) + Send>>`
1375/// for thread-safe shared ownership scenarios. This type allows the mutator
1376/// to be safely shared and used across multiple threads.
1377///
1378/// # Features
1379///
1380/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1381/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1382/// - **Interior Mutability**: Uses `Mutex` for safe concurrent mutations
1383/// - **Mutable State**: Can modify captured environment via `FnMut`
1384/// - **Chainable**: Method chaining via `&self` (non-consuming)
1385///
1386/// # Use Cases
1387///
1388/// Choose `ArcMutator` when:
1389/// - The mutator needs to be shared across multiple threads
1390/// - Concurrent task processing (e.g., thread pools)
1391/// - Thread safety is required (Send + Sync)
1392///
1393/// # Examples
1394///
1395/// ```rust
1396/// use prism3_function::{Mutator, ArcMutator};
1397///
1398/// let mutator = ArcMutator::new(|x: &mut i32| *x *= 2);
1399/// let clone = mutator.clone();
1400///
1401/// let mut value = 5;
1402/// let mut m = mutator;
1403/// m.mutate(&mut value);
1404/// assert_eq!(value, 10);
1405/// ```
1406///
1407/// # Author
1408///
1409/// Haixing Hu
1410pub struct ArcMutator<T> {
1411    func: ArcMutMutatorFn<T>,
1412}
1413
1414impl<T> ArcMutator<T>
1415where
1416    T: Send + 'static,
1417{
1418    /// Creates a new ArcMutator
1419    ///
1420    /// # Parameters
1421    ///
1422    /// * `f` - The closure to wrap
1423    ///
1424    /// # Returns
1425    ///
1426    /// Returns a new `ArcMutator<T>` instance
1427    ///
1428    /// # Examples
1429    ///
1430    /// ```rust
1431    /// use prism3_function::{Mutator, ArcMutator};
1432    ///
1433    /// let mutator = ArcMutator::new(|x: &mut i32| *x += 1);
1434    /// let mut value = 5;
1435    /// let mut m = mutator;
1436    /// m.mutate(&mut value);
1437    /// assert_eq!(value, 6);
1438    /// ```
1439    pub fn new<F>(f: F) -> Self
1440    where
1441        F: FnMut(&mut T) + Send + 'static,
1442    {
1443        ArcMutator {
1444            func: Arc::new(Mutex::new(f)),
1445        }
1446    }
1447
1448    /// Creates a no-op mutator
1449    ///
1450    /// Returns a mutator that performs no operation.
1451    ///
1452    /// # Returns
1453    ///
1454    /// Returns a no-op mutator
1455    ///
1456    /// # Examples
1457    ///
1458    /// ```rust
1459    /// use prism3_function::{Mutator, ArcMutator};
1460    ///
1461    /// let noop = ArcMutator::<i32>::noop();
1462    /// let mut value = 42;
1463    /// let mut m = noop;
1464    /// m.mutate(&mut value);
1465    /// assert_eq!(value, 42); // Value unchanged
1466    /// ```
1467    pub fn noop() -> Self {
1468        ArcMutator::new(|_| {})
1469    }
1470
1471    /// Chains another ArcMutator in sequence
1472    ///
1473    /// Returns a new mutator that first executes the current operation, then
1474    /// executes the next operation. Borrows &self, does not consume the
1475    /// original mutator.
1476    ///
1477    /// # Parameters
1478    ///
1479    /// * `next` - The mutator to execute after the current operation
1480    ///
1481    /// # Returns
1482    ///
1483    /// Returns a new composed `ArcMutator<T>`
1484    ///
1485    /// # Examples
1486    ///
1487    /// ```rust
1488    /// use prism3_function::{Mutator, ArcMutator};
1489    ///
1490    /// let first = ArcMutator::new(|x: &mut i32| *x *= 2);
1491    /// let second = ArcMutator::new(|x: &mut i32| *x += 10);
1492    ///
1493    /// let chained = first.and_then(&second);
1494    ///
1495    /// // first and second are still usable
1496    /// let mut value = 5;
1497    /// let mut m = chained;
1498    /// m.mutate(&mut value);
1499    /// assert_eq!(value, 20); // (5 * 2) + 10
1500    /// ```
1501    pub fn and_then(&self, next: &ArcMutator<T>) -> ArcMutator<T> {
1502        let first = Arc::clone(&self.func);
1503        let second = Arc::clone(&next.func);
1504        ArcMutator {
1505            func: Arc::new(Mutex::new(move |t: &mut T| {
1506                first.lock().unwrap()(t);
1507                second.lock().unwrap()(t);
1508            })),
1509        }
1510    }
1511
1512    /// Creates a conditional mutator (thread-safe version)
1513    ///
1514    /// Returns a mutator that only executes when a predicate is satisfied.
1515    ///
1516    /// # Parameters
1517    ///
1518    /// * `predicate` - The condition to check. **Note: This parameter is passed
1519    ///   by value and will transfer ownership.** If you need to preserve the
1520    ///   original predicate, clone it first (if it implements `Clone`).
1521    ///   Must be `Send + Sync`, can be:
1522    ///   - A closure: `|x: &T| -> bool` (requires `Send + Sync`)
1523    ///   - A function pointer: `fn(&T) -> bool`
1524    ///   - An `ArcPredicate<T>`
1525    ///   - Any type implementing `Predicate<T> + Send + Sync`
1526    ///
1527    /// # Returns
1528    ///
1529    /// Returns `ArcConditionalMutator<T>`
1530    ///
1531    /// # Examples
1532    ///
1533    /// ```rust
1534    /// use prism3_function::{Mutator, ArcMutator};
1535    ///
1536    /// let mutator = ArcMutator::new(|x: &mut i32| *x *= 2);
1537    /// let conditional = mutator.when(|x: &i32| *x > 0);
1538    ///
1539    /// let conditional_clone = conditional.clone();
1540    ///
1541    /// let mut positive = 5;
1542    /// let mut m = conditional;
1543    /// m.mutate(&mut positive);
1544    /// assert_eq!(positive, 10);
1545    /// ```
1546    pub fn when<P>(self, predicate: P) -> ArcConditionalMutator<T>
1547    where
1548        P: Predicate<T> + Send + Sync + 'static,
1549        T: Send + Sync,
1550    {
1551        ArcConditionalMutator {
1552            mutator: self,
1553            predicate: predicate.into_arc(),
1554        }
1555    }
1556}
1557
1558impl<T> Mutator<T> for ArcMutator<T> {
1559    fn mutate(&mut self, value: &mut T) {
1560        (self.func.lock().unwrap())(value)
1561    }
1562
1563    fn into_box(self) -> BoxMutator<T>
1564    where
1565        T: 'static,
1566    {
1567        let func = self.func;
1568        BoxMutator::new(move |t| func.lock().unwrap()(t))
1569    }
1570
1571    fn into_rc(self) -> RcMutator<T>
1572    where
1573        T: 'static,
1574    {
1575        let func = self.func;
1576        RcMutator::new(move |t| func.lock().unwrap()(t))
1577    }
1578
1579    fn into_arc(self) -> ArcMutator<T>
1580    where
1581        T: Send + 'static,
1582    {
1583        self
1584    }
1585
1586    fn into_fn(self) -> impl FnMut(&mut T)
1587    where
1588        Self: Sized + 'static,
1589        T: 'static,
1590    {
1591        let func = self.func;
1592        move |t: &mut T| func.lock().unwrap()(t)
1593    }
1594}
1595
1596impl<T> Clone for ArcMutator<T> {
1597    /// Clones the ArcMutator
1598    ///
1599    /// Creates a new ArcMutator that shares the underlying function with the
1600    /// original instance.
1601    fn clone(&self) -> Self {
1602        Self {
1603            func: Arc::clone(&self.func),
1604        }
1605    }
1606}
1607
1608// ============================================================================
1609// 7. ArcConditionalMutator - Arc-based Conditional Mutator
1610// ============================================================================
1611
1612/// ArcConditionalMutator struct
1613///
1614/// A thread-safe conditional mutator that only executes when a predicate is
1615/// satisfied. Uses `ArcMutator` and `ArcPredicate` for shared ownership across
1616/// threads.
1617///
1618/// This type is typically created by calling `ArcMutator::when()` and is
1619/// designed to work with the `or_else()` method to create if-then-else logic.
1620///
1621/// # Features
1622///
1623/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1624/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1625/// - **Conditional Execution**: Only mutates when predicate returns `true`
1626/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1627///
1628/// # Examples
1629///
1630/// ```rust
1631/// use prism3_function::{Mutator, ArcMutator};
1632///
1633/// let conditional = ArcMutator::new(|x: &mut i32| *x *= 2)
1634///     .when(|x: &i32| *x > 0);
1635///
1636/// let conditional_clone = conditional.clone();
1637///
1638/// let mut value = 5;
1639/// let mut m = conditional;
1640/// m.mutate(&mut value);
1641/// assert_eq!(value, 10);
1642/// ```
1643///
1644/// # Author
1645///
1646/// Haixing Hu
1647pub struct ArcConditionalMutator<T> {
1648    mutator: ArcMutator<T>,
1649    predicate: ArcPredicate<T>,
1650}
1651impl<T> Mutator<T> for ArcConditionalMutator<T>
1652where
1653    T: Send + 'static,
1654{
1655    fn mutate(&mut self, value: &mut T) {
1656        if self.predicate.test(value) {
1657            self.mutator.mutate(value);
1658        }
1659    }
1660
1661    fn into_box(self) -> BoxMutator<T>
1662    where
1663        T: 'static,
1664    {
1665        let pred = self.predicate;
1666        let mut mutator = self.mutator;
1667        BoxMutator::new(move |t| {
1668            if pred.test(t) {
1669                mutator.mutate(t);
1670            }
1671        })
1672    }
1673
1674    fn into_rc(self) -> RcMutator<T>
1675    where
1676        T: 'static,
1677    {
1678        let pred = self.predicate.to_rc();
1679        let mutator = self.mutator.into_rc();
1680        let pred_fn = pred.to_fn();
1681        let mut mutator_fn = mutator;
1682        RcMutator::new(move |t| {
1683            if pred_fn(t) {
1684                mutator_fn.mutate(t);
1685            }
1686        })
1687    }
1688
1689    fn into_arc(self) -> ArcMutator<T>
1690    where
1691        T: Send + 'static,
1692    {
1693        let pred = self.predicate;
1694        let mut mutator = self.mutator;
1695        ArcMutator::new(move |t| {
1696            if pred.test(t) {
1697                mutator.mutate(t);
1698            }
1699        })
1700    }
1701
1702    fn into_fn(self) -> impl FnMut(&mut T)
1703    where
1704        T: 'static,
1705    {
1706        let pred = self.predicate;
1707        let mut mutator = self.mutator;
1708        move |t: &mut T| {
1709            if pred.test(t) {
1710                mutator.mutate(t);
1711            }
1712        }
1713    }
1714}
1715impl<T> ArcConditionalMutator<T>
1716where
1717    T: Send + 'static,
1718{
1719    /// Adds an else branch (thread-safe version)
1720    ///
1721    /// Executes the original mutator when the condition is satisfied, otherwise
1722    /// executes else_mutator.
1723    ///
1724    /// # Parameters
1725    ///
1726    /// * `else_mutator` - The mutator for the else branch. **Note: This parameter
1727    ///   is passed by value and will transfer ownership.** If you need to preserve
1728    ///   the original mutator, clone it first (if it implements `Clone`).
1729    ///   Must be `Send`, can be:
1730    ///   - A closure: `|x: &mut T|` (must be `Send`)
1731    ///   - An `ArcMutator<T>`
1732    ///   - A `BoxMutator<T>`
1733    ///   - Any type implementing `Mutator<T> + Send`
1734    ///
1735    /// # Returns
1736    ///
1737    /// Returns the composed `ArcMutator<T>`
1738    ///
1739    /// # Examples
1740    ///
1741    /// ## Using a closure (recommended)
1742    ///
1743    /// ```rust
1744    /// use prism3_function::{Mutator, ArcMutator};
1745    ///
1746    /// let mut mutator = ArcMutator::new(|x: &mut i32| *x *= 2)
1747    ///     .when(|x: &i32| *x > 0)
1748    ///     .or_else(|x: &mut i32| *x -= 1);
1749    ///
1750    /// let mut positive = 5;
1751    /// mutator.mutate(&mut positive);
1752    /// assert_eq!(positive, 10);
1753    ///
1754    /// let mut negative = -5;
1755    /// mutator.mutate(&mut negative);
1756    /// assert_eq!(negative, -6);
1757    /// ```
1758    pub fn or_else<C>(self, else_mutator: C) -> ArcMutator<T>
1759    where
1760        C: Mutator<T> + Send + 'static,
1761        T: Send + Sync,
1762    {
1763        let pred = self.predicate;
1764        let mut then_mut = self.mutator;
1765        let mut else_mut = else_mutator;
1766
1767        ArcMutator::new(move |t: &mut T| {
1768            if pred.test(t) {
1769                then_mut.mutate(t);
1770            } else {
1771                else_mut.mutate(t);
1772            }
1773        })
1774    }
1775}
1776
1777impl<T> Clone for ArcConditionalMutator<T> {
1778    /// Clones the conditional mutator
1779    ///
1780    /// Creates a new instance that shares the underlying mutator and predicate
1781    /// with the original instance.
1782    fn clone(&self) -> Self {
1783        Self {
1784            mutator: self.mutator.clone(),
1785            predicate: self.predicate.clone(),
1786        }
1787    }
1788}
1789
1790// ============================================================================
1791// 8. Implement Mutator trait for closures
1792// ============================================================================
1793
1794impl<T, F> Mutator<T> for F
1795where
1796    F: FnMut(&mut T),
1797{
1798    fn mutate(&mut self, value: &mut T) {
1799        self(value)
1800    }
1801
1802    fn into_box(self) -> BoxMutator<T>
1803    where
1804        Self: Sized + 'static,
1805        T: 'static,
1806    {
1807        BoxMutator::new(self)
1808    }
1809
1810    fn into_rc(self) -> RcMutator<T>
1811    where
1812        Self: Sized + 'static,
1813        T: 'static,
1814    {
1815        RcMutator::new(self)
1816    }
1817
1818    fn into_arc(self) -> ArcMutator<T>
1819    where
1820        Self: Sized + Send + 'static,
1821        T: Send + 'static,
1822    {
1823        ArcMutator::new(self)
1824    }
1825
1826    fn into_fn(self) -> impl FnMut(&mut T)
1827    where
1828        Self: Sized + 'static,
1829        T: 'static,
1830    {
1831        self
1832    }
1833}
1834
1835// ============================================================================
1836// 9. Provide extension methods for closures
1837// ============================================================================
1838
1839// ============================================================================
1840// 7. Provide extension methods for closures
1841// ============================================================================
1842
1843/// Extension trait providing mutator composition methods for closures
1844///
1845/// Provides `and_then` and other composition methods for all closures that
1846/// implement `FnMut(&mut T)`, enabling direct method chaining on closures
1847/// without explicit wrapper types.
1848///
1849/// # Features
1850///
1851/// - **Natural Syntax**: Chain operations directly on closures
1852/// - **Returns BoxMutator**: Composition results are `BoxMutator<T>` for
1853///   continued chaining
1854/// - **Zero Cost**: No overhead when composing closures
1855/// - **Automatic Implementation**: All `FnMut(&mut T)` closures get these
1856///   methods automatically
1857///
1858/// # Examples
1859///
1860/// ```rust
1861/// use prism3_function::{Mutator, FnMutatorOps};
1862///
1863/// let chained = (|x: &mut i32| *x *= 2)
1864///     .and_then(|x: &mut i32| *x += 10);
1865/// let mut value = 5;
1866/// let mut result = chained;
1867/// result.mutate(&mut value);
1868/// assert_eq!(value, 20); // (5 * 2) + 10
1869/// ```
1870///
1871/// # Author
1872///
1873/// Haixing Hu
1874pub trait FnMutatorOps<T>: FnMut(&mut T) + Sized {
1875    /// Chains another mutator in sequence
1876    ///
1877    /// Returns a new mutator that first executes the current operation, then
1878    /// executes the next operation. Consumes the current closure and returns
1879    /// `BoxMutator<T>`.
1880    ///
1881    /// # Parameters
1882    ///
1883    /// * `next` - The mutator to execute after the current operation. **Note:
1884    ///   This parameter is passed by value and will transfer ownership.** If you
1885    ///   need to preserve the original mutator, clone it first (if it implements
1886    ///   `Clone`). Can be:
1887    ///   - A closure: `|x: &mut T|`
1888    ///   - A `BoxMutator<T>`
1889    ///   - An `ArcMutator<T>`
1890    ///   - An `RcMutator<T>`
1891    ///   - Any type implementing `Mutator<T>`
1892    ///
1893    /// # Returns
1894    ///
1895    /// Returns the composed `BoxMutator<T>`
1896    ///
1897    /// # Examples
1898    ///
1899    /// ```rust
1900    /// use prism3_function::{Mutator, FnMutatorOps};
1901    ///
1902    /// let chained = (|x: &mut i32| *x *= 2)
1903    ///     .and_then(|x: &mut i32| *x += 10)
1904    ///     .and_then(|x: &mut i32| println!("Result: {}", x));
1905    ///
1906    /// let mut value = 5;
1907    /// let mut result = chained;
1908    /// result.mutate(&mut value); // Prints: Result: 20
1909    /// assert_eq!(value, 20);
1910    /// ```
1911    fn and_then<C>(self, next: C) -> BoxMutator<T>
1912    where
1913        Self: 'static,
1914        C: Mutator<T> + 'static,
1915        T: 'static,
1916    {
1917        let mut first = self;
1918        let mut second = next;
1919        BoxMutator::new(move |t| {
1920            first(t);
1921            second.mutate(t);
1922        })
1923    }
1924}
1925
1926/// Implements FnMutatorOps for all closure types
1927impl<T, F> FnMutatorOps<T> for F where F: FnMut(&mut T) {}