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