prism3_function/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//! # Design Philosophy
25//!
26//! Unlike `Consumer` which observes values without modifying them (`FnMut(&T)`),
27//! `Mutator` is designed to **modify input values** using `FnMut(&mut T)`.
28//!
29//! ## Mutator vs Consumer
30//!
31//! | Type | Input | Modifies Input? | Modifies Self? | Use Cases |
32//! |------|-------|----------------|----------------|-----------|
33//! | **Consumer** | `&T` | ❌ | ✅ | Observe, log, count, notify |
34//! | **Mutator** | `&mut T` | ✅ | ✅ | Modify, transform, update |
35//!
36//! **Key Insight**: If you need to modify input values, use `Mutator`.
37//! If you only need to observe or accumulate state, use `Consumer`.
38//!
39//! # Comparison Table
40//!
41//! | Feature | BoxMutator | ArcMutator | RcMutator |
42//! |------------------|------------|------------|-----------|
43//! | Ownership | Single | Shared | Shared |
44//! | Cloneable | ❌ | ✅ | ✅ |
45//! | Thread-Safe | ❌ | ✅ | ❌ |
46//! | Interior Mut. | N/A | Mutex | RefCell |
47//! | `and_then` API | `self` | `&self` | `&self` |
48//! | Lock Overhead | None | Yes | None |
49//!
50//! # Use Cases
51//!
52//! ## BoxMutator
53//!
54//! - One-time operations that don't require sharing
55//! - Builder patterns where ownership naturally flows
56//! - Simple scenarios with no reuse requirements
57//!
58//! ## ArcMutator
59//!
60//! - Multi-threaded shared operations
61//! - Concurrent task processing (e.g., thread pools)
62//! - Situations requiring the same mutator across threads
63//!
64//! ## RcMutator
65//!
66//! - Single-threaded operations with multiple uses
67//! - Event handling in single-threaded UI frameworks
68//! - Performance-critical single-threaded scenarios
69//!
70//! # Examples
71//!
72//! ## Basic Usage
73//!
74//! ```rust
75//! use prism3_function::{BoxMutator, ArcMutator, RcMutator, Mutator};
76//!
77//! // BoxMutator: Single ownership, consumes self
78//! let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
79//! let mut value = 5;
80//! mutator.mutate(&mut value);
81//! assert_eq!(value, 10);
82//!
83//! // ArcMutator: Shared ownership, cloneable, thread-safe
84//! let shared = ArcMutator::new(|x: &mut i32| *x *= 2);
85//! let clone = shared.clone();
86//! let mut value = 5;
87//! let mut m = shared;
88//! m.mutate(&mut value);
89//! assert_eq!(value, 10);
90//!
91//! // RcMutator: Shared ownership, cloneable, single-threaded
92//! let rc = RcMutator::new(|x: &mut i32| *x *= 2);
93//! let clone = rc.clone();
94//! let mut value = 5;
95//! let mut m = rc;
96//! m.mutate(&mut value);
97//! assert_eq!(value, 10);
98//! ```
99//!
100//! ## Method Chaining
101//!
102//! ```rust
103//! use prism3_function::{Mutator, BoxMutator, ArcMutator};
104//!
105//! // BoxMutator: Consumes self
106//! let mut chained = BoxMutator::new(|x: &mut i32| *x *= 2)
107//! .and_then(|x: &mut i32| *x += 10);
108//! let mut value = 5;
109//! chained.mutate(&mut value);
110//! assert_eq!(value, 20); // (5 * 2) + 10
111//!
112//! // ArcMutator: Borrows &self, original still usable
113//! let first = ArcMutator::new(|x: &mut i32| *x *= 2);
114//! let second = ArcMutator::new(|x: &mut i32| *x += 10);
115//! let combined = first.and_then(&second);
116//! // first and second are still usable here
117//! ```
118//!
119//! ## Working with Closures
120//!
121//! All closures automatically implement the `Mutator` trait:
122//!
123//! ```rust
124//! use prism3_function::{Mutator, FnMutatorOps};
125//!
126//! // Closures can use .mutate() directly
127//! let mut closure = |x: &mut i32| *x *= 2;
128//! let mut value = 5;
129//! closure.mutate(&mut value);
130//! assert_eq!(value, 10);
131//!
132//! // Closures can be chained, returning BoxMutator
133//! let mut chained = (|x: &mut i32| *x *= 2)
134//! .and_then(|x: &mut i32| *x += 10);
135//! let mut value = 5;
136//! chained.mutate(&mut value);
137//! assert_eq!(value, 20);
138//! ```
139//!
140//! ## Type Conversions
141//!
142//! ```rust
143//! use prism3_function::Mutator;
144//!
145//! // Convert closure to concrete type
146//! let closure = |x: &mut i32| *x *= 2;
147//! let mut box_mutator = closure.into_box();
148//!
149//! let closure = |x: &mut i32| *x *= 2;
150//! let mut rc_mutator = closure.into_rc();
151//!
152//! let closure = |x: &mut i32| *x *= 2;
153//! let mut arc_mutator = closure.into_arc();
154//! ```
155//!
156//! ## Conditional Execution
157//!
158//! All mutator types support conditional execution through the `when` method,
159//! which returns a `ConditionalMutator`. You can optionally add an `or_else`
160//! branch to create if-then-else logic:
161//!
162//! ```rust
163//! use prism3_function::{Mutator, BoxMutator};
164//!
165//! // Simple conditional (if-then)
166//! let mut conditional = BoxMutator::new(|x: &mut i32| *x *= 2)
167//! .when(|x: &i32| *x > 0);
168//!
169//! let mut positive = 5;
170//! conditional.mutate(&mut positive);
171//! assert_eq!(positive, 10); // Executed
172//!
173//! let mut negative = -5;
174//! conditional.mutate(&mut negative);
175//! assert_eq!(negative, -5); // Not executed
176//!
177//! // Conditional with else branch (if-then-else)
178//! let mut branched = BoxMutator::new(|x: &mut i32| *x *= 2)
179//! .when(|x: &i32| *x > 0)
180//! .or_else(|x: &mut i32| *x -= 1);
181//!
182//! let mut positive = 5;
183//! branched.mutate(&mut positive);
184//! assert_eq!(positive, 10); // when branch
185//!
186//! let mut negative = -5;
187//! branched.mutate(&mut negative);
188//! assert_eq!(negative, -6); // or_else branch
189//! ```
190//!
191//! # Author
192//!
193//! Haixing Hu
194
195use std::cell::RefCell;
196use std::rc::Rc;
197use std::sync::{Arc, Mutex};
198
199use crate::predicate::{ArcPredicate, BoxPredicate, Predicate, RcPredicate};
200
201// ============================================================================
202// 1. Mutator Trait - Unified Mutator Interface
203// ============================================================================
204
205/// Mutator trait - Unified mutator interface
206///
207/// Defines the core behavior of all mutator types. Performs operations that
208/// accept a mutable reference and modify the input value (not just side effects).
209///
210/// This trait is automatically implemented by:
211/// - All closures implementing `FnMut(&mut T)`
212/// - `BoxMutator<T>`, `ArcMutator<T>`, and `RcMutator<T>`
213///
214/// # Design Rationale
215///
216/// The trait provides a unified abstraction over different ownership models,
217/// allowing generic code to work with any mutator type. Type conversion
218/// methods (`into_box`, `into_arc`, `into_rc`) enable flexible ownership
219/// transitions based on usage requirements.
220///
221/// # Features
222///
223/// - **Unified Interface**: All mutator types share the same `mutate`
224/// method signature
225/// - **Automatic Implementation**: Closures automatically implement this
226/// trait with zero overhead
227/// - **Type Conversions**: Easy conversion between ownership models
228/// - **Generic Programming**: Write functions that work with any mutator
229/// type
230///
231/// # Examples
232///
233/// ## Generic Mutator Function
234///
235/// ```rust
236/// use prism3_function::{Mutator, BoxMutator, ArcMutator};
237///
238/// fn apply_mutator<M: Mutator<i32>>(
239/// mutator: &mut M,
240/// value: i32
241/// ) -> i32 {
242/// let mut val = value;
243/// mutator.mutate(&mut val);
244/// val
245/// }
246///
247/// // Works with any mutator type
248/// let mut box_mut = BoxMutator::new(|x: &mut i32| *x *= 2);
249/// assert_eq!(apply_mutator(&mut box_mut, 5), 10);
250///
251/// let mut arc_mut = ArcMutator::new(|x: &mut i32| *x *= 2);
252/// assert_eq!(apply_mutator(&mut arc_mut, 5), 10);
253///
254/// let mut closure = |x: &mut i32| *x *= 2;
255/// assert_eq!(apply_mutator(&mut closure, 5), 10);
256/// ```
257///
258/// ## Type Conversion
259///
260/// ```rust
261/// use prism3_function::Mutator;
262///
263/// let closure = |x: &mut i32| *x *= 2;
264///
265/// // Convert to different ownership models
266/// let box_mutator = closure.into_box();
267/// // let rc_mutator = closure.into_rc(); // closure moved
268/// // let arc_mutator = closure.into_arc(); // closure moved
269/// ```
270///
271/// # Author
272///
273/// Haixing Hu
274pub trait Mutator<T> {
275 /// Performs the mutation operation
276 ///
277 /// Executes an operation on the given mutable reference. The operation
278 /// typically modifies the input value or produces side effects.
279 ///
280 /// # Parameters
281 ///
282 /// * `value` - A mutable reference to the value to be mutated
283 ///
284 /// # Examples
285 ///
286 /// ```rust
287 /// use prism3_function::{Mutator, BoxMutator};
288 ///
289 /// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
290 /// let mut value = 5;
291 /// mutator.mutate(&mut value);
292 /// assert_eq!(value, 10);
293 /// ```
294 fn mutate(&mut self, value: &mut T);
295
296 /// Convert this mutator into a `BoxMutator<T>`.
297 ///
298 /// This consuming conversion takes ownership of `self` and returns a
299 /// boxed implementation that forwards calls to the original mutator.
300 /// Types that can provide a more efficient conversion may override the
301 /// default implementation.
302 ///
303 /// # Consumption
304 ///
305 /// This method consumes the mutator: the original value will no longer
306 /// be available after the call. For cloneable mutators call `.clone()`
307 /// before converting if you need to retain the original instance.
308 ///
309 /// # Returns
310 ///
311 /// A `BoxMutator<T>` that forwards to the original mutator.
312 ///
313 /// # Examples
314 ///
315 /// ```rust
316 /// use prism3_function::Mutator;
317 ///
318 /// let closure = |x: &mut i32| *x *= 2;
319 /// let mut boxed = closure.into_box();
320 /// let mut value = 5;
321 /// boxed.mutate(&mut value);
322 /// assert_eq!(value, 10);
323 /// ```
324 fn into_box(mut self) -> BoxMutator<T>
325 where
326 Self: Sized + 'static,
327 T: 'static,
328 {
329 BoxMutator::new(move |t| self.mutate(t))
330 }
331
332 /// Convert this mutator into an `RcMutator<T>`.
333 ///
334 /// This consuming conversion takes ownership of `self` and returns an
335 /// `Rc`-backed mutator that forwards calls to the original. Override to
336 /// provide a more direct or efficient conversion when available.
337 ///
338 /// # Consumption
339 ///
340 /// This method consumes the mutator. If you need to keep the original
341 /// instance, clone it prior to calling this method.
342 ///
343 /// # Returns
344 ///
345 /// An `RcMutator<T>` forwarding to the original mutator.
346 ///
347 /// # Examples
348 ///
349 /// ```rust
350 /// use prism3_function::Mutator;
351 ///
352 /// let closure = |x: &mut i32| *x *= 2;
353 /// let mut rc = closure.into_rc();
354 /// let mut value = 5;
355 /// rc.mutate(&mut value);
356 /// assert_eq!(value, 10);
357 /// ```
358 fn into_rc(mut self) -> RcMutator<T>
359 where
360 Self: Sized + 'static,
361 T: 'static,
362 {
363 RcMutator::new(move |t| self.mutate(t))
364 }
365
366 /// Convert this mutator into an `ArcMutator<T>`.
367 ///
368 /// This consuming conversion takes ownership of `self` and returns an
369 /// `Arc`-wrapped, thread-safe mutator. Types may override the default
370 /// implementation to provide a more efficient conversion.
371 ///
372 /// # Consumption
373 ///
374 /// This method consumes the mutator. Clone the instance first if you
375 /// need to retain the original for further use.
376 ///
377 /// # Returns
378 ///
379 /// An `ArcMutator<T>` that forwards to the original mutator.
380 ///
381 /// # Examples
382 ///
383 /// ```rust
384 /// use prism3_function::Mutator;
385 ///
386 /// let closure = |x: &mut i32| *x *= 2;
387 /// let mut arc = closure.into_arc();
388 /// let mut value = 5;
389 /// arc.mutate(&mut value);
390 /// assert_eq!(value, 10);
391 /// ```
392 fn into_arc(mut self) -> ArcMutator<T>
393 where
394 Self: Sized + Send + 'static,
395 T: Send + 'static,
396 {
397 ArcMutator::new(move |t| self.mutate(t))
398 }
399
400 /// Consume the mutator and return an `FnMut(&mut T)` closure.
401 ///
402 /// The returned closure forwards calls to the original mutator and is
403 /// suitable for use with iterator adapters such as `for_each`.
404 ///
405 /// # Consumption
406 ///
407 /// This method consumes the mutator. The original instance will not be
408 /// available after calling this method.
409 ///
410 /// # Returns
411 ///
412 /// A closure implementing `FnMut(&mut T)` which forwards to the
413 /// original mutator.
414 ///
415 /// # Examples
416 ///
417 /// ```rust
418 /// use prism3_function::{Mutator, BoxMutator};
419 ///
420 /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
421 /// let mut values = vec![1, 2, 3, 4, 5];
422 /// values.iter_mut().for_each(mutator.into_fn());
423 /// assert_eq!(values, vec![2, 4, 6, 8, 10]);
424 /// ```
425 fn into_fn(mut self) -> impl FnMut(&mut T)
426 where
427 Self: Sized + 'static,
428 T: 'static,
429 {
430 move |t| self.mutate(t)
431 }
432
433 /// Create a non-consuming `BoxMutator<T>` that forwards to `self`.
434 ///
435 /// The default implementation clones `self` (requires `Clone`) and
436 /// returns a boxed mutator that calls the cloned instance. Override this
437 /// method if a more efficient conversion exists.
438 ///
439 /// # Returns
440 ///
441 /// A `BoxMutator<T>` that forwards to a clone of `self`.
442 fn to_box(&self) -> BoxMutator<T>
443 where
444 Self: Sized + Clone + 'static,
445 T: 'static,
446 {
447 self.clone().into_box()
448 }
449
450 /// Create a non-consuming `RcMutator<T>` that forwards to `self`.
451 ///
452 /// The default implementation clones `self` (requires `Clone`) and
453 /// returns an `Rc`-backed mutator that forwards calls to the clone.
454 /// Override to provide a more direct or efficient conversion if needed.
455 ///
456 /// # Returns
457 ///
458 /// An `RcMutator<T>` that forwards to a clone of `self`.
459 fn to_rc(&self) -> RcMutator<T>
460 where
461 Self: Sized + Clone + 'static,
462 T: 'static,
463 {
464 self.clone().into_rc()
465 }
466
467 /// Create a non-consuming `ArcMutator<T>` that forwards to `self`.
468 ///
469 /// The default implementation clones `self` (requires `Clone + Send`) and
470 /// returns an `Arc`-wrapped mutator that forwards calls to the clone.
471 /// Override when a more efficient conversion is available.
472 ///
473 /// # Returns
474 ///
475 /// An `ArcMutator<T>` that forwards to a clone of `self`.
476 fn to_arc(&self) -> ArcMutator<T>
477 where
478 Self: Sized + Clone + Send + 'static,
479 T: Send + 'static,
480 {
481 self.clone().into_arc()
482 }
483
484 /// Create a boxed `FnMut(&mut T)` closure that forwards to `self`.
485 ///
486 /// The default implementation clones `self` (requires `Clone`) and
487 /// returns a boxed closure that invokes the cloned instance. Override to
488 /// provide a more efficient conversion when possible.
489 ///
490 /// # Returns
491 ///
492 /// A closure implementing `FnMut(&mut T)` which forwards to the
493 /// original mutator.
494 fn to_fn(&self) -> impl FnMut(&mut T)
495 where
496 Self: Sized + Clone + 'static,
497 T: 'static,
498 {
499 self.clone().into_fn()
500 }
501}
502
503// ============================================================================
504// 2. Type Aliases
505// ============================================================================
506
507/// Type alias for Arc-wrapped mutable mutator function
508type ArcMutMutatorFn<T> = Arc<Mutex<dyn FnMut(&mut T) + Send>>;
509
510/// Type alias for Rc-wrapped mutable mutator function
511type RcMutMutatorFn<T> = Rc<RefCell<dyn FnMut(&mut T)>>;
512
513// ============================================================================
514// 3. BoxMutator - Single Ownership Implementation
515// ============================================================================
516
517/// BoxMutator struct
518///
519/// A mutator implementation based on `Box<dyn FnMut(&mut T)>` for single
520/// ownership scenarios. This is the simplest and most efficient mutator
521/// type when sharing is not required.
522///
523/// # Features
524///
525/// - **Single Ownership**: Not cloneable, ownership moves on use
526/// - **Zero Overhead**: No reference counting or locking
527/// - **Mutable State**: Can modify captured environment via `FnMut`
528/// - **Builder Pattern**: Method chaining consumes `self` naturally
529/// - **Factory Methods**: Convenient constructors for common patterns
530///
531/// # Use Cases
532///
533/// Choose `BoxMutator` when:
534/// - The mutator is used only once or in a linear flow
535/// - Building pipelines where ownership naturally flows
536/// - No need to share the mutator across contexts
537/// - Performance is critical and no sharing overhead is acceptable
538///
539/// # Performance
540///
541/// `BoxMutator` has the best performance among the three mutator types:
542/// - No reference counting overhead
543/// - No lock acquisition or runtime borrow checking
544/// - Direct function call through vtable
545/// - Minimal memory footprint (single pointer)
546///
547/// # Examples
548///
549/// ```rust
550/// use prism3_function::{Mutator, BoxMutator};
551///
552/// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
553/// let mut value = 5;
554/// mutator.mutate(&mut value);
555/// assert_eq!(value, 10);
556/// ```
557///
558/// # Author
559///
560/// Haixing Hu
561pub struct BoxMutator<T> {
562 function: Box<dyn FnMut(&mut T)>,
563}
564
565impl<T> BoxMutator<T>
566where
567 T: 'static,
568{
569 /// Creates a new BoxMutator
570 ///
571 /// # Parameters
572 ///
573 /// * `f` - The closure to wrap
574 ///
575 /// # Returns
576 ///
577 /// Returns a new `BoxMutator<T>` instance
578 ///
579 /// # Examples
580 ///
581 /// ```rust
582 /// use prism3_function::{Mutator, BoxMutator};
583 ///
584 /// let mut mutator = BoxMutator::new(|x: &mut i32| *x += 1);
585 /// let mut value = 5;
586 /// mutator.mutate(&mut value);
587 /// assert_eq!(value, 6);
588 /// ```
589 pub fn new<F>(f: F) -> Self
590 where
591 F: FnMut(&mut T) + 'static,
592 {
593 BoxMutator {
594 function: Box::new(f),
595 }
596 }
597
598 /// Creates a no-op mutator
599 ///
600 /// Returns a mutator that performs no operation.
601 ///
602 /// # Returns
603 ///
604 /// Returns a no-op mutator
605 ///
606 /// # Examples
607 ///
608 /// ```rust
609 /// use prism3_function::{Mutator, BoxMutator};
610 ///
611 /// let mut noop = BoxMutator::<i32>::noop();
612 /// let mut value = 42;
613 /// noop.mutate(&mut value);
614 /// assert_eq!(value, 42); // Value unchanged
615 /// ```
616 pub fn noop() -> Self {
617 BoxMutator::new(|_| {})
618 }
619
620 /// Chains another mutator in sequence
621 ///
622 /// Returns a new mutator that first executes the current operation, then
623 /// executes the next operation. Consumes self.
624 ///
625 /// # Parameters
626 ///
627 /// * `next` - The mutator to execute after the current operation. **Note:
628 /// This parameter is passed by value and will transfer ownership.** If you
629 /// need to preserve the original mutator, clone it first (if it implements
630 /// `Clone`). Can be:
631 /// - A closure: `|x: &mut T|`
632 /// - A `BoxMutator<T>`
633 /// - An `ArcMutator<T>`
634 /// - An `RcMutator<T>`
635 /// - Any type implementing `Mutator<T>`
636 ///
637 /// # Returns
638 ///
639 /// Returns a new composed `BoxMutator<T>`
640 ///
641 /// # Examples
642 ///
643 /// ## Direct value passing (ownership transfer)
644 ///
645 /// ```rust
646 /// use prism3_function::{Mutator, BoxMutator};
647 ///
648 /// let first = BoxMutator::new(|x: &mut i32| *x *= 2);
649 /// let second = BoxMutator::new(|x: &mut i32| *x += 10);
650 ///
651 /// // second is moved here
652 /// let mut chained = first.and_then(second);
653 /// let mut value = 5;
654 /// chained.mutate(&mut value);
655 /// assert_eq!(value, 20);
656 /// // second.mutate(&mut value); // Would not compile - moved
657 /// ```
658 ///
659 /// ## Preserving original with clone
660 ///
661 /// ```rust
662 /// use prism3_function::{Mutator, BoxMutator};
663 ///
664 /// let first = BoxMutator::new(|x: &mut i32| *x *= 2);
665 /// let second = BoxMutator::new(|x: &mut i32| *x += 10);
666 ///
667 /// // Clone to preserve original
668 /// let mut chained = first.and_then(second.clone());
669 /// let mut value = 5;
670 /// chained.mutate(&mut value);
671 /// assert_eq!(value, 20);
672 ///
673 /// // Original still usable
674 /// let mut value2 = 3;
675 /// second.mutate(&mut value2);
676 /// assert_eq!(value2, 13);
677 /// ```
678 pub fn and_then<C>(self, next: C) -> Self
679 where
680 C: Mutator<T> + 'static,
681 {
682 let mut first = self.function;
683 let mut second = next.into_fn();
684 BoxMutator::new(move |t| {
685 (first)(t);
686 second(t);
687 })
688 }
689
690 /// Creates a conditional mutator
691 ///
692 /// Returns a mutator that only executes when a predicate is satisfied.
693 ///
694 /// # Parameters
695 ///
696 /// * `predicate` - The condition to check. **Note: This parameter is passed
697 /// by value and will transfer ownership.** If you need to preserve the
698 /// original predicate, clone it first (if it implements `Clone`).
699 /// Can be:
700 /// - A closure: `|x: &T| -> bool`
701 /// - A function pointer: `fn(&T) -> bool`
702 /// - A `BoxPredicate<T>`
703 /// - An `RcPredicate<T>`
704 /// - An `ArcPredicate<T>`
705 /// - Any type implementing `Predicate<T>`
706 ///
707 /// # Returns
708 ///
709 /// Returns `BoxConditionalMutator<T>`
710 ///
711 /// # Examples
712 ///
713 /// ## Using a closure
714 ///
715 /// ```rust
716 /// use prism3_function::{Mutator, BoxMutator};
717 ///
718 /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
719 /// let mut conditional = mutator.when(|x: &i32| *x > 0);
720 ///
721 /// let mut positive = 5;
722 /// conditional.mutate(&mut positive);
723 /// assert_eq!(positive, 10);
724 ///
725 /// let mut negative = -5;
726 /// conditional.mutate(&mut negative);
727 /// assert_eq!(negative, -5); // Unchanged
728 /// ```
729 ///
730 /// ## Using BoxPredicate
731 ///
732 /// ```rust
733 /// use prism3_function::{Mutator, BoxMutator};
734 /// use prism3_function::predicate::{Predicate, BoxPredicate};
735 ///
736 /// let pred = BoxPredicate::new(|x: &i32| *x > 0);
737 /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
738 /// let mut conditional = mutator.when(pred);
739 ///
740 /// let mut value = 5;
741 /// conditional.mutate(&mut value);
742 /// assert_eq!(value, 10);
743 /// ```
744 ///
745 /// ## Using composed predicate
746 ///
747 /// ```rust
748 /// use prism3_function::{Mutator, BoxMutator};
749 /// use prism3_function::predicate::{Predicate, FnPredicateOps};
750 ///
751 /// let pred = (|x: &i32| *x > 0).and(|x: &i32| x % 2 == 0);
752 /// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
753 /// let mut conditional = mutator.when(pred);
754 ///
755 /// let mut value = 4;
756 /// conditional.mutate(&mut value);
757 /// assert_eq!(value, 8); // Positive and even
758 ///
759 /// let mut odd = 3;
760 /// conditional.mutate(&mut odd);
761 /// assert_eq!(odd, 3); // Positive but odd, unchanged
762 /// ```
763 pub fn when<P>(self, predicate: P) -> BoxConditionalMutator<T>
764 where
765 P: Predicate<T> + 'static,
766 {
767 BoxConditionalMutator {
768 mutator: self,
769 predicate: predicate.into_box(),
770 }
771 }
772}
773
774impl<T> Mutator<T> for BoxMutator<T> {
775 fn mutate(&mut self, value: &mut T) {
776 (self.function)(value)
777 }
778
779 fn into_box(self) -> BoxMutator<T>
780 where
781 T: 'static,
782 {
783 self
784 }
785
786 fn into_rc(self) -> RcMutator<T>
787 where
788 T: 'static,
789 {
790 let mut self_fn = self.function;
791 RcMutator::new(move |t| self_fn(t))
792 }
793
794 // do NOT override Mutator::into_arc() because BoxMutator is not Send + Sync
795 // and calling BoxMutator::into_arc() will cause a compile error
796
797 fn into_fn(mut self) -> impl FnMut(&mut T)
798 where
799 Self: Sized + 'static,
800 T: 'static,
801 {
802 move |t| (self.function)(t)
803 }
804
805 // do NOT override Mutator::to_xxx() because BoxMutator is not Clone
806 // and calling BoxMutator::to_xxx() will cause a compile error
807}
808
809// ============================================================================
810// 3. BoxConditionalMutator - Box-based Conditional Mutator
811// ============================================================================
812
813/// BoxConditionalMutator struct
814///
815/// A conditional mutator that only executes when a predicate is satisfied.
816/// Uses `BoxMutator` and `BoxPredicate` for single ownership semantics.
817///
818/// This type is typically created by calling `BoxMutator::when()` and is
819/// designed to work with the `or_else()` method to create if-then-else logic.
820///
821/// # Features
822///
823/// - **Single Ownership**: Not cloneable, consumes `self` on use
824/// - **Conditional Execution**: Only mutates when predicate returns `true`
825/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
826/// - **Implements Mutator**: Can be used anywhere a `Mutator` is expected
827///
828/// # Examples
829///
830/// ## Basic Conditional Execution
831///
832/// ```rust
833/// use prism3_function::{Mutator, BoxMutator};
834///
835/// let mutator = BoxMutator::new(|x: &mut i32| *x *= 2);
836/// let mut conditional = mutator.when(|x: &i32| *x > 0);
837///
838/// let mut positive = 5;
839/// conditional.mutate(&mut positive);
840/// assert_eq!(positive, 10); // Executed
841///
842/// let mut negative = -5;
843/// conditional.mutate(&mut negative);
844/// assert_eq!(negative, -5); // Not executed
845/// ```
846///
847/// ## With or_else Branch
848///
849/// ```rust
850/// use prism3_function::{Mutator, BoxMutator};
851///
852/// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2)
853/// .when(|x: &i32| *x > 0)
854/// .or_else(|x: &mut i32| *x -= 1);
855///
856/// let mut positive = 5;
857/// mutator.mutate(&mut positive);
858/// assert_eq!(positive, 10); // when branch executed
859///
860/// let mut negative = -5;
861/// mutator.mutate(&mut negative);
862/// assert_eq!(negative, -6); // or_else branch executed
863/// ```
864///
865/// # Author
866///
867/// Haixing Hu
868pub struct BoxConditionalMutator<T> {
869 mutator: BoxMutator<T>,
870 predicate: BoxPredicate<T>,
871}
872
873impl<T> BoxConditionalMutator<T>
874where
875 T: 'static,
876{
877 /// Chains another mutator in sequence
878 ///
879 /// Combines the current conditional mutator with another mutator into a new
880 /// mutator. The current conditional mutator executes first, followed by the
881 /// next mutator.
882 ///
883 /// # Parameters
884 ///
885 /// * `next` - The next mutator to execute. **Note: This parameter is passed
886 /// by value and will transfer ownership.** If you need to preserve the
887 /// original mutator, clone it first (if it implements `Clone`). Can be:
888 /// - A closure: `|x: &mut T|`
889 /// - A `BoxMutator<T>`
890 /// - An `ArcMutator<T>`
891 /// - An `RcMutator<T>`
892 /// - Any type implementing `Mutator<T>`
893 ///
894 /// # Returns
895 ///
896 /// Returns a new `BoxMutator<T>`
897 ///
898 /// # Examples
899 ///
900 /// ## Direct value passing (ownership transfer)
901 ///
902 /// ```rust
903 /// use prism3_function::{Mutator, BoxMutator};
904 ///
905 /// let cond1 = BoxMutator::new(|x: &mut i32| *x *= 2).when(|x: &i32| *x > 0);
906 /// let cond2 = BoxMutator::new(|x: &mut i32| *x = 100).when(|x: &i32| *x > 100);
907 ///
908 /// // cond2 is moved here
909 /// let mut chained = cond1.and_then(cond2);
910 /// let mut value = 60;
911 /// chained.mutate(&mut value);
912 /// assert_eq!(value, 100); // First *2 = 120, then capped to 100
913 /// // cond2.mutate(&mut value); // Would not compile - moved
914 /// ```
915 ///
916 /// ## Preserving original with clone
917 ///
918 /// ```rust
919 /// use prism3_function::{Mutator, BoxMutator};
920 ///
921 /// let cond1 = BoxMutator::new(|x: &mut i32| *x *= 2).when(|x: &i32| *x > 0);
922 /// let cond2 = BoxMutator::new(|x: &mut i32| *x = 100).when(|x: &i32| *x > 100);
923 ///
924 /// // Clone to preserve original
925 /// let mut chained = cond1.and_then(cond2.clone());
926 /// let mut value = 60;
927 /// chained.mutate(&mut value);
928 /// assert_eq!(value, 100); // First *2 = 120, then capped to 100
929 ///
930 /// // Original still usable
931 /// let mut value2 = 50;
932 /// cond2.mutate(&mut value2);
933 /// assert_eq!(value2, 100);
934 /// ```
935 pub fn and_then<C>(self, next: C) -> BoxMutator<T>
936 where
937 C: Mutator<T> + 'static,
938 {
939 let mut first = self;
940 let mut second = next.into_fn();
941 BoxMutator::new(move |t| {
942 first.mutate(t);
943 second(t);
944 })
945 }
946
947 /// Adds an else branch
948 ///
949 /// Executes the original mutator when the condition is satisfied, otherwise
950 /// executes else_mutator.
951 ///
952 /// # Parameters
953 ///
954 /// * `else_mutator` - The mutator for the else branch. **Note: This parameter
955 /// is passed by value and will transfer ownership.** If you need to preserve
956 /// the original mutator, clone it first (if it implements `Clone`). Can be:
957 /// - A closure: `|x: &mut T|`
958 /// - A `BoxMutator<T>`
959 /// - An `RcMutator<T>`
960 /// - An `ArcMutator<T>`
961 /// - Any type implementing `Mutator<T>`
962 ///
963 /// # Returns
964 ///
965 /// Returns the composed `BoxMutator<T>`
966 ///
967 /// # Examples
968 ///
969 /// ## Using a closure (recommended)
970 ///
971 /// ```rust
972 /// use prism3_function::{Mutator, BoxMutator};
973 ///
974 /// let mut mutator = BoxMutator::new(|x: &mut i32| *x *= 2)
975 /// .when(|x: &i32| *x > 0)
976 /// .or_else(|x: &mut i32| *x -= 1);
977 ///
978 /// let mut positive = 5;
979 /// mutator.mutate(&mut positive);
980 /// assert_eq!(positive, 10); // Condition satisfied, execute *2
981 ///
982 /// let mut negative = -5;
983 /// mutator.mutate(&mut negative);
984 /// assert_eq!(negative, -6); // Condition not satisfied, execute -1
985 /// ```
986 pub fn or_else<C>(self, else_mutator: C) -> BoxMutator<T>
987 where
988 C: Mutator<T> + 'static,
989 {
990 let pred = self.predicate;
991 let mut then_mut = self.mutator;
992 let mut else_mut = else_mutator;
993 BoxMutator::new(move |t| {
994 if pred.test(t) {
995 then_mut.mutate(t);
996 } else {
997 else_mut.mutate(t);
998 }
999 })
1000 }
1001}
1002
1003impl<T> Mutator<T> for BoxConditionalMutator<T>
1004where
1005 T: 'static,
1006{
1007 fn mutate(&mut self, value: &mut T) {
1008 if self.predicate.test(value) {
1009 self.mutator.mutate(value);
1010 }
1011 }
1012
1013 fn into_box(self) -> BoxMutator<T> {
1014 let pred = self.predicate;
1015 let mut mutator = self.mutator;
1016 BoxMutator::new(move |t| {
1017 if pred.test(t) {
1018 mutator.mutate(t);
1019 }
1020 })
1021 }
1022
1023 fn into_rc(self) -> RcMutator<T> {
1024 let pred = self.predicate.into_rc();
1025 let mutator = self.mutator.into_rc();
1026 let mut mutator_fn = mutator;
1027 RcMutator::new(move |t| {
1028 if pred.test(t) {
1029 mutator_fn.mutate(t);
1030 }
1031 })
1032 }
1033
1034 // do NOT override Mutator::into_arc() because BoxConditionalMutator is not Send + Sync
1035 // and calling BoxConditionalMutator::into_arc() will cause a compile error
1036
1037 fn into_fn(self) -> impl FnMut(&mut T) {
1038 let pred = self.predicate;
1039 let mut mutator = self.mutator;
1040 move |t: &mut T| {
1041 if pred.test(t) {
1042 mutator.mutate(t);
1043 }
1044 }
1045 }
1046
1047 // do NOT override Mutator::to_xxx() because BoxConditionalMutator is not Clone
1048 // and calling BoxConditionalMutator::to_xxx() will cause a compile error
1049}
1050
1051// ============================================================================
1052// 4. RcMutator - Single-Threaded Shared Ownership Implementation
1053// ============================================================================
1054
1055/// RcMutator struct
1056///
1057/// A mutator implementation based on `Rc<RefCell<dyn FnMut(&mut T)>>` for
1058/// single-threaded shared ownership scenarios. This type allows multiple
1059/// references to the same mutator without the overhead of thread safety.
1060///
1061/// # Features
1062///
1063/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1064/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1065/// - **Interior Mutability**: Uses `RefCell` for runtime borrow checking
1066/// - **Mutable State**: Can modify captured environment via `FnMut`
1067/// - **Chainable**: Method chaining via `&self` (non-consuming)
1068/// - **Performance**: More efficient than `ArcMutator` (no locking)
1069///
1070/// # Use Cases
1071///
1072/// Choose `RcMutator` when:
1073/// - The mutator needs to be shared within a single thread
1074/// - Thread safety is not required
1075/// - Performance is important (avoiding lock overhead)
1076///
1077/// # Examples
1078///
1079/// ```rust
1080/// use prism3_function::{Mutator, RcMutator};
1081///
1082/// let mutator = RcMutator::new(|x: &mut i32| *x *= 2);
1083/// let clone = mutator.clone();
1084///
1085/// let mut value = 5;
1086/// let mut m = mutator;
1087/// m.mutate(&mut value);
1088/// assert_eq!(value, 10);
1089/// ```
1090///
1091/// # Author
1092///
1093/// Haixing Hu
1094pub struct RcMutator<T> {
1095 function: RcMutMutatorFn<T>,
1096}
1097
1098impl<T> RcMutator<T>
1099where
1100 T: 'static,
1101{
1102 /// Creates a new RcMutator
1103 ///
1104 /// # Parameters
1105 ///
1106 /// * `f` - The closure to wrap
1107 ///
1108 /// # Returns
1109 ///
1110 /// Returns a new `RcMutator<T>` instance
1111 ///
1112 /// # Examples
1113 ///
1114 /// ```rust
1115 /// use prism3_function::{Mutator, RcMutator};
1116 ///
1117 /// let mutator = RcMutator::new(|x: &mut i32| *x += 1);
1118 /// let mut value = 5;
1119 /// let mut m = mutator;
1120 /// m.mutate(&mut value);
1121 /// assert_eq!(value, 6);
1122 /// ```
1123 pub fn new<F>(f: F) -> Self
1124 where
1125 F: FnMut(&mut T) + 'static,
1126 {
1127 RcMutator {
1128 function: Rc::new(RefCell::new(f)),
1129 }
1130 }
1131
1132 /// Creates a no-op mutator
1133 ///
1134 /// Returns a mutator that performs no operation.
1135 ///
1136 /// # Returns
1137 ///
1138 /// Returns a no-op mutator
1139 ///
1140 /// # Examples
1141 ///
1142 /// ```rust
1143 /// use prism3_function::{Mutator, RcMutator};
1144 ///
1145 /// let noop = RcMutator::<i32>::noop();
1146 /// let mut value = 42;
1147 /// let mut m = noop;
1148 /// m.mutate(&mut value);
1149 /// assert_eq!(value, 42); // Value unchanged
1150 /// ```
1151 pub fn noop() -> Self {
1152 RcMutator::new(|_| {})
1153 }
1154
1155 /// Chains another RcMutator in sequence
1156 ///
1157 /// Returns a new mutator that first executes the current operation, then
1158 /// executes the next operation. Borrows &self, does not consume the
1159 /// original mutator.
1160 ///
1161 /// # Parameters
1162 ///
1163 /// * `next` - The mutator to execute after the current operation
1164 ///
1165 /// # Returns
1166 ///
1167 /// Returns a new composed `RcMutator<T>`
1168 ///
1169 /// # Examples
1170 ///
1171 /// ```rust
1172 /// use prism3_function::{Mutator, RcMutator};
1173 ///
1174 /// let first = RcMutator::new(|x: &mut i32| *x *= 2);
1175 /// let second = RcMutator::new(|x: &mut i32| *x += 10);
1176 ///
1177 /// let chained = first.and_then(&second);
1178 ///
1179 /// // first and second are still usable
1180 /// let mut value = 5;
1181 /// let mut m = chained;
1182 /// m.mutate(&mut value);
1183 /// assert_eq!(value, 20); // (5 * 2) + 10
1184 /// ```
1185 pub fn and_then(&self, next: &RcMutator<T>) -> RcMutator<T> {
1186 let first = self.function.clone();
1187 let second = next.function.clone();
1188 RcMutator::new(move |t: &mut T| {
1189 (first.borrow_mut())(t);
1190 (second.borrow_mut())(t);
1191 })
1192 }
1193
1194 /// Creates a conditional mutator (single-threaded shared version)
1195 ///
1196 /// Returns a mutator that only executes when a predicate is satisfied.
1197 ///
1198 /// # Parameters
1199 ///
1200 /// * `predicate` - The condition to check. **Note: This parameter is passed
1201 /// by value and will transfer ownership.** If you need to preserve the
1202 /// original predicate, clone it first (if it implements `Clone`). Can be:
1203 /// - A closure: `|x: &T| -> bool`
1204 /// - A function pointer: `fn(&T) -> bool`
1205 /// - An `RcPredicate<T>`
1206 /// - A `BoxPredicate<T>`
1207 /// - Any type implementing `Predicate<T>`
1208 ///
1209 /// # Returns
1210 ///
1211 /// Returns `RcConditionalMutator<T>`
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```rust
1216 /// use prism3_function::{Mutator, RcMutator};
1217 ///
1218 /// let mutator = RcMutator::new(|x: &mut i32| *x *= 2);
1219 /// let conditional = mutator.when(|x: &i32| *x > 0);
1220 ///
1221 /// let conditional_clone = conditional.clone();
1222 ///
1223 /// let mut positive = 5;
1224 /// let mut m = conditional;
1225 /// m.mutate(&mut positive);
1226 /// assert_eq!(positive, 10);
1227 /// ```
1228 pub fn when<P>(&self, predicate: P) -> RcConditionalMutator<T>
1229 where
1230 P: Predicate<T> + 'static,
1231 {
1232 RcConditionalMutator {
1233 mutator: self.clone(),
1234 predicate: predicate.into_rc(),
1235 }
1236 }
1237}
1238
1239impl<T> Mutator<T> for RcMutator<T> {
1240 fn mutate(&mut self, value: &mut T) {
1241 (self.function.borrow_mut())(value)
1242 }
1243
1244 fn into_box(self) -> BoxMutator<T>
1245 where
1246 T: 'static,
1247 {
1248 BoxMutator::new(move |t| self.function.borrow_mut()(t))
1249 }
1250
1251 fn into_rc(self) -> RcMutator<T>
1252 where
1253 T: 'static,
1254 {
1255 self
1256 }
1257
1258 // do NOT override Mutator::into_arc() because RcMutator is not Send + Sync
1259 // and calling RcMutator::into_arc() will cause a compile error
1260
1261 fn into_fn(self) -> impl FnMut(&mut T)
1262 where
1263 Self: Sized + 'static,
1264 T: 'static,
1265 {
1266 move |t| self.function.borrow_mut()(t)
1267 }
1268
1269 fn to_box(&self) -> BoxMutator<T>
1270 where
1271 Self: Sized + 'static,
1272 T: 'static,
1273 {
1274 let self_fn = self.function.clone();
1275 BoxMutator::new(move |t| self_fn.borrow_mut()(t))
1276 }
1277
1278 fn to_rc(&self) -> RcMutator<T>
1279 where
1280 Self: Sized + 'static,
1281 T: 'static,
1282 {
1283 self.clone()
1284 }
1285
1286 // do NOT override Mutator::to_arc() because RcMutator is not Send + Sync
1287 // and calling RcMutator::to_arc() will cause a compile error
1288
1289 fn to_fn(&self) -> impl FnMut(&mut T)
1290 where
1291 Self: Sized + 'static,
1292 T: 'static,
1293 {
1294 let self_fn = self.function.clone();
1295 move |t| self_fn.borrow_mut()(t)
1296 }
1297}
1298
1299impl<T> Clone for RcMutator<T> {
1300 /// Clones the RcMutator
1301 ///
1302 /// Creates a new RcMutator that shares the underlying function with the
1303 /// original instance.
1304 fn clone(&self) -> Self {
1305 RcMutator {
1306 function: self.function.clone(),
1307 }
1308 }
1309}
1310
1311// ============================================================================
1312// 5. RcConditionalMutator - Rc-based Conditional Mutator
1313// ============================================================================
1314
1315/// RcConditionalMutator struct
1316///
1317/// A single-threaded conditional mutator that only executes when a predicate is
1318/// satisfied. Uses `RcMutator` and `RcPredicate` for shared ownership within a
1319/// single thread.
1320///
1321/// This type is typically created by calling `RcMutator::when()` and is
1322/// designed to work with the `or_else()` method to create if-then-else logic.
1323///
1324/// # Features
1325///
1326/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1327/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1328/// - **Conditional Execution**: Only mutates when predicate returns `true`
1329/// - **No Lock Overhead**: More efficient than `ArcConditionalMutator`
1330///
1331/// # Examples
1332///
1333/// ```rust
1334/// use prism3_function::{Mutator, RcMutator};
1335///
1336/// let conditional = RcMutator::new(|x: &mut i32| *x *= 2)
1337/// .when(|x: &i32| *x > 0);
1338///
1339/// let conditional_clone = conditional.clone();
1340///
1341/// let mut value = 5;
1342/// let mut m = conditional;
1343/// m.mutate(&mut value);
1344/// assert_eq!(value, 10);
1345/// ```
1346///
1347/// # Author
1348///
1349/// Haixing Hu
1350pub struct RcConditionalMutator<T> {
1351 mutator: RcMutator<T>,
1352 predicate: RcPredicate<T>,
1353}
1354impl<T> Mutator<T> for RcConditionalMutator<T>
1355where
1356 T: 'static,
1357{
1358 fn mutate(&mut self, value: &mut T) {
1359 if self.predicate.test(value) {
1360 self.mutator.mutate(value);
1361 }
1362 }
1363
1364 fn into_box(self) -> BoxMutator<T> {
1365 let pred = self.predicate;
1366 let mut mutator = self.mutator;
1367 BoxMutator::new(move |t| {
1368 if pred.test(t) {
1369 mutator.mutate(t);
1370 }
1371 })
1372 }
1373
1374 fn into_rc(self) -> RcMutator<T> {
1375 let pred = self.predicate;
1376 let mut mutator = self.mutator;
1377 RcMutator::new(move |t| {
1378 if pred.test(t) {
1379 mutator.mutate(t);
1380 }
1381 })
1382 }
1383
1384 // do NOT override Mutator::into_arc() because RcConditionalMutator is not Send + Sync
1385 // and calling RcConditionalMutator::into_arc() will cause a compile error
1386
1387 fn into_fn(self) -> impl FnMut(&mut T) {
1388 let pred = self.predicate;
1389 let mut mutator = self.mutator;
1390 move |t: &mut T| {
1391 if pred.test(t) {
1392 mutator.mutate(t);
1393 }
1394 }
1395 }
1396
1397 fn to_box(&self) -> BoxMutator<T>
1398 where
1399 Self: Sized + 'static,
1400 T: 'static,
1401 {
1402 self.clone().into_box()
1403 }
1404
1405 fn to_rc(&self) -> RcMutator<T>
1406 where
1407 Self: Sized + 'static,
1408 T: 'static,
1409 {
1410 self.clone().into_rc()
1411 }
1412
1413 // do NOT override Mutator::to_arc() because RcMutator is not Send + Sync
1414 // and calling RcMutator::to_arc() will cause a compile error
1415
1416 fn to_fn(&self) -> impl FnMut(&mut T)
1417 where
1418 Self: Sized + 'static,
1419 T: 'static,
1420 {
1421 self.clone().into_fn()
1422 }
1423}
1424
1425impl<T> RcConditionalMutator<T>
1426where
1427 T: 'static,
1428{
1429 /// Adds an else branch (single-threaded shared version)
1430 ///
1431 /// Executes the original mutator when the condition is satisfied, otherwise
1432 /// executes else_mutator.
1433 ///
1434 /// # Parameters
1435 ///
1436 /// * `else_mutator` - The mutator for the else branch. **Note: This parameter
1437 /// is passed by value and will transfer ownership.** If you need to preserve
1438 /// the original mutator, clone it first (if it implements `Clone`). Can be:
1439 /// - A closure: `|x: &mut T|`
1440 /// - An `RcMutator<T>`
1441 /// - A `BoxMutator<T>`
1442 /// - Any type implementing `Mutator<T>`
1443 ///
1444 /// # Returns
1445 ///
1446 /// Returns the composed `RcMutator<T>`
1447 ///
1448 /// # Examples
1449 ///
1450 /// ## Using a closure (recommended)
1451 ///
1452 /// ```rust
1453 /// use prism3_function::{Mutator, RcMutator};
1454 ///
1455 /// let mut mutator = RcMutator::new(|x: &mut i32| *x *= 2)
1456 /// .when(|x: &i32| *x > 0)
1457 /// .or_else(|x: &mut i32| *x -= 1);
1458 ///
1459 /// let mut positive = 5;
1460 /// mutator.mutate(&mut positive);
1461 /// assert_eq!(positive, 10);
1462 ///
1463 /// let mut negative = -5;
1464 /// mutator.mutate(&mut negative);
1465 /// assert_eq!(negative, -6);
1466 /// ```
1467 pub fn or_else<C>(self, else_mutator: C) -> RcMutator<T>
1468 where
1469 C: Mutator<T> + 'static,
1470 {
1471 let pred = self.predicate;
1472 let mut then_mut = self.mutator;
1473 let mut else_mut = else_mutator;
1474
1475 RcMutator::new(move |t: &mut T| {
1476 if pred.test(t) {
1477 then_mut.mutate(t);
1478 } else {
1479 else_mut.mutate(t);
1480 }
1481 })
1482 }
1483}
1484
1485impl<T> Clone for RcConditionalMutator<T> {
1486 /// Clones the conditional mutator
1487 ///
1488 /// Creates a new instance that shares the underlying mutator and predicate
1489 /// with the original instance.
1490 fn clone(&self) -> Self {
1491 RcConditionalMutator {
1492 mutator: self.mutator.clone(),
1493 predicate: self.predicate.clone(),
1494 }
1495 }
1496}
1497
1498// ============================================================================
1499// 6. ArcMutator - Thread-Safe Shared Ownership Implementation
1500// ============================================================================
1501
1502/// ArcMutator struct
1503///
1504/// A mutator implementation based on `Arc<Mutex<dyn FnMut(&mut T) + Send>>`
1505/// for thread-safe shared ownership scenarios. This type allows the mutator
1506/// to be safely shared and used across multiple threads.
1507///
1508/// # Features
1509///
1510/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1511/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1512/// - **Interior Mutability**: Uses `Mutex` for safe concurrent mutations
1513/// - **Mutable State**: Can modify captured environment via `FnMut`
1514/// - **Chainable**: Method chaining via `&self` (non-consuming)
1515///
1516/// # Use Cases
1517///
1518/// Choose `ArcMutator` when:
1519/// - The mutator needs to be shared across multiple threads
1520/// - Concurrent task processing (e.g., thread pools)
1521/// - Thread safety is required (Send + Sync)
1522///
1523/// # Examples
1524///
1525/// ```rust
1526/// use prism3_function::{Mutator, ArcMutator};
1527///
1528/// let mutator = ArcMutator::new(|x: &mut i32| *x *= 2);
1529/// let clone = mutator.clone();
1530///
1531/// let mut value = 5;
1532/// let mut m = mutator;
1533/// m.mutate(&mut value);
1534/// assert_eq!(value, 10);
1535/// ```
1536///
1537/// # Author
1538///
1539/// Haixing Hu
1540pub struct ArcMutator<T> {
1541 function: ArcMutMutatorFn<T>,
1542}
1543
1544impl<T> ArcMutator<T>
1545where
1546 T: Send + 'static,
1547{
1548 /// Creates a new ArcMutator
1549 ///
1550 /// # Parameters
1551 ///
1552 /// * `f` - The closure to wrap
1553 ///
1554 /// # Returns
1555 ///
1556 /// Returns a new `ArcMutator<T>` instance
1557 ///
1558 /// # Examples
1559 ///
1560 /// ```rust
1561 /// use prism3_function::{Mutator, ArcMutator};
1562 ///
1563 /// let mutator = ArcMutator::new(|x: &mut i32| *x += 1);
1564 /// let mut value = 5;
1565 /// let mut m = mutator;
1566 /// m.mutate(&mut value);
1567 /// assert_eq!(value, 6);
1568 /// ```
1569 pub fn new<F>(f: F) -> Self
1570 where
1571 F: FnMut(&mut T) + Send + 'static,
1572 {
1573 ArcMutator {
1574 function: Arc::new(Mutex::new(f)),
1575 }
1576 }
1577
1578 /// Creates a no-op mutator
1579 ///
1580 /// Returns a mutator that performs no operation.
1581 ///
1582 /// # Returns
1583 ///
1584 /// Returns a no-op mutator
1585 ///
1586 /// # Examples
1587 ///
1588 /// ```rust
1589 /// use prism3_function::{Mutator, ArcMutator};
1590 ///
1591 /// let noop = ArcMutator::<i32>::noop();
1592 /// let mut value = 42;
1593 /// let mut m = noop;
1594 /// m.mutate(&mut value);
1595 /// assert_eq!(value, 42); // Value unchanged
1596 /// ```
1597 pub fn noop() -> Self {
1598 ArcMutator::new(|_| {})
1599 }
1600
1601 /// Chains another ArcMutator in sequence
1602 ///
1603 /// Returns a new mutator that first executes the current operation, then
1604 /// executes the next operation. Borrows &self, does not consume the
1605 /// original mutator.
1606 ///
1607 /// # Parameters
1608 ///
1609 /// * `next` - The mutator to execute after the current operation
1610 ///
1611 /// # Returns
1612 ///
1613 /// Returns a new composed `ArcMutator<T>`
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```rust
1618 /// use prism3_function::{Mutator, ArcMutator};
1619 ///
1620 /// let first = ArcMutator::new(|x: &mut i32| *x *= 2);
1621 /// let second = ArcMutator::new(|x: &mut i32| *x += 10);
1622 ///
1623 /// let chained = first.and_then(&second);
1624 ///
1625 /// // first and second are still usable
1626 /// let mut value = 5;
1627 /// let mut m = chained;
1628 /// m.mutate(&mut value);
1629 /// assert_eq!(value, 20); // (5 * 2) + 10
1630 /// ```
1631 pub fn and_then(&self, next: &ArcMutator<T>) -> ArcMutator<T> {
1632 let first = Arc::clone(&self.function);
1633 let second = Arc::clone(&next.function);
1634 ArcMutator {
1635 function: Arc::new(Mutex::new(move |t: &mut T| {
1636 (first.lock().unwrap())(t);
1637 (second.lock().unwrap())(t);
1638 })),
1639 }
1640 }
1641
1642 /// Creates a conditional mutator (thread-safe version)
1643 ///
1644 /// Returns a mutator that only executes when a predicate is satisfied.
1645 ///
1646 /// # Parameters
1647 ///
1648 /// * `predicate` - The condition to check. **Note: This parameter is passed
1649 /// by value and will transfer ownership.** If you need to preserve the
1650 /// original predicate, clone it first (if it implements `Clone`).
1651 /// Must be `Send + Sync`, can be:
1652 /// - A closure: `|x: &T| -> bool` (requires `Send + Sync`)
1653 /// - A function pointer: `fn(&T) -> bool`
1654 /// - An `ArcPredicate<T>`
1655 /// - Any type implementing `Predicate<T> + Send + Sync`
1656 ///
1657 /// # Returns
1658 ///
1659 /// Returns `ArcConditionalMutator<T>`
1660 ///
1661 /// # Examples
1662 ///
1663 /// ```rust
1664 /// use prism3_function::{Mutator, ArcMutator};
1665 ///
1666 /// let mutator = ArcMutator::new(|x: &mut i32| *x *= 2);
1667 /// let conditional = mutator.when(|x: &i32| *x > 0);
1668 ///
1669 /// let conditional_clone = conditional.clone();
1670 ///
1671 /// let mut positive = 5;
1672 /// let mut m = conditional;
1673 /// m.mutate(&mut positive);
1674 /// assert_eq!(positive, 10);
1675 /// ```
1676 pub fn when<P>(&self, predicate: P) -> ArcConditionalMutator<T>
1677 where
1678 P: Predicate<T> + Send + Sync + 'static,
1679 T: Send + Sync,
1680 {
1681 ArcConditionalMutator {
1682 mutator: self.clone(),
1683 predicate: predicate.into_arc(),
1684 }
1685 }
1686}
1687
1688impl<T> Mutator<T> for ArcMutator<T> {
1689 fn mutate(&mut self, value: &mut T) {
1690 (self.function.lock().unwrap())(value)
1691 }
1692
1693 fn into_box(self) -> BoxMutator<T>
1694 where
1695 T: 'static,
1696 {
1697 BoxMutator::new(move |t| self.function.lock().unwrap()(t))
1698 }
1699
1700 fn into_rc(self) -> RcMutator<T>
1701 where
1702 T: 'static,
1703 {
1704 RcMutator::new(move |t| self.function.lock().unwrap()(t))
1705 }
1706
1707 fn into_arc(self) -> ArcMutator<T>
1708 where
1709 T: Send + 'static,
1710 {
1711 self
1712 }
1713
1714 fn into_fn(self) -> impl FnMut(&mut T)
1715 where
1716 Self: Sized + 'static,
1717 T: 'static,
1718 {
1719 move |t| self.function.lock().unwrap()(t)
1720 }
1721
1722 fn to_box(&self) -> BoxMutator<T>
1723 where
1724 Self: Sized + 'static,
1725 T: 'static,
1726 {
1727 let self_fn = self.function.clone();
1728 BoxMutator::new(move |t| self_fn.lock().unwrap()(t))
1729 }
1730
1731 fn to_rc(&self) -> RcMutator<T>
1732 where
1733 Self: Sized + 'static,
1734 T: 'static,
1735 {
1736 let self_fn = self.function.clone();
1737 RcMutator::new(move |t| self_fn.lock().unwrap()(t))
1738 }
1739
1740 fn to_arc(&self) -> ArcMutator<T>
1741 where
1742 Self: Sized + Send + 'static,
1743 T: Send + 'static,
1744 {
1745 self.clone()
1746 }
1747
1748 fn to_fn(&self) -> impl FnMut(&mut T)
1749 where
1750 Self: Sized + 'static,
1751 T: 'static,
1752 {
1753 let self_fn = self.function.clone();
1754 move |t| self_fn.lock().unwrap()(t)
1755 }
1756}
1757
1758impl<T> Clone for ArcMutator<T> {
1759 /// Clones the ArcMutator
1760 ///
1761 /// Creates a new ArcMutator that shares the underlying function with the
1762 /// original instance.
1763 fn clone(&self) -> Self {
1764 ArcMutator {
1765 function: self.function.clone(),
1766 }
1767 }
1768}
1769
1770// ============================================================================
1771// 7. ArcConditionalMutator - Arc-based Conditional Mutator
1772// ============================================================================
1773
1774/// ArcConditionalMutator struct
1775///
1776/// A thread-safe conditional mutator that only executes when a predicate is
1777/// satisfied. Uses `ArcMutator` and `ArcPredicate` for shared ownership across
1778/// threads.
1779///
1780/// This type is typically created by calling `ArcMutator::when()` and is
1781/// designed to work with the `or_else()` method to create if-then-else logic.
1782///
1783/// # Features
1784///
1785/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1786/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1787/// - **Conditional Execution**: Only mutates when predicate returns `true`
1788/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1789///
1790/// # Examples
1791///
1792/// ```rust
1793/// use prism3_function::{Mutator, ArcMutator};
1794///
1795/// let conditional = ArcMutator::new(|x: &mut i32| *x *= 2)
1796/// .when(|x: &i32| *x > 0);
1797///
1798/// let conditional_clone = conditional.clone();
1799///
1800/// let mut value = 5;
1801/// let mut m = conditional;
1802/// m.mutate(&mut value);
1803/// assert_eq!(value, 10);
1804/// ```
1805///
1806/// # Author
1807///
1808/// Haixing Hu
1809pub struct ArcConditionalMutator<T> {
1810 mutator: ArcMutator<T>,
1811 predicate: ArcPredicate<T>,
1812}
1813impl<T> Mutator<T> for ArcConditionalMutator<T>
1814where
1815 T: Send + 'static,
1816{
1817 fn mutate(&mut self, value: &mut T) {
1818 if self.predicate.test(value) {
1819 self.mutator.mutate(value);
1820 }
1821 }
1822
1823 fn into_box(self) -> BoxMutator<T>
1824 where
1825 T: 'static,
1826 {
1827 let pred = self.predicate;
1828 let mut mutator = self.mutator;
1829 BoxMutator::new(move |t| {
1830 if pred.test(t) {
1831 mutator.mutate(t);
1832 }
1833 })
1834 }
1835
1836 fn into_rc(self) -> RcMutator<T>
1837 where
1838 T: 'static,
1839 {
1840 let pred = self.predicate.to_rc();
1841 let mutator = self.mutator.into_rc();
1842 let mut mutator_fn = mutator;
1843 RcMutator::new(move |t| {
1844 if pred.test(t) {
1845 mutator_fn.mutate(t);
1846 }
1847 })
1848 }
1849
1850 fn into_arc(self) -> ArcMutator<T>
1851 where
1852 T: Send + 'static,
1853 {
1854 let pred = self.predicate;
1855 let mut mutator = self.mutator;
1856 ArcMutator::new(move |t| {
1857 if pred.test(t) {
1858 mutator.mutate(t);
1859 }
1860 })
1861 }
1862
1863 fn into_fn(self) -> impl FnMut(&mut T)
1864 where
1865 T: 'static,
1866 {
1867 let pred = self.predicate;
1868 let mut mutator = self.mutator;
1869 move |t: &mut T| {
1870 if pred.test(t) {
1871 mutator.mutate(t);
1872 }
1873 }
1874 }
1875
1876 fn to_box(&self) -> BoxMutator<T>
1877 where
1878 Self: Sized + 'static,
1879 T: 'static,
1880 {
1881 self.clone().into_box()
1882 }
1883
1884 fn to_rc(&self) -> RcMutator<T>
1885 where
1886 Self: Sized + 'static,
1887 T: 'static,
1888 {
1889 self.clone().into_rc()
1890 }
1891
1892 fn to_arc(&self) -> ArcMutator<T>
1893 where
1894 Self: Sized + 'static,
1895 T: 'static,
1896 {
1897 self.clone().into_arc()
1898 }
1899
1900 fn to_fn(&self) -> impl FnMut(&mut T)
1901 where
1902 Self: Sized + 'static,
1903 T: 'static,
1904 {
1905 self.clone().into_fn()
1906 }
1907}
1908
1909impl<T> ArcConditionalMutator<T>
1910where
1911 T: Send + 'static,
1912{
1913 /// Adds an else branch (thread-safe version)
1914 ///
1915 /// Executes the original mutator when the condition is satisfied, otherwise
1916 /// executes else_mutator.
1917 ///
1918 /// # Parameters
1919 ///
1920 /// * `else_mutator` - The mutator for the else branch. **Note: This parameter
1921 /// is passed by value and will transfer ownership.** If you need to preserve
1922 /// the original mutator, clone it first (if it implements `Clone`).
1923 /// Must be `Send`, can be:
1924 /// - A closure: `|x: &mut T|` (must be `Send`)
1925 /// - An `ArcMutator<T>`
1926 /// - A `BoxMutator<T>`
1927 /// - Any type implementing `Mutator<T> + Send`
1928 ///
1929 /// # Returns
1930 ///
1931 /// Returns the composed `ArcMutator<T>`
1932 ///
1933 /// # Examples
1934 ///
1935 /// ## Using a closure (recommended)
1936 ///
1937 /// ```rust
1938 /// use prism3_function::{Mutator, ArcMutator};
1939 ///
1940 /// let mut mutator = ArcMutator::new(|x: &mut i32| *x *= 2)
1941 /// .when(|x: &i32| *x > 0)
1942 /// .or_else(|x: &mut i32| *x -= 1);
1943 ///
1944 /// let mut positive = 5;
1945 /// mutator.mutate(&mut positive);
1946 /// assert_eq!(positive, 10);
1947 ///
1948 /// let mut negative = -5;
1949 /// mutator.mutate(&mut negative);
1950 /// assert_eq!(negative, -6);
1951 /// ```
1952 pub fn or_else<C>(&self, else_mutator: C) -> ArcMutator<T>
1953 where
1954 C: Mutator<T> + Send + 'static,
1955 T: Send + Sync,
1956 {
1957 let pred = self.predicate.clone();
1958 let mut then_mut = self.mutator.clone();
1959 let mut else_mut = else_mutator;
1960 ArcMutator::new(move |t: &mut T| {
1961 if pred.test(t) {
1962 then_mut.mutate(t);
1963 } else {
1964 else_mut.mutate(t);
1965 }
1966 })
1967 }
1968}
1969
1970impl<T> Clone for ArcConditionalMutator<T> {
1971 /// Clones the conditional mutator
1972 ///
1973 /// Creates a new instance that shares the underlying mutator and predicate
1974 /// with the original instance.
1975 fn clone(&self) -> Self {
1976 ArcConditionalMutator {
1977 mutator: self.mutator.clone(),
1978 predicate: self.predicate.clone(),
1979 }
1980 }
1981}
1982
1983// ============================================================================
1984// 8. Implement Mutator trait for closures
1985// ============================================================================
1986
1987impl<T, F> Mutator<T> for F
1988where
1989 F: FnMut(&mut T),
1990{
1991 fn mutate(&mut self, value: &mut T) {
1992 self(value)
1993 }
1994
1995 fn into_box(self) -> BoxMutator<T>
1996 where
1997 Self: Sized + 'static,
1998 T: 'static,
1999 {
2000 BoxMutator::new(self)
2001 }
2002
2003 fn into_rc(self) -> RcMutator<T>
2004 where
2005 Self: Sized + 'static,
2006 T: 'static,
2007 {
2008 RcMutator::new(self)
2009 }
2010
2011 fn into_arc(self) -> ArcMutator<T>
2012 where
2013 Self: Sized + Send + 'static,
2014 T: Send + 'static,
2015 {
2016 ArcMutator::new(self)
2017 }
2018
2019 fn into_fn(self) -> impl FnMut(&mut T)
2020 where
2021 Self: Sized + 'static,
2022 T: 'static,
2023 {
2024 self
2025 }
2026
2027 fn to_box(&self) -> BoxMutator<T>
2028 where
2029 Self: Sized + Clone + 'static,
2030 T: 'static,
2031 {
2032 let cloned = self.clone();
2033 BoxMutator::new(cloned)
2034 }
2035
2036 fn to_rc(&self) -> RcMutator<T>
2037 where
2038 Self: Sized + Clone + 'static,
2039 T: 'static,
2040 {
2041 let cloned = self.clone();
2042 RcMutator::new(cloned)
2043 }
2044
2045 fn to_arc(&self) -> ArcMutator<T>
2046 where
2047 Self: Sized + Clone + Send + 'static,
2048 T: Send + 'static,
2049 {
2050 let cloned = self.clone();
2051 ArcMutator::new(cloned)
2052 }
2053
2054 fn to_fn(&self) -> impl FnMut(&mut T)
2055 where
2056 Self: Sized + Clone + 'static,
2057 T: 'static,
2058 {
2059 self.clone()
2060 }
2061}
2062
2063// ============================================================================
2064// 9. Provide extension methods for closures
2065// ============================================================================
2066
2067// ============================================================================
2068// 7. Provide extension methods for closures
2069// ============================================================================
2070
2071/// Extension trait providing mutator composition methods for closures
2072///
2073/// Provides `and_then` and other composition methods for all closures that
2074/// implement `FnMut(&mut T)`, enabling direct method chaining on closures
2075/// without explicit wrapper types.
2076///
2077/// # Features
2078///
2079/// - **Natural Syntax**: Chain operations directly on closures
2080/// - **Returns BoxMutator**: Composition results are `BoxMutator<T>` for
2081/// continued chaining
2082/// - **Zero Cost**: No overhead when composing closures
2083/// - **Automatic Implementation**: All `FnMut(&mut T)` closures get these
2084/// methods automatically
2085///
2086/// # Examples
2087///
2088/// ```rust
2089/// use prism3_function::{Mutator, FnMutatorOps};
2090///
2091/// let chained = (|x: &mut i32| *x *= 2)
2092/// .and_then(|x: &mut i32| *x += 10);
2093/// let mut value = 5;
2094/// let mut result = chained;
2095/// result.mutate(&mut value);
2096/// assert_eq!(value, 20); // (5 * 2) + 10
2097/// ```
2098///
2099/// # Author
2100///
2101/// Haixing Hu
2102pub trait FnMutatorOps<T>: FnMut(&mut T) + Sized {
2103 /// Chains another mutator in sequence
2104 ///
2105 /// Returns a new mutator that first executes the current operation, then
2106 /// executes the next operation. Consumes the current closure and returns
2107 /// `BoxMutator<T>`.
2108 ///
2109 /// # Parameters
2110 ///
2111 /// * `next` - The mutator to execute after the current operation. **Note:
2112 /// This parameter is passed by value and will transfer ownership.** If you
2113 /// need to preserve the original mutator, clone it first (if it implements
2114 /// `Clone`). Can be:
2115 /// - A closure: `|x: &mut T|`
2116 /// - A `BoxMutator<T>`
2117 /// - An `ArcMutator<T>`
2118 /// - An `RcMutator<T>`
2119 /// - Any type implementing `Mutator<T>`
2120 ///
2121 /// # Returns
2122 ///
2123 /// Returns the composed `BoxMutator<T>`
2124 ///
2125 /// # Examples
2126 ///
2127 /// ```rust
2128 /// use prism3_function::{Mutator, FnMutatorOps};
2129 ///
2130 /// let chained = (|x: &mut i32| *x *= 2)
2131 /// .and_then(|x: &mut i32| *x += 10)
2132 /// .and_then(|x: &mut i32| println!("Result: {}", x));
2133 ///
2134 /// let mut value = 5;
2135 /// let mut result = chained;
2136 /// result.mutate(&mut value); // Prints: Result: 20
2137 /// assert_eq!(value, 20);
2138 /// ```
2139 fn and_then<C>(self, next: C) -> BoxMutator<T>
2140 where
2141 Self: 'static,
2142 C: Mutator<T> + 'static,
2143 T: 'static,
2144 {
2145 let mut first = self;
2146 let mut second = next.into_fn();
2147 BoxMutator::new(move |t| {
2148 (first)(t);
2149 second(t);
2150 })
2151 }
2152}
2153
2154/// Implements FnMutatorOps for all closure types
2155impl<T, F> FnMutatorOps<T> for F where F: FnMut(&mut T) {}