Skip to main content

qubit_function/functions/
mutating_function.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # MutatingFunction Types
10//!
11//! Provides Java-like `MutatingFunction` interface implementations for
12//! performing operations that accept a mutable reference and return a result.
13//!
14//! It is similar to the `Fn(&mut T) -> R` trait in the standard library.
15//!
16//! This module provides a unified `MutatingFunction` trait and three concrete
17//! implementations based on different ownership models:
18//!
19//! - **`BoxMutatingFunction<T, R>`**: Box-based single ownership
20//!   implementation
21//! - **`ArcMutatingFunction<T, R>`**: Arc-based thread-safe shared ownership
22//!   implementation
23//! - **`RcMutatingFunction<T, R>`**: Rc-based single-threaded shared
24//!   ownership implementation
25//!
26//! # Design Philosophy
27//!
28//! `MutatingFunction` bridges the gap between `Function` and `Mutator`:
29//!
30//! - **Function**: `Fn(&T) -> R` - reads input, returns result
31//! - **Mutator**: `Fn(&mut T)` - modifies input, no return
32//! - **MutatingFunction**: `Fn(&mut T) -> R` - modifies input AND returns
33//!   result
34//!
35//! ## Comparison with Related Types
36//!
37//! | Type | Input | Modifies? | Returns? | Use Cases |
38//! |------|-------|-----------|----------|-----------|
39//! | **Function** | `&T` | ❌ | ✅ | Read-only transform |
40//! | **Mutator** | `&mut T` | ✅ | ❌ | In-place modification |
41//! | **MutatingFunction** | `&mut T` | ✅ | ✅ | Modify + return info |
42//! | **Transformer** | `T` | N/A | ✅ | Consume + transform |
43//!
44//! **Key Insight**: Use `MutatingFunction` when you need to both modify the
45//! input and return information about the modification or the previous state.
46//!
47//! # Comparison Table
48//!
49//! | Feature          | Box | Arc | Rc |
50//! |------------------|-----|-----|----|
51//! | Ownership        | Single | Shared | Shared |
52//! | Cloneable        | ❌ | ✅ | ✅ |
53//! | Thread-Safe      | ❌ | ✅ | ❌ |
54//! | Interior Mut.    | N/A | N/A | N/A |
55//! | `and_then` API   | `self` | `&self` | `&self` |
56//! | Lock Overhead    | None | None | None |
57//!
58//! # Use Cases
59//!
60//! ## Common Scenarios
61//!
62//! - **Atomic operations**: Increment counter and return new value
63//! - **Cache updates**: Update cache and return old value
64//! - **Validation**: Validate and fix data, return validation result
65//! - **Event handlers**: Process event and return whether to continue
66//! - **State machines**: Transition state and return transition info
67//!
68//! # Examples
69//!
70//! ## Basic Usage
71//!
72//! ```rust
73//! use qubit_function::{BoxMutatingFunction, MutatingFunction};
74//!
75//! // Increment counter and return new value
76//! let incrementer = BoxMutatingFunction::new(|x: &mut i32| {
77//!     *x += 1;
78//!     *x
79//! });
80//!
81//! let mut value = 5;
82//! let result = incrementer.apply(&mut value);
83//! assert_eq!(value, 6);
84//! assert_eq!(result, 6);
85//! ```
86//!
87//! ## Method Chaining
88//!
89//! ```rust
90//! use qubit_function::{BoxMutatingFunction, MutatingFunction};
91//!
92//! let chained = BoxMutatingFunction::new(|x: &mut i32| {
93//!     *x *= 2;
94//!     *x
95//! })
96//! .and_then(|x: &mut i32| {
97//!     *x += 10;
98//!     *x
99//! });
100//!
101//! let mut value = 5;
102//! let result = chained.apply(&mut value);
103//! assert_eq!(value, 20); // (5 * 2) + 10
104//! assert_eq!(result, 20);
105//! ```
106//!
107//! ## Cache Update Pattern
108//!
109//! ```rust
110//! use qubit_function::{BoxMutatingFunction, MutatingFunction};
111//! use std::collections::HashMap;
112//!
113//! let updater = BoxMutatingFunction::new(
114//!     |cache: &mut HashMap<String, i32>| {
115//!         cache.insert("key".to_string(), 42)
116//!     }
117//! );
118//!
119//! let mut cache = HashMap::new();
120//! cache.insert("key".to_string(), 10);
121//! let old_value = updater.apply(&mut cache);
122//! assert_eq!(old_value, Some(10));
123//! assert_eq!(cache.get("key"), Some(&42));
124//! ```
125//!
126//! # Author
127//!
128//! Haixing Hu
129use std::rc::Rc;
130use std::sync::Arc;
131
132use crate::functions::{
133    function::Function,
134    macros::{
135        impl_box_conditional_function,
136        impl_box_function_methods,
137        impl_conditional_function_clone,
138        impl_conditional_function_debug_display,
139        impl_fn_ops_trait,
140        impl_function_clone,
141        impl_function_common_methods,
142        impl_function_debug_display,
143        impl_function_identity_method,
144        impl_shared_conditional_function,
145        impl_shared_function_methods,
146    },
147    mutating_function_once::BoxMutatingFunctionOnce,
148};
149use crate::macros::{
150    impl_arc_conversions,
151    impl_box_conversions,
152    impl_closure_trait,
153    impl_rc_conversions,
154};
155use crate::predicates::predicate::{
156    ArcPredicate,
157    BoxPredicate,
158    Predicate,
159    RcPredicate,
160};
161
162// =======================================================================
163// 1. MutatingFunction Trait - Unified Interface
164// =======================================================================
165
166/// MutatingFunction trait - Unified mutating function interface
167///
168/// It is similar to the `Fn(&mut T) -> R` trait in the standard library.
169///
170/// Defines the core behavior of all mutating function types. Performs
171/// operations that accept a mutable reference, potentially modify it, and
172/// return a result.
173///
174/// This trait is automatically implemented by:
175/// - All closures implementing `Fn(&mut T) -> R`
176/// - `BoxMutatingFunction<T, R>`, `ArcMutatingFunction<T, R>`, and
177///   `RcMutatingFunction<T, R>`
178///
179/// # Design Rationale
180///
181/// The trait provides a unified abstraction over different ownership models
182/// for operations that both modify input and return results. This is useful
183/// for scenarios where you need to:
184/// - Update state and return information about the update
185/// - Perform atomic-like operations (modify and return)
186/// - Implement event handlers that modify state and signal continuation
187///
188/// # Features
189///
190/// - **Unified Interface**: All mutating function types share the same
191///   `apply` method signature
192/// - **Automatic Implementation**: Closures automatically implement this
193///   trait
194/// - **Type Conversions**: Easy conversion between ownership models
195/// - **Generic Programming**: Write functions that work with any mutating
196///   function type
197///
198/// # Examples
199///
200/// ## Generic Function
201///
202/// ```rust
203/// use qubit_function::{MutatingFunction, BoxMutatingFunction};
204///
205/// fn apply_and_log<F: MutatingFunction<i32, i32>>(
206///     func: &F,
207///     value: i32
208/// ) -> i32 {
209///     let mut val = value;
210///     let result = func.apply(&mut val);
211///     println!("Modified: {} -> {}, returned: {}", value, val, result);
212///     result
213/// }
214///
215/// let incrementer = BoxMutatingFunction::new(|x: &mut i32| {
216///     *x += 1;
217///     *x
218/// });
219/// assert_eq!(apply_and_log(&incrementer, 5), 6);
220/// ```
221///
222/// ## Type Conversion
223///
224/// ```rust
225/// use qubit_function::MutatingFunction;
226///
227/// let closure = |x: &mut i32| {
228///     *x *= 2;
229///     *x
230/// };
231///
232/// // Convert to different ownership models
233/// let box_func = closure.into_box();
234/// // let rc_func = closure.into_rc();  // closure moved
235/// // let arc_func = closure.into_arc(); // closure moved
236/// ```
237///
238/// # Author
239///
240/// Haixing Hu
241pub trait MutatingFunction<T, R> {
242    /// Applies the function to the mutable reference and returns a result
243    ///
244    /// Executes an operation on the given mutable reference, potentially
245    /// modifying it, and returns a result value.
246    ///
247    /// # Parameters
248    ///
249    /// * `t` - A mutable reference to the input value
250    ///
251    /// # Returns
252    ///
253    /// The computed result value
254    ///
255    /// # Examples
256    ///
257    /// ```rust
258    /// use qubit_function::{MutatingFunction, BoxMutatingFunction};
259    ///
260    /// let func = BoxMutatingFunction::new(|x: &mut i32| {
261    ///     let old = *x;
262    ///     *x += 1;
263    ///     old
264    /// });
265    ///
266    /// let mut value = 5;
267    /// let old_value = func.apply(&mut value);
268    /// assert_eq!(old_value, 5);
269    /// assert_eq!(value, 6);
270    /// ```
271    fn apply(&self, t: &mut T) -> R;
272
273    /// Convert this mutating function into a `BoxMutatingFunction<T, R>`.
274    ///
275    /// This consuming conversion takes ownership of `self` and returns a
276    /// boxed implementation that forwards calls to the original function.
277    /// Types that can provide a more efficient conversion may override the
278    /// default implementation.
279    ///
280    /// # Consumption
281    ///
282    /// This method consumes the function: the original value will no longer
283    /// be available after the call. For cloneable functions call `.clone()`
284    /// before converting if you need to retain the original instance.
285    ///
286    /// # Returns
287    ///
288    /// A `BoxMutatingFunction<T, R>` that forwards to the original function.
289    ///
290    /// # Examples
291    ///
292    /// ```rust
293    /// use qubit_function::MutatingFunction;
294    ///
295    /// let closure = |x: &mut i32| {
296    ///     *x *= 2;
297    ///     *x
298    /// };
299    /// let mut boxed = closure.into_box();
300    /// let mut value = 5;
301    /// assert_eq!(boxed.apply(&mut value), 10);
302    /// ```
303    fn into_box(self) -> BoxMutatingFunction<T, R>
304    where
305        Self: Sized + 'static,
306    {
307        BoxMutatingFunction::new(move |t| self.apply(t))
308    }
309
310    /// Convert this mutating function into an `RcMutatingFunction<T, R>`.
311    ///
312    /// This consuming conversion takes ownership of `self` and returns an
313    /// `Rc`-backed function that forwards calls to the original. Override to
314    /// provide a more direct or efficient conversion when available.
315    ///
316    /// # Consumption
317    ///
318    /// This method consumes the function. If you need to keep the original
319    /// instance, clone it prior to calling this method.
320    ///
321    /// # Returns
322    ///
323    /// An `RcMutatingFunction<T, R>` forwarding to the original function.
324    ///
325    /// # Examples
326    ///
327    /// ```rust
328    /// use qubit_function::MutatingFunction;
329    ///
330    /// let closure = |x: &mut i32| {
331    ///     *x *= 2;
332    ///     *x
333    /// };
334    /// let mut rc = closure.into_rc();
335    /// let mut value = 5;
336    /// assert_eq!(rc.apply(&mut value), 10);
337    /// ```
338    fn into_rc(self) -> RcMutatingFunction<T, R>
339    where
340        Self: Sized + 'static,
341    {
342        RcMutatingFunction::new(move |t| self.apply(t))
343    }
344
345    /// Convert this mutating function into an `ArcMutatingFunction<T, R>`.
346    ///
347    /// This consuming conversion takes ownership of `self` and returns an
348    /// `Arc`-wrapped, thread-safe function. Types may override the default
349    /// implementation to provide a more efficient conversion.
350    ///
351    /// # Consumption
352    ///
353    /// This method consumes the function. Clone the instance first if you
354    /// need to retain the original for further use.
355    ///
356    /// # Returns
357    ///
358    /// An `ArcMutatingFunction<T, R>` that forwards to the original
359    /// function.
360    ///
361    /// # Examples
362    ///
363    /// ```rust
364    /// use qubit_function::MutatingFunction;
365    ///
366    /// let closure = |x: &mut i32| {
367    ///     *x *= 2;
368    ///     *x
369    /// };
370    /// let mut arc = closure.into_arc();
371    /// let mut value = 5;
372    /// assert_eq!(arc.apply(&mut value), 10);
373    /// ```
374    fn into_arc(self) -> ArcMutatingFunction<T, R>
375    where
376        Self: Sized + Send + Sync + 'static,
377    {
378        ArcMutatingFunction::new(move |t| self.apply(t))
379    }
380
381    /// Consume the function and return an `Fn(&mut T) -> R` closure.
382    ///
383    /// The returned closure forwards calls to the original function and is
384    /// suitable for use with iterator adapters or other contexts expecting
385    /// closures.
386    ///
387    /// # Consumption
388    ///
389    /// This method consumes the function. The original instance will not be
390    /// available after calling this method.
391    ///
392    /// # Returns
393    ///
394    /// A closure implementing `Fn(&mut T) -> R` which forwards to the
395    /// original function.
396    ///
397    /// # Examples
398    ///
399    /// ```rust
400    /// use qubit_function::{MutatingFunction, BoxMutatingFunction};
401    ///
402    /// let func = BoxMutatingFunction::new(|x: &mut i32| {
403    ///     *x *= 2;
404    ///     *x
405    /// });
406    /// let closure = func.into_fn();
407    /// let mut value = 5;
408    /// assert_eq!(closure(&mut value), 10);
409    /// ```
410    fn into_fn(self) -> impl Fn(&mut T) -> R
411    where
412        Self: Sized + 'static,
413    {
414        move |t| self.apply(t)
415    }
416
417    /// Convert to MutatingFunctionOnce
418    ///
419    /// **⚠️ Consumes `self`**: The original function will be unavailable
420    /// after calling this method.
421    ///
422    /// Converts a reusable mutating function to a one-time function that
423    /// consumes itself on use. This enables passing `MutatingFunction` to
424    /// functions that require `MutatingFunctionOnce`.
425    ///
426    /// # Returns
427    ///
428    /// Returns a `BoxMutatingFunctionOnce<T, R>`
429    ///
430    /// # Examples
431    ///
432    /// ```rust
433    /// use qubit_function::{MutatingFunctionOnce, MutatingFunction,
434    ///                       BoxMutatingFunction};
435    ///
436    /// fn takes_once<F: MutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
437    ///     let result = func.apply(value);
438    ///     println!("Result: {}", result);
439    /// }
440    ///
441    /// let func = BoxMutatingFunction::new(|x: &mut i32| {
442    ///     *x *= 2;
443    ///     *x
444    /// });
445    /// let mut value = 5;
446    /// takes_once(func.into_once(), &mut value);
447    /// ```
448    fn into_once(self) -> BoxMutatingFunctionOnce<T, R>
449    where
450        Self: Sized + 'static,
451    {
452        BoxMutatingFunctionOnce::new(move |t| self.apply(t))
453    }
454
455    /// Create a non-consuming `BoxMutatingFunction<T, R>` that forwards to
456    /// `self`.
457    ///
458    /// The default implementation clones `self` (requires `Clone`) and
459    /// returns a boxed function that calls the cloned instance. Override this
460    /// method if a more efficient conversion exists.
461    ///
462    /// # Returns
463    ///
464    /// A `BoxMutatingFunction<T, R>` that forwards to a clone of `self`.
465    fn to_box(&self) -> BoxMutatingFunction<T, R>
466    where
467        Self: Sized + Clone + 'static,
468    {
469        self.clone().into_box()
470    }
471
472    /// Create a non-consuming `RcMutatingFunction<T, R>` that forwards to
473    /// `self`.
474    ///
475    /// The default implementation clones `self` (requires `Clone`) and
476    /// returns an `Rc`-backed function that forwards calls to the clone.
477    /// Override to provide a more direct or efficient conversion if needed.
478    ///
479    /// # Returns
480    ///
481    /// An `RcMutatingFunction<T, R>` that forwards to a clone of `self`.
482    fn to_rc(&self) -> RcMutatingFunction<T, R>
483    where
484        Self: Sized + Clone + 'static,
485    {
486        self.clone().into_rc()
487    }
488
489    /// Create a non-consuming `ArcMutatingFunction<T, R>` that forwards to
490    /// `self`.
491    ///
492    /// The default implementation clones `self` (requires
493    /// `Clone + Send + Sync`) and returns an `Arc`-wrapped function that
494    /// forwards calls to the clone. Override when a more efficient conversion
495    /// is available.
496    ///
497    /// # Returns
498    ///
499    /// An `ArcMutatingFunction<T, R>` that forwards to a clone of `self`.
500    fn to_arc(&self) -> ArcMutatingFunction<T, R>
501    where
502        Self: Sized + Clone + Send + Sync + 'static,
503    {
504        self.clone().into_arc()
505    }
506
507    /// Create a boxed `Fn(&mut T) -> R` closure that forwards to `self`.
508    ///
509    /// The default implementation clones `self` (requires `Clone`) and
510    /// returns a boxed closure that invokes the cloned instance. Override to
511    /// provide a more efficient conversion when possible.
512    ///
513    /// # Returns
514    ///
515    /// A closure implementing `Fn(&mut T) -> R` which forwards to the
516    /// original function.
517    fn to_fn(&self) -> impl Fn(&mut T) -> R
518    where
519        Self: Sized + Clone + 'static,
520    {
521        self.clone().into_fn()
522    }
523
524    /// Convert to MutatingFunctionOnce without consuming self
525    ///
526    /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
527    /// Clones the current function and converts the clone to a one-time function.
528    ///
529    /// # Returns
530    ///
531    /// Returns a `BoxMutatingFunctionOnce<T, R>`
532    ///
533    /// # Examples
534    ///
535    /// ```rust
536    /// use qubit_function::{MutatingFunctionOnce, MutatingFunction,
537    ///                       BoxMutatingFunction};
538    ///
539    /// fn takes_once<F: MutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
540    ///     let result = func.apply(value);
541    ///     println!("Result: {}", result);
542    /// }
543    ///
544    /// let func = BoxMutatingFunction::new(|x: &mut i32| {
545    ///     *x *= 2;
546    ///     *x
547    /// });
548    /// let mut value = 5;
549    /// takes_once(func.to_once(), &mut value);
550    /// ```
551    fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
552    where
553        Self: Clone + 'static,
554    {
555        self.clone().into_once()
556    }
557}
558
559// =======================================================================
560// 3. BoxMutatingFunction - Single Ownership Implementation
561// =======================================================================
562
563/// BoxMutatingFunction struct
564///
565/// A mutating function implementation based on `Box<dyn Fn(&mut T) -> R>`
566/// for single ownership scenarios. This is the simplest and most efficient
567/// mutating function type when sharing is not required.
568///
569/// # Features
570///
571/// - **Single Ownership**: Not cloneable, ownership moves on use
572/// - **Zero Overhead**: No reference counting or locking
573/// - **Stateless**: Cannot modify captured environment (uses `Fn` not
574///   `FnMut`)
575/// - **Builder Pattern**: Method chaining consumes `self` naturally
576/// - **Factory Methods**: Convenient constructors for common patterns
577///
578/// # Use Cases
579///
580/// Choose `BoxMutatingFunction` when:
581/// - The function is used for stateless operations
582/// - Building pipelines where ownership naturally flows
583/// - No need to share the function across contexts
584/// - Performance is critical and no sharing overhead is acceptable
585///
586/// # Performance
587///
588/// `BoxMutatingFunction` has the best performance among the three function
589/// types:
590/// - No reference counting overhead
591/// - No lock acquisition or runtime borrow checking
592/// - Direct function call through vtable
593/// - Minimal memory footprint (single pointer)
594///
595/// # Examples
596///
597/// ```rust
598/// use qubit_function::{MutatingFunction, BoxMutatingFunction};
599///
600/// let func = BoxMutatingFunction::new(|x: &mut i32| {
601///     *x *= 2;
602///     *x
603/// });
604/// let mut value = 5;
605/// assert_eq!(func.apply(&mut value), 10);
606/// assert_eq!(value, 10);
607/// ```
608///
609/// # Author
610///
611/// Haixing Hu
612pub struct BoxMutatingFunction<T, R> {
613    function: Box<dyn Fn(&mut T) -> R>,
614    name: Option<String>,
615}
616
617impl<T, R> BoxMutatingFunction<T, R> {
618    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
619    impl_function_common_methods!(
620        BoxMutatingFunction<T, R>,
621        (Fn(&mut T) -> R + 'static),
622        |f| Box::new(f)
623    );
624
625    // Generates: when(), and_then(), compose()
626    impl_box_function_methods!(
627        BoxMutatingFunction<T, R>,
628        BoxConditionalMutatingFunction,
629        Function  // chains a non-mutating function after this mutating function
630    );
631}
632
633// Generates: Debug and Display implementations for BoxMutatingFunction<T, R>
634impl_function_debug_display!(BoxMutatingFunction<T, R>);
635
636// Generates: identity() method for BoxMutatingFunction<T, T>
637impl_function_identity_method!(BoxMutatingFunction<T, T>, mutating);
638
639// Implement MutatingFunction trait for BoxMutatingFunction<T, R>
640impl<T, R> MutatingFunction<T, R> for BoxMutatingFunction<T, R> {
641    fn apply(&self, t: &mut T) -> R {
642        (self.function)(t)
643    }
644
645    // Generates: into_box(), into_rc(), into_fn(), into_once()
646    impl_box_conversions!(
647        BoxMutatingFunction<T, R>,
648        RcMutatingFunction,
649        Fn(&mut T) -> R,
650        BoxMutatingFunctionOnce
651    );
652}
653
654// =======================================================================
655// 4. RcMutatingFunction - Single-Threaded Shared Ownership
656// =======================================================================
657
658/// RcMutatingFunction struct
659///
660/// A mutating function implementation based on `Rc<dyn Fn(&mut T) -> R>` for
661/// single-threaded shared ownership scenarios. This type allows multiple
662/// references to the same function without the overhead of thread safety.
663///
664/// # Features
665///
666/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
667/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
668/// - **Stateless**: Cannot modify captured environment (uses `Fn` not
669///   `FnMut`)
670/// - **Chainable**: Method chaining via `&self` (non-consuming)
671/// - **Performance**: More efficient than `ArcMutatingFunction` (no locking)
672///
673/// # Use Cases
674///
675/// Choose `RcMutatingFunction` when:
676/// - The function needs to be shared within a single thread for stateless
677///   operations
678/// - Thread safety is not required
679/// - Performance is important (avoiding lock overhead)
680///
681/// # Examples
682///
683/// ```rust
684/// use qubit_function::{MutatingFunction, RcMutatingFunction};
685///
686/// let func = RcMutatingFunction::new(|x: &mut i32| {
687///     *x *= 2;
688///     *x
689/// });
690/// let clone = func.clone();
691///
692/// let mut value = 5;
693/// assert_eq!(func.apply(&mut value), 10);
694/// ```
695///
696/// # Author
697///
698/// Haixing Hu
699pub struct RcMutatingFunction<T, R> {
700    function: Rc<dyn Fn(&mut T) -> R>,
701    name: Option<String>,
702}
703
704impl<T, R> RcMutatingFunction<T, R> {
705    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
706    impl_function_common_methods!(
707        RcMutatingFunction<T, R>,
708        (Fn(&mut T) -> R + 'static),
709        |f| Rc::new(f)
710    );
711
712    // Generates: when(), and_then(), compose()
713    impl_shared_function_methods!(
714        RcMutatingFunction<T, R>,
715        RcConditionalMutatingFunction,
716        into_rc,
717        Function,  // chains a non-mutating function after this mutating function
718        'static
719    );
720}
721
722// Generates: Clone implementation for RcMutatingFunction<T, R>
723impl_function_clone!(RcMutatingFunction<T, R>);
724
725// Generates: Debug and Display implementations for RcMutatingFunction<T, R>
726impl_function_debug_display!(RcMutatingFunction<T, R>);
727
728// Generates: identity() method for RcMutatingFunction<T, T>
729impl_function_identity_method!(RcMutatingFunction<T, T>, mutating);
730
731impl<T, R> MutatingFunction<T, R> for RcMutatingFunction<T, R> {
732    fn apply(&self, input: &mut T) -> R {
733        (self.function)(input)
734    }
735
736    // Use macro to implement conversion methods
737    impl_rc_conversions!(
738        RcMutatingFunction<T, R>,
739        BoxMutatingFunction,
740        BoxMutatingFunctionOnce,
741        Fn(input: &mut T) -> R
742    );
743}
744
745// =======================================================================
746// 5. ArcMutatingFunction - Thread-Safe Shared Ownership
747// =======================================================================
748
749/// ArcMutatingFunction struct
750///
751/// A mutating function implementation based on
752/// `Arc<dyn Fn(&mut T) -> R + Send + Sync>` for thread-safe shared ownership
753/// scenarios. This type allows the function to be safely shared and used
754/// across multiple threads.
755///
756/// # Features
757///
758/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
759/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
760/// - **Stateless**: Cannot modify captured environment (uses `Fn` not
761///   `FnMut`)
762/// - **Chainable**: Method chaining via `&self` (non-consuming)
763///
764/// # Use Cases
765///
766/// Choose `ArcMutatingFunction` when:
767/// - The function needs to be shared across multiple threads for stateless
768///   operations
769/// - Concurrent task processing (e.g., thread pools)
770/// - Thread safety is required (Send + Sync)
771///
772/// # Examples
773///
774/// ```rust
775/// use qubit_function::{MutatingFunction, ArcMutatingFunction};
776///
777/// let func = ArcMutatingFunction::new(|x: &mut i32| {
778///     *x *= 2;
779///     *x
780/// });
781/// let clone = func.clone();
782///
783/// let mut value = 5;
784/// assert_eq!(func.apply(&mut value), 10);
785/// ```
786///
787/// # Author
788///
789/// Haixing Hu
790pub struct ArcMutatingFunction<T, R> {
791    function: Arc<dyn Fn(&mut T) -> R + Send + Sync>,
792    name: Option<String>,
793}
794
795impl<T, R> ArcMutatingFunction<T, R> {
796    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
797    impl_function_common_methods!(
798        ArcMutatingFunction<T, R>,
799        (Fn(&mut T) -> R + Send + Sync + 'static),
800        |f| Arc::new(f)
801    );
802
803    // Generates: when(), and_then(), compose()
804    impl_shared_function_methods!(
805        ArcMutatingFunction<T, R>,
806        ArcConditionalMutatingFunction,
807        into_arc,
808        Function,  // chains a non-mutating function after this mutating function
809        Send + Sync + 'static
810    );
811}
812
813// Generates: Clone implementation for ArcMutatingFunction<T, R>
814impl_function_clone!(ArcMutatingFunction<T, R>);
815
816// Generates: Debug and Display implementations for ArcMutatingFunction<T, R>
817impl_function_debug_display!(ArcMutatingFunction<T, R>);
818
819// Generates: identity() method for ArcMutatingFunction<T, T>
820impl_function_identity_method!(ArcMutatingFunction<T, T>, mutating);
821
822impl<T, R> MutatingFunction<T, R> for ArcMutatingFunction<T, R> {
823    fn apply(&self, input: &mut T) -> R {
824        (self.function)(input)
825    }
826
827    // Use macro to implement conversion methods
828    impl_arc_conversions!(
829        ArcMutatingFunction<T, R>,
830        BoxMutatingFunction,
831        RcMutatingFunction,
832        BoxMutatingFunctionOnce,
833        Fn(input: &mut T) -> R
834    );
835}
836
837// =======================================================================
838// 6. Implement MutatingFunction trait for closures
839// =======================================================================
840
841impl_closure_trait!(
842    MutatingFunction<T, R>,
843    apply,
844    BoxMutatingFunctionOnce,
845    Fn(input: &mut T) -> R
846);
847
848// =======================================================================
849// 7. Provide extension methods for closures
850// =======================================================================
851
852// Generates: FnFunctionOps trait and blanket implementation
853impl_fn_ops_trait!(
854    (Fn(&mut T) -> R),
855    FnMutatingFunctionOps,
856    BoxMutatingFunction,
857    Function, // chains a non-mutating function after this mutating function
858    BoxConditionalMutatingFunction
859);
860
861// ============================================================================
862// BoxConditionalMutatingFunction - Box-based Conditional Mutating Function
863// ============================================================================
864
865/// BoxConditionalMutatingFunction struct
866///
867/// A conditional function that only executes when a predicate is satisfied.
868/// Uses `BoxMutatingFunction` and `BoxPredicate` for single ownership semantics.
869///
870/// This type is typically created by calling `BoxMutatingFunction::when()` and is
871/// designed to work with the `or_else()` method to create if-then-else logic.
872///
873/// # Features
874///
875/// - **Single Ownership**: Not cloneable, consumes `self` on use
876/// - **Conditional Execution**: Only transforms when predicate returns `true`
877/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
878/// - **Implements Function**: Can be used anywhere a `Function` is expected
879///
880/// # Examples
881///
882/// ## With or_else Branch
883///
884/// ```rust
885/// use qubit_function::{MutatingFunction, BoxMutatingFunction};
886///
887/// let double = BoxMutatingFunction::new(|x: &mut i32| x * 2);
888/// let negate = BoxMutatingFunction::new(|x: &mut i32| -x);
889/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
890///
891/// assert_eq!(conditional.apply(5), 10); // when branch executed
892/// assert_eq!(conditional.apply(-5), 5); // or_else branch executed
893/// ```
894///
895/// # Author
896///
897/// Haixing Hu
898pub struct BoxConditionalMutatingFunction<T, R> {
899    function: BoxMutatingFunction<T, R>,
900    predicate: BoxPredicate<T>,
901}
902
903// Use macro to generate conditional function implementations
904impl_box_conditional_function!(
905    BoxConditionalMutatingFunction<T, R>,
906    BoxMutatingFunction,
907    MutatingFunction
908);
909
910// Use macro to generate conditional function debug and display implementations
911impl_conditional_function_debug_display!(BoxConditionalMutatingFunction<T, R>);
912
913// ============================================================================
914// RcConditionalMutatingFunction - Rc-based Conditional Mutating Function
915// ============================================================================
916
917/// RcConditionalMutatingFunction struct
918///
919/// A single-threaded conditional function that only executes when a
920/// predicate is satisfied. Uses `RcMutatingFunction` and `RcPredicate` for shared
921/// ownership within a single thread.
922///
923/// This type is typically created by calling `RcMutatingFunction::when()` and is
924/// designed to work with the `or_else()` method to create if-then-else logic.
925///
926/// # Features
927///
928/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
929/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
930/// - **Conditional Execution**: Only transforms when predicate returns `true`
931/// - **No Lock Overhead**: More efficient than `ArcConditionalFunction`
932///
933/// # Examples
934///
935/// ```rust
936/// use qubit_function::{MutatingFunction, RcMutatingFunction};
937///
938/// let double = RcMutatingFunction::new(|x: &mut i32| x * 2);
939/// let identity = RcMutatingFunction::<i32, i32>::identity();
940/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
941///
942/// let conditional_clone = conditional.clone();
943///
944/// assert_eq!(conditional.apply(5), 10);
945/// assert_eq!(conditional_clone.apply(-5), -5);
946/// ```
947///
948/// # Author
949///
950/// Haixing Hu
951pub struct RcConditionalMutatingFunction<T, R> {
952    function: RcMutatingFunction<T, R>,
953    predicate: RcPredicate<T>,
954}
955
956// Use macro to generate conditional function implementations
957impl_shared_conditional_function!(
958    RcConditionalMutatingFunction<T, R>,
959    RcMutatingFunction,
960    MutatingFunction,
961    'static
962);
963
964// Use macro to generate conditional function clone implementations
965impl_conditional_function_clone!(RcConditionalMutatingFunction<T, R>);
966
967// Use macro to generate conditional function debug and display implementations
968impl_conditional_function_debug_display!(RcConditionalMutatingFunction<T, R>);
969
970// ============================================================================
971// ArcConditionalMutatingFunction - Arc-based Conditional Mutating Function
972// ============================================================================
973
974/// ArcConditionalMutatingFunction struct
975///
976/// A thread-safe conditional function that only executes when a predicate is
977/// satisfied. Uses `ArcMutatingFunction` and `ArcPredicate` for shared ownership
978/// across threads.
979///
980/// This type is typically created by calling `ArcMutatingFunction::when()` and is
981/// designed to work with the `or_else()` method to create if-then-else logic.
982///
983/// # Features
984///
985/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
986/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
987/// - **Conditional Execution**: Only transforms when predicate returns `true`
988/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
989///
990/// # Examples
991///
992/// ```rust
993/// use qubit_function::{MutatingFunction, ArcMutatingFunction};
994///
995/// let double = ArcMutatingFunction::new(|x: &mut i32| x * 2);
996/// let identity = ArcMutatingFunction::<i32, i32>::identity();
997/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
998///
999/// let conditional_clone = conditional.clone();
1000///
1001/// assert_eq!(conditional.apply(5), 10);
1002/// assert_eq!(conditional_clone.apply(-5), -5);
1003/// ```
1004///
1005/// # Author
1006///
1007/// Haixing Hu
1008pub struct ArcConditionalMutatingFunction<T, R> {
1009    function: ArcMutatingFunction<T, R>,
1010    predicate: ArcPredicate<T>,
1011}
1012
1013// Use macro to generate conditional function implementations
1014impl_shared_conditional_function!(
1015    ArcConditionalMutatingFunction<T, R>,
1016    ArcMutatingFunction,
1017    MutatingFunction,
1018    Send + Sync + 'static
1019);
1020
1021// Use macro to generate conditional function clone implementations
1022impl_conditional_function_clone!(ArcConditionalMutatingFunction<T, R>);
1023
1024// Use macro to generate conditional function debug and display implementations
1025impl_conditional_function_debug_display!(ArcConditionalMutatingFunction<T, R>);