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