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