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