Skip to main content

qubit_function/mutators/
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 (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 qubit_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 qubit_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.clone().and_then(second.clone());
122//! let mut value = 5;
123//! combined.apply(&mut value);
124//! assert_eq!(value, 20); // (5 * 2) + 10
125//! // first and second are still usable here
126//! ```
127//!
128//! ## Working with Closures
129//!
130//! All closures automatically implement the `Mutator` trait:
131//!
132//! ```rust
133//! use qubit_function::{Mutator, FnMutatorOps};
134//!
135//! // Closures can use .apply() directly
136//! let mut closure = |x: &mut i32| *x *= 2;
137//! let mut value = 5;
138//! closure.apply(&mut value);
139//! assert_eq!(value, 10);
140//!
141//! // Closures can be chained, returning BoxMutator
142//! let mut chained = (|x: &mut i32| *x *= 2)
143//!     .and_then(|x: &mut i32| *x += 10);
144//! let mut value = 5;
145//! chained.apply(&mut value);
146//! assert_eq!(value, 20);
147//! ```
148//!
149//! ## Type Conversions
150//!
151//! ```rust
152//! use qubit_function::Mutator;
153//!
154//! // Convert closure to concrete type
155//! let closure = |x: &mut i32| *x *= 2;
156//! let mut box_mutator = closure.into_box();
157//!
158//! let closure = |x: &mut i32| *x *= 2;
159//! let mut rc_mutator = closure.into_rc();
160//!
161//! let closure = |x: &mut i32| *x *= 2;
162//! let mut arc_mutator = closure.into_arc();
163//! ```
164//!
165//! ## Conditional Execution
166//!
167//! All mutator types support conditional execution through the `when` method,
168//! which returns a `ConditionalMutator`. You can optionally add an `or_else`
169//! branch to create if-then-else logic:
170//!
171//! ```rust
172//! use qubit_function::{Mutator, BoxMutator};
173//!
174//! // Simple conditional (if-then)
175//! let mut conditional = BoxMutator::new(|x: &mut i32| *x *= 2)
176//!     .when(|x: &i32| *x > 0);
177//!
178//! let mut positive = 5;
179//! conditional.apply(&mut positive);
180//! assert_eq!(positive, 10); // Executed
181//!
182//! let mut negative = -5;
183//! conditional.apply(&mut negative);
184//! assert_eq!(negative, -5); // Not executed
185//!
186//! // Conditional with else branch (if-then-else)
187//! let mut branched = BoxMutator::new(|x: &mut i32| *x *= 2)
188//!     .when(|x: &i32| *x > 0)
189//!     .or_else(|x: &mut i32| *x -= 1);
190//!
191//! let mut positive = 5;
192//! branched.apply(&mut positive);
193//! assert_eq!(positive, 10); // when branch
194//!
195//! let mut negative = -5;
196//! branched.apply(&mut negative);
197//! assert_eq!(negative, -6); // or_else branch
198//! ```
199//!
200//! # Author
201//!
202//! Haixing Hu
203use std::rc::Rc;
204use std::sync::Arc;
205
206use crate::macros::{
207    impl_arc_conversions,
208    impl_box_conversions,
209    impl_closure_trait,
210    impl_rc_conversions,
211};
212use crate::mutators::{
213    macros::{
214        impl_box_conditional_mutator,
215        impl_box_mutator_methods,
216        impl_conditional_mutator_clone,
217        impl_conditional_mutator_conversions,
218        impl_conditional_mutator_debug_display,
219        impl_mutator_clone,
220        impl_mutator_common_methods,
221        impl_mutator_debug_display,
222        impl_shared_conditional_mutator,
223        impl_shared_mutator_methods,
224    },
225    mutator_once::BoxMutatorOnce,
226};
227use crate::predicates::predicate::{
228    ArcPredicate,
229    BoxPredicate,
230    Predicate,
231    RcPredicate,
232};
233
234// ============================================================================
235// 1. Type Aliases
236// ============================================================================
237
238/// Type alias for Arc-wrapped stateless mutator function
239type ArcMutatorFn<T> = Arc<dyn Fn(&mut T) + Send + Sync>;
240
241/// Type alias for Rc-wrapped stateless mutator function
242type RcMutatorFn<T> = Rc<dyn Fn(&mut T)>;
243
244mod box_mutator;
245pub use box_mutator::BoxMutator;
246mod rc_mutator;
247pub use rc_mutator::RcMutator;
248mod arc_mutator;
249pub use arc_mutator::ArcMutator;
250mod fn_mutator_ops;
251pub use fn_mutator_ops::FnMutatorOps;
252mod box_conditional_mutator;
253pub use box_conditional_mutator::BoxConditionalMutator;
254mod rc_conditional_mutator;
255pub use rc_conditional_mutator::RcConditionalMutator;
256mod arc_conditional_mutator;
257pub use arc_conditional_mutator::ArcConditionalMutator;
258
259// ============================================================================
260// 2. Mutator Trait - Unified Mutator Interface
261// ============================================================================
262
263/// Mutator trait - Unified stateless mutator interface
264///
265/// Defines the core behavior of all stateless mutator types. Performs operations
266/// that accept a mutable reference and modify the input value without maintaining
267/// internal state.
268///
269/// This trait is automatically implemented by:
270/// - All closures implementing `Fn(&mut T)` (stateless)
271/// - `BoxMutator<T>`, `ArcMutator<T>`, and `RcMutator<T>`
272///
273/// # Design Rationale
274///
275/// The trait provides a unified abstraction over different ownership models for
276/// **stateless** operations. Unlike `StatefulMutator` which uses `FnMut` and can
277/// modify its internal state, `Mutator` uses `Fn` for pure transformations.
278///
279/// # Features
280///
281/// - **Stateless Operations**: No internal state modification (`&self` not `&mut self`)
282/// - **Unified Interface**: All mutator types share the same `mutate` method signature
283/// - **Automatic Implementation**: Closures automatically implement this trait
284/// - **Type Conversions**: Easy conversion between ownership models
285/// - **Generic Programming**: Write functions that work with any mutator type
286///
287/// # Examples
288///
289/// ## Generic Mutator Function
290///
291/// ```rust
292/// use qubit_function::{Mutator, BoxMutator, ArcMutator};
293///
294/// fn apply_mutator<M: Mutator<i32>>(
295///     mutator: &mut M,
296///     value: i32
297/// ) -> i32 {
298///     let mut val = value;
299///     mutator.apply(&mut val);
300///     val
301/// }
302///
303/// // Works with any mutator type
304/// let mut box_mut = BoxMutator::new(|x: &mut i32| *x *= 2);
305/// assert_eq!(apply_mutator(&mut box_mut, 5), 10);
306///
307/// let mut arc_mut = ArcMutator::new(|x: &mut i32| *x *= 2);
308/// assert_eq!(apply_mutator(&mut arc_mut, 5), 10);
309///
310/// let mut closure = |x: &mut i32| *x *= 2;
311/// assert_eq!(apply_mutator(&mut closure, 5), 10);
312/// ```
313///
314/// ## Type Conversion
315///
316/// ```rust
317/// use qubit_function::Mutator;
318///
319/// let closure = |x: &mut i32| *x *= 2;
320///
321/// // Convert to different ownership models
322/// let box_mutator = closure.into_box();
323/// // let rc_mutator = closure.into_rc();  // closure moved
324/// // let arc_mutator = closure.into_arc(); // closure moved
325/// ```
326///
327/// # Author
328///
329/// Haixing Hu
330pub trait Mutator<T> {
331    /// Performs the stateless mutation operation
332    ///
333    /// Executes an operation on the given mutable reference without modifying
334    /// the mutator's internal state. This is a pure transformation operation.
335    ///
336    /// # Parameters
337    ///
338    /// * `value` - A mutable reference to the value to be mutated
339    ///
340    /// # Examples
341    ///
342    /// ```rust
343    /// use qubit_function::{Mutator, BoxMutator};
344    ///
345    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
346    /// let mut value = 5;
347    /// mutator.apply(&mut value);
348    /// assert_eq!(value, 10);
349    /// ```
350    fn apply(&self, value: &mut T);
351
352    /// Convert this mutator into a `BoxMutator<T>`.
353    ///
354    /// This consuming conversion takes ownership of `self` and returns a
355    /// boxed implementation that forwards calls to the original mutator.
356    /// Types that can provide a more efficient conversion may override the
357    /// default implementation.
358    ///
359    /// # Consumption
360    ///
361    /// This method consumes the mutator: the original value will no longer
362    /// be available after the call. For cloneable mutators call `.clone()`
363    /// before converting if you need to retain the original instance.
364    ///
365    /// # Returns
366    ///
367    /// A `BoxMutator<T>` that forwards to the original mutator.
368    ///
369    /// # Examples
370    ///
371    /// ```rust
372    /// use qubit_function::Mutator;
373    ///
374    /// let closure = |x: &mut i32| *x *= 2;
375    /// let mut boxed = closure.into_box();
376    /// let mut value = 5;
377    /// boxed.apply(&mut value);
378    /// assert_eq!(value, 10);
379    /// ```
380    fn into_box(self) -> BoxMutator<T>
381    where
382        Self: Sized + 'static,
383    {
384        BoxMutator::new(move |t| self.apply(t))
385    }
386
387    /// Convert this mutator into an `RcMutator<T>`.
388    ///
389    /// This consuming conversion takes ownership of `self` and returns an
390    /// `Rc`-backed mutator that forwards calls to the original. Override to
391    /// provide a more direct or efficient conversion when available.
392    ///
393    /// # Consumption
394    ///
395    /// This method consumes the mutator. If you need to keep the original
396    /// instance, clone it prior to calling this method.
397    ///
398    /// # Returns
399    ///
400    /// An `RcMutator<T>` forwarding to the original mutator.
401    ///
402    /// # Examples
403    ///
404    /// ```rust
405    /// use qubit_function::Mutator;
406    ///
407    /// let closure = |x: &mut i32| *x *= 2;
408    /// let mut rc = closure.into_rc();
409    /// let mut value = 5;
410    /// rc.apply(&mut value);
411    /// assert_eq!(value, 10);
412    /// ```
413    fn into_rc(self) -> RcMutator<T>
414    where
415        Self: Sized + 'static,
416    {
417        RcMutator::new(move |t| self.apply(t))
418    }
419
420    /// Convert this mutator into an `ArcMutator<T>`.
421    ///
422    /// This consuming conversion takes ownership of `self` and returns an
423    /// `Arc`-wrapped, thread-safe mutator. Types may override the default
424    /// implementation to provide a more efficient conversion.
425    ///
426    /// # Consumption
427    ///
428    /// This method consumes the mutator. Clone the instance first if you
429    /// need to retain the original for further use.
430    ///
431    /// # Returns
432    ///
433    /// An `ArcMutator<T>` that forwards to the original mutator.
434    ///
435    /// # Examples
436    ///
437    /// ```rust
438    /// use qubit_function::Mutator;
439    ///
440    /// let closure = |x: &mut i32| *x *= 2;
441    /// let mut arc = closure.into_arc();
442    /// let mut value = 5;
443    /// arc.apply(&mut value);
444    /// assert_eq!(value, 10);
445    /// ```
446    fn into_arc(self) -> ArcMutator<T>
447    where
448        Self: Sized + Send + Sync + 'static,
449    {
450        ArcMutator::new(move |t| self.apply(t))
451    }
452
453    /// Consume the mutator and return an `Fn(&mut T)` closure.
454    ///
455    /// The returned closure forwards calls to the original mutator and is
456    /// suitable for use with iterator adapters such as `for_each`.
457    ///
458    /// # Consumption
459    ///
460    /// This method consumes the mutator. The original instance will not be
461    /// available after calling this method.
462    ///
463    /// # Returns
464    ///
465    /// A closure implementing `Fn(&mut T)` which forwards to the
466    /// original mutator.
467    ///
468    /// # Examples
469    ///
470    /// ```rust
471    /// use qubit_function::{Mutator, BoxMutator};
472    ///
473    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
474    /// let mut values = vec![1, 2, 3, 4, 5];
475    /// values.iter_mut().for_each(mutator.into_fn());
476    /// assert_eq!(values, vec![2, 4, 6, 8, 10]);
477    /// ```
478    fn into_fn(self) -> impl Fn(&mut T)
479    where
480        Self: Sized + 'static,
481    {
482        move |t| self.apply(t)
483    }
484
485    /// Convert this mutator into a `BoxMutatorOnce<T>` (consuming).
486    ///
487    /// This consuming conversion takes ownership of `self` and returns a
488    /// boxed one-time mutator that forwards calls to the original mutator.
489    /// The returned mutator can only be used once.
490    ///
491    /// # Consumption
492    ///
493    /// This method consumes the mutator: the original value will no longer
494    /// be available after the call. For cloneable mutators call `.clone()`
495    /// before converting if you need to retain the original instance.
496    ///
497    /// # Returns
498    ///
499    /// A `BoxMutatorOnce<T>` that forwards to the original mutator.
500    ///
501    /// # Examples
502    ///
503    /// ```rust
504    /// use qubit_function::{Mutator, MutatorOnce, BoxMutator, BoxMutatorOnce};
505    ///
506    /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
507    /// let once_mutator = mutator.into_once();
508    /// let mut value = 5;
509    /// once_mutator.apply(&mut value);
510    /// assert_eq!(value, 10);
511    /// ```
512    fn into_once(self) -> BoxMutatorOnce<T>
513    where
514        Self: Sized + 'static,
515    {
516        BoxMutatorOnce::new(move |t| self.apply(t))
517    }
518
519    /// Create a non-consuming `BoxMutator<T>` that forwards to `self`.
520    ///
521    /// The default implementation clones `self` (requires `Clone`) and
522    /// returns a boxed mutator that calls the cloned instance. Override this
523    /// method if a more efficient conversion exists.
524    ///
525    /// # Returns
526    ///
527    /// A `BoxMutator<T>` that forwards to a clone of `self`.
528    fn to_box(&self) -> BoxMutator<T>
529    where
530        Self: Sized + Clone + 'static,
531    {
532        self.clone().into_box()
533    }
534
535    /// Create a non-consuming `RcMutator<T>` that forwards to `self`.
536    ///
537    /// The default implementation clones `self` (requires `Clone`) and
538    /// returns an `Rc`-backed mutator that forwards calls to the clone.
539    /// Override to provide a more direct or efficient conversion if needed.
540    ///
541    /// # Returns
542    ///
543    /// An `RcMutator<T>` that forwards to a clone of `self`.
544    fn to_rc(&self) -> RcMutator<T>
545    where
546        Self: Sized + Clone + 'static,
547    {
548        self.clone().into_rc()
549    }
550
551    /// Create a non-consuming `ArcMutator<T>` that forwards to `self`.
552    ///
553    /// The default implementation clones `self` (requires `Clone + Send + Sync`) and
554    /// returns an `Arc`-wrapped mutator that forwards calls to the clone.
555    /// Override when a more efficient conversion is available.
556    ///
557    /// # Returns
558    ///
559    /// An `ArcMutator<T>` that forwards to a clone of `self`.
560    fn to_arc(&self) -> ArcMutator<T>
561    where
562        Self: Sized + Clone + Send + Sync + 'static,
563    {
564        self.clone().into_arc()
565    }
566
567    /// Create a boxed `Fn(&mut T)` closure that forwards to `self`.
568    ///
569    /// The default implementation clones `self` (requires `Clone`) and
570    /// returns a boxed closure that invokes the cloned instance. Override to
571    /// provide a more efficient conversion when possible.
572    ///
573    /// # Returns
574    ///
575    /// A closure implementing `Fn(&mut T)` which forwards to the
576    /// original mutator.
577    fn to_fn(&self) -> impl Fn(&mut T)
578    where
579        Self: Sized + Clone + 'static,
580    {
581        self.clone().into_fn()
582    }
583
584    /// Create a non-consuming `BoxMutatorOnce<T>` that forwards to `self`.
585    ///
586    /// The default implementation clones `self` (requires `Clone`) and
587    /// returns a boxed one-time mutator that calls the cloned instance.
588    /// Override this method if a more efficient conversion exists.
589    ///
590    /// # Returns
591    ///
592    /// A `BoxMutatorOnce<T>` that forwards to a clone of `self`.
593    fn to_once(&self) -> BoxMutatorOnce<T>
594    where
595        Self: Sized + Clone + 'static,
596    {
597        self.clone().into_once()
598    }
599}