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