Skip to main content

qubit_function/mutators/
stateful_mutator.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Mutator Types
10//!
11//! Provides Java-like `Mutator` interface implementations for performing
12//! operations that accept a single mutable input parameter and return no result.
13//!
14//! This module provides a unified `Mutator` trait and three concrete
15//! implementations based on different ownership models:
16//!
17//! - **`BoxMutator<T>`**: Box-based single ownership implementation for
18//!   one-time use scenarios and builder patterns
19//! - **`ArcMutator<T>`**: Arc<Mutex<>>-based thread-safe shared ownership
20//!   implementation for multi-threaded scenarios
21//! - **`RcMutator<T>`**: Rc<RefCell<>>-based single-threaded shared
22//!   ownership implementation with no lock overhead
23//!
24//! It is similar to the `FnMut(&mut T)` trait in the standard library.
25//!
26//! # Design Philosophy
27//!
28//! Unlike `Consumer` which observes values without modifying them (`FnMut(&T)`),
29//! `Mutator` is designed to **modify input values** using `FnMut(&mut T)`.
30//!
31//! ## Mutator vs Consumer
32//!
33//! | Type | Input | Modifies Input? | Modifies Self? | Use Cases |
34//! |------|-------|----------------|----------------|-----------|
35//! | **Consumer** | `&T` | ❌ | ✅ | Observe, log, count, notify |
36//! | **Mutator** | `&mut T` | ✅ | ✅ | Modify, transform, update |
37//!
38//! **Key Insight**: If you need to modify input values, use `Mutator`.
39//! If you only need to observe or accumulate state, use `Consumer`.
40//!
41//! # Comparison Table
42//!
43//! | Feature          | BoxMutator | ArcMutator | RcMutator |
44//! |------------------|------------|------------|-----------|
45//! | Ownership        | Single     | Shared     | Shared    |
46//! | Cloneable        | ❌         | ✅         | ✅        |
47//! | Thread-Safe      | ❌         | ✅         | ❌        |
48//! | Interior Mut.    | N/A        | Mutex      | RefCell   |
49//! | `and_then` API   | `self`     | `&self`    | `&self`   |
50//! | Lock Overhead    | None       | Yes        | None      |
51//!
52//! # Use Cases
53//!
54//! ## BoxMutator
55//!
56//! - One-time operations that don't require sharing
57//! - Builder patterns where ownership naturally flows
58//! - Simple scenarios with no reuse requirements
59//!
60//! ## ArcMutator
61//!
62//! - Multi-threaded shared operations
63//! - Concurrent task processing (e.g., thread pools)
64//! - Situations requiring the same mutator across threads
65//!
66//! ## RcMutator
67//!
68//! - Single-threaded operations with multiple uses
69//! - Event handling in single-threaded UI frameworks
70//! - Performance-critical single-threaded scenarios
71//!
72//! # Examples
73//!
74//! ## Basic Usage
75//!
76//! ```rust
77//! use qubit_function::{BoxMutator, ArcMutator, RcMutator, Mutator};
78//!
79//! // BoxMutator: Single ownership, consumes self
80//! let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
81//! let mut value = 5;
82//! mutator.apply(&mut value);
83//! assert_eq!(value, 10);
84//!
85//! // ArcMutator: Shared ownership, cloneable, thread-safe
86//! let shared = ArcMutator::new(|x: &mut i32| *x *= 2);
87//! let clone = shared.clone();
88//! let mut value = 5;
89//! let mut m = shared;
90//! m.apply(&mut value);
91//! assert_eq!(value, 10);
92//!
93//! // RcMutator: Shared ownership, cloneable, single-threaded
94//! let rc = RcMutator::new(|x: &mut i32| *x *= 2);
95//! let clone = rc.clone();
96//! let mut value = 5;
97//! let mut m = rc;
98//! m.apply(&mut value);
99//! assert_eq!(value, 10);
100//! ```
101//!
102//! ## Method Chaining
103//!
104//! ```rust
105//! use qubit_function::{Mutator, BoxMutator, ArcMutator};
106//!
107//! // BoxMutator: Consumes self
108//! let mut chained = BoxMutator::new(|x: &mut i32| *x *= 2)
109//!     .and_then(|x: &mut i32| *x += 10);
110//! let mut value = 5;
111//! chained.apply(&mut value);
112//! assert_eq!(value, 20); // (5 * 2) + 10
113//!
114//! // ArcMutator: Borrows &self, original still usable
115//! let first = ArcMutator::new(|x: &mut i32| *x *= 2);
116//! let second = ArcMutator::new(|x: &mut i32| *x += 10);
117//! let combined = first.clone().and_then(second.clone());
118//! let mut value = 5;
119//! combined.apply(&mut value);
120//! assert_eq!(value, 20);
121//! // first and second are still usable here
122//! ```
123//!
124//! ## Working with Closures
125//!
126//! All closures automatically implement the `Mutator` trait:
127//!
128//! ```rust
129//! use qubit_function::{Mutator, FnMutatorOps};
130//!
131//! // Closures can use .apply() directly
132//! let mut closure = |x: &mut i32| *x *= 2;
133//! let mut value = 5;
134//! closure.apply(&mut value);
135//! assert_eq!(value, 10);
136//!
137//! // Closures can be chained, returning BoxMutator
138//! let mut chained = (|x: &mut i32| *x *= 2)
139//!     .and_then(|x: &mut i32| *x += 10);
140//! let mut value = 5;
141//! chained.apply(&mut value);
142//! assert_eq!(value, 20);
143//! ```
144//!
145//! ## Type Conversions
146//!
147//! ```rust
148//! use qubit_function::Mutator;
149//!
150//! // Convert closure to concrete type
151//! let closure = |x: &mut i32| *x *= 2;
152//! let mut box_mutator = closure.into_box();
153//!
154//! let closure = |x: &mut i32| *x *= 2;
155//! let mut rc_mutator = closure.into_rc();
156//!
157//! let closure = |x: &mut i32| *x *= 2;
158//! let mut arc_mutator = closure.into_arc();
159//! ```
160//!
161//! ## Conditional Execution
162//!
163//! All mutator types support conditional execution through the `when` method,
164//! which returns a `ConditionalMutator`. You can optionally add an `or_else`
165//! branch to create if-then-else logic:
166//!
167//! ```rust
168//! use qubit_function::{Mutator, BoxMutator};
169//!
170//! // Simple conditional (if-then)
171//! let mut conditional = BoxMutator::new(|x: &mut i32| *x *= 2)
172//!     .when(|x: &i32| *x > 0);
173//!
174//! let mut positive = 5;
175//! conditional.apply(&mut positive);
176//! assert_eq!(positive, 10); // Executed
177//!
178//! let mut negative = -5;
179//! conditional.apply(&mut negative);
180//! assert_eq!(negative, -5); // Not executed
181//!
182//! // Conditional with else branch (if-then-else)
183//! let mut branched = BoxMutator::new(|x: &mut i32| *x *= 2)
184//!     .when(|x: &i32| *x > 0)
185//!     .or_else(|x: &mut i32| *x -= 1);
186//!
187//! let mut positive = 5;
188//! branched.apply(&mut positive);
189//! assert_eq!(positive, 10); // when branch
190//!
191//! let mut negative = -5;
192//! branched.apply(&mut negative);
193//! assert_eq!(negative, -6); // or_else branch
194//! ```
195//!
196//! # Author
197//!
198//! Haixing Hu
199use std::cell::RefCell;
200use std::rc::Rc;
201use std::sync::Arc;
202
203use parking_lot::Mutex;
204
205use crate::macros::{
206    impl_arc_conversions,
207    impl_box_conversions,
208    impl_closure_trait,
209    impl_rc_conversions,
210};
211use crate::mutators::{
212    macros::{
213        impl_box_conditional_mutator,
214        impl_box_mutator_methods,
215        impl_conditional_mutator_clone,
216        impl_conditional_mutator_conversions,
217        impl_conditional_mutator_debug_display,
218        impl_mutator_clone,
219        impl_mutator_common_methods,
220        impl_mutator_debug_display,
221        impl_shared_conditional_mutator,
222        impl_shared_mutator_methods,
223    },
224    mutator_once::BoxMutatorOnce,
225};
226use crate::predicates::predicate::{
227    ArcPredicate,
228    BoxPredicate,
229    Predicate,
230    RcPredicate,
231};
232
233// ============================================================================
234// 1. Type Aliases
235// ============================================================================
236
237/// Type alias for Arc-wrapped mutable mutator function
238type ArcMutMutatorFn<T> = Arc<Mutex<dyn FnMut(&mut T) + Send>>;
239
240/// Type alias for Rc-wrapped mutable mutator function
241type RcMutMutatorFn<T> = Rc<RefCell<dyn FnMut(&mut T)>>;
242
243mod box_stateful_mutator;
244pub use box_stateful_mutator::BoxStatefulMutator;
245mod rc_stateful_mutator;
246pub use rc_stateful_mutator::RcStatefulMutator;
247mod arc_stateful_mutator;
248pub use arc_stateful_mutator::ArcStatefulMutator;
249mod fn_mut_stateful_mutator_ops;
250pub use fn_mut_stateful_mutator_ops::FnMutStatefulMutatorOps;
251mod box_conditional_stateful_mutator;
252pub use box_conditional_stateful_mutator::BoxConditionalStatefulMutator;
253mod rc_conditional_stateful_mutator;
254pub use rc_conditional_stateful_mutator::RcConditionalStatefulMutator;
255mod arc_conditional_stateful_mutator;
256pub use arc_conditional_stateful_mutator::ArcConditionalStatefulMutator;
257
258// ============================================================================
259// 2. Mutator Trait - Unified Mutator Interface
260// ============================================================================
261
262/// Mutator trait - Unified mutator interface
263///
264/// Defines the core behavior of all mutator types. Performs operations that
265/// accept a mutable reference and modify the input value (not just side effects).
266///
267/// This trait is automatically implemented by:
268/// - All closures implementing `FnMut(&mut T)`
269/// - `BoxMutator<T>`, `ArcMutator<T>`, and `RcMutator<T>`
270///
271/// # Design Rationale
272///
273/// The trait provides a unified abstraction over different ownership models,
274/// allowing generic code to work with any mutator type. Type conversion
275/// methods (`into_box`, `into_arc`, `into_rc`) enable flexible ownership
276/// transitions based on usage requirements.
277///
278/// # Features
279///
280/// - **Unified Interface**: All mutator types share the same `mutate`
281///   method signature
282/// - **Automatic Implementation**: Closures automatically implement this
283///   trait with zero overhead
284/// - **Type Conversions**: Easy conversion between ownership models
285/// - **Generic Programming**: Write functions that work with any mutator
286///   type
287///
288/// # Examples
289///
290/// ## Generic Mutator Function
291///
292/// ```rust
293/// use qubit_function::{Mutator, BoxMutator, ArcMutator};
294///
295/// fn apply_mutator<M: Mutator<i32>>(
296///     mutator: &mut M,
297///     value: i32
298/// ) -> i32 {
299///     let mut val = value;
300///     mutator.apply(&mut val);
301///     val
302/// }
303///
304/// // Works with any mutator type
305/// let mut box_mut = BoxMutator::new(|x: &mut i32| *x *= 2);
306/// assert_eq!(apply_mutator(&mut box_mut, 5), 10);
307///
308/// let mut arc_mut = ArcMutator::new(|x: &mut i32| *x *= 2);
309/// assert_eq!(apply_mutator(&mut arc_mut, 5), 10);
310///
311/// let mut closure = |x: &mut i32| *x *= 2;
312/// assert_eq!(apply_mutator(&mut closure, 5), 10);
313/// ```
314///
315/// ## Type Conversion
316///
317/// ```rust
318/// use qubit_function::Mutator;
319///
320/// let closure = |x: &mut i32| *x *= 2;
321///
322/// // Convert to different ownership models
323/// let box_mutator = closure.into_box();
324/// // let rc_mutator = closure.into_rc();  // closure moved
325/// // let arc_mutator = closure.into_arc(); // closure moved
326/// ```
327///
328/// # Author
329///
330/// Haixing Hu
331pub trait StatefulMutator<T> {
332    /// Performs the mutation operation
333    ///
334    /// Executes an operation on the given mutable reference. The operation
335    /// typically modifies the input value or produces side effects.
336    ///
337    /// # Parameters
338    ///
339    /// * `value` - A mutable reference to the value to be mutated
340    ///
341    /// # Examples
342    ///
343    /// ```rust
344    /// use qubit_function::{Mutator, BoxMutator};
345    ///
346    /// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
347    /// let mut value = 5;
348    /// mutator.apply(&mut value);
349    /// assert_eq!(value, 10);
350    /// ```
351    fn apply(&mut self, value: &mut T);
352
353    /// Convert this mutator into a `BoxMutator<T>`.
354    ///
355    /// This consuming conversion takes ownership of `self` and returns a
356    /// boxed implementation that forwards calls to the original mutator.
357    /// Types that can provide a more efficient conversion may override the
358    /// default implementation.
359    ///
360    /// # Consumption
361    ///
362    /// This method consumes the mutator: the original value will no longer
363    /// be available after the call. For cloneable mutators call `.clone()`
364    /// before converting if you need to retain the original instance.
365    ///
366    /// # Returns
367    ///
368    /// A `BoxMutator<T>` that forwards to the original mutator.
369    ///
370    /// # Examples
371    ///
372    /// ```rust
373    /// use qubit_function::Mutator;
374    ///
375    /// let closure = |x: &mut i32| *x *= 2;
376    /// let mut boxed = closure.into_box();
377    /// let mut value = 5;
378    /// boxed.apply(&mut value);
379    /// assert_eq!(value, 10);
380    /// ```
381    fn into_box(mut self) -> BoxStatefulMutator<T>
382    where
383        Self: Sized + 'static,
384    {
385        BoxStatefulMutator::new(move |t| self.apply(t))
386    }
387
388    /// Convert this mutator into an `RcMutator<T>`.
389    ///
390    /// This consuming conversion takes ownership of `self` and returns an
391    /// `Rc`-backed mutator that forwards calls to the original. Override to
392    /// provide a more direct or efficient conversion when available.
393    ///
394    /// # Consumption
395    ///
396    /// This method consumes the mutator. If you need to keep the original
397    /// instance, clone it prior to calling this method.
398    ///
399    /// # Returns
400    ///
401    /// An `RcMutator<T>` forwarding to the original mutator.
402    ///
403    /// # Examples
404    ///
405    /// ```rust
406    /// use qubit_function::Mutator;
407    ///
408    /// let closure = |x: &mut i32| *x *= 2;
409    /// let mut rc = closure.into_rc();
410    /// let mut value = 5;
411    /// rc.apply(&mut value);
412    /// assert_eq!(value, 10);
413    /// ```
414    fn into_rc(mut self) -> RcStatefulMutator<T>
415    where
416        Self: Sized + 'static,
417    {
418        RcStatefulMutator::new(move |t| self.apply(t))
419    }
420
421    /// Convert this mutator into an `ArcMutator<T>`.
422    ///
423    /// This consuming conversion takes ownership of `self` and returns an
424    /// `Arc`-wrapped, thread-safe mutator. Types may override the default
425    /// implementation to provide a more efficient conversion.
426    ///
427    /// # Consumption
428    ///
429    /// This method consumes the mutator. Clone the instance first if you
430    /// need to retain the original for further use.
431    ///
432    /// # Returns
433    ///
434    /// An `ArcMutator<T>` that forwards to the original mutator.
435    ///
436    /// # Examples
437    ///
438    /// ```rust
439    /// use qubit_function::Mutator;
440    ///
441    /// let closure = |x: &mut i32| *x *= 2;
442    /// let mut arc = closure.into_arc();
443    /// let mut value = 5;
444    /// arc.apply(&mut value);
445    /// assert_eq!(value, 10);
446    /// ```
447    fn into_arc(mut self) -> ArcStatefulMutator<T>
448    where
449        Self: Sized + Send + 'static,
450    {
451        ArcStatefulMutator::new(move |t| self.apply(t))
452    }
453
454    /// Consume the mutator and return an `FnMut(&mut T)` closure.
455    ///
456    /// The returned closure forwards calls to the original mutator and is
457    /// suitable for use with iterator adapters such as `for_each`.
458    ///
459    /// # Consumption
460    ///
461    /// This method consumes the mutator. The original instance will not be
462    /// available after calling this method.
463    ///
464    /// # Returns
465    ///
466    /// A closure implementing `FnMut(&mut T)` which forwards to the
467    /// original mutator.
468    ///
469    /// # Examples
470    ///
471    /// ```rust
472    /// use qubit_function::{Mutator, BoxMutator};
473    ///
474    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
475    /// let mut values = vec![1, 2, 3, 4, 5];
476    /// values.iter_mut().for_each(mutator.into_fn());
477    /// assert_eq!(values, vec![2, 4, 6, 8, 10]);
478    /// ```
479    fn into_fn(mut self) -> impl FnMut(&mut T)
480    where
481        Self: Sized + 'static,
482    {
483        move |t| self.apply(t)
484    }
485
486    /// Create a non-consuming `BoxMutator<T>` that forwards to `self`.
487    ///
488    /// The default implementation clones `self` (requires `Clone`) and
489    /// returns a boxed mutator that calls the cloned instance. Override this
490    /// method if a more efficient conversion exists.
491    ///
492    /// # Returns
493    ///
494    /// A `BoxMutator<T>` that forwards to a clone of `self`.
495    fn to_box(&self) -> BoxStatefulMutator<T>
496    where
497        Self: Sized + Clone + 'static,
498    {
499        self.clone().into_box()
500    }
501
502    /// Create a non-consuming `RcMutator<T>` that forwards to `self`.
503    ///
504    /// The default implementation clones `self` (requires `Clone`) and
505    /// returns an `Rc`-backed mutator that forwards calls to the clone.
506    /// Override to provide a more direct or efficient conversion if needed.
507    ///
508    /// # Returns
509    ///
510    /// An `RcMutator<T>` that forwards to a clone of `self`.
511    fn to_rc(&self) -> RcStatefulMutator<T>
512    where
513        Self: Sized + Clone + 'static,
514    {
515        self.clone().into_rc()
516    }
517
518    /// Create a non-consuming `ArcMutator<T>` that forwards to `self`.
519    ///
520    /// The default implementation clones `self` (requires `Clone + Send`) and
521    /// returns an `Arc`-wrapped mutator that forwards calls to the clone.
522    /// Override when a more efficient conversion is available.
523    ///
524    /// # Returns
525    ///
526    /// An `ArcMutator<T>` that forwards to a clone of `self`.
527    fn to_arc(&self) -> ArcStatefulMutator<T>
528    where
529        Self: Sized + Clone + Send + 'static,
530    {
531        self.clone().into_arc()
532    }
533
534    /// Create a boxed `FnMut(&mut T)` closure that forwards to `self`.
535    ///
536    /// The default implementation clones `self` (requires `Clone`) and
537    /// returns a boxed closure that invokes the cloned instance. Override to
538    /// provide a more efficient conversion when possible.
539    ///
540    /// # Returns
541    ///
542    /// A closure implementing `FnMut(&mut T)` which forwards to the
543    /// original mutator.
544    fn to_fn(&self) -> impl FnMut(&mut T)
545    where
546        Self: Sized + Clone + 'static,
547    {
548        self.clone().into_fn()
549    }
550
551    /// Convert this mutator into a `BoxMutatorOnce<T>` (consuming).
552    ///
553    /// This consuming conversion takes ownership of `self` and returns a
554    /// boxed one-time mutator that forwards calls to the original mutator.
555    /// The returned mutator can only be used once.
556    ///
557    /// # Consumption
558    ///
559    /// This method consumes the mutator: the original value will no longer
560    /// be available after the call. For cloneable mutators call `.clone()`
561    /// before converting if you need to retain the original instance.
562    ///
563    /// # Returns
564    ///
565    /// A `BoxMutatorOnce<T>` that forwards to the original mutator.
566    ///
567    /// # Examples
568    ///
569    /// ```rust
570    /// use qubit_function::{StatefulMutator, MutatorOnce, BoxStatefulMutator,
571    ///                       BoxMutatorOnce};
572    ///
573    /// let mutator = BoxStatefulMutator::new(|x: &mut i32| *x *= 2);
574    /// let once_mutator = mutator.into_once();
575    /// let mut value = 5;
576    /// once_mutator.apply(&mut value);
577    /// assert_eq!(value, 10);
578    /// ```
579    fn into_once(mut self) -> BoxMutatorOnce<T>
580    where
581        Self: Sized + 'static,
582    {
583        BoxMutatorOnce::new(move |t| self.apply(t))
584    }
585
586    /// Create a non-consuming `BoxMutatorOnce<T>` that forwards to `self`.
587    ///
588    /// The default implementation clones `self` (requires `Clone`) and
589    /// returns a boxed one-time mutator that calls the cloned instance.
590    /// Override this method if a more efficient conversion exists.
591    ///
592    /// # Returns
593    ///
594    /// A `BoxMutatorOnce<T>` that forwards to a clone of `self`.
595    fn to_once(&self) -> BoxMutatorOnce<T>
596    where
597        Self: Sized + Clone + 'static,
598    {
599        self.clone().into_once()
600    }
601}