prism3_function/functions/
stateful_mutating_function.rs

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