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