Skip to main content

qubit_function/functions/
stateful_mutating_function.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit 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 qubit_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 qubit_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
158mod box_stateful_mutating_function;
159pub use box_stateful_mutating_function::BoxStatefulMutatingFunction;
160mod rc_stateful_mutating_function;
161pub use rc_stateful_mutating_function::RcStatefulMutatingFunction;
162mod arc_stateful_mutating_function;
163pub use arc_stateful_mutating_function::ArcStatefulMutatingFunction;
164mod box_conditional_stateful_mutating_function;
165pub use box_conditional_stateful_mutating_function::BoxConditionalStatefulMutatingFunction;
166mod rc_conditional_stateful_mutating_function;
167pub use rc_conditional_stateful_mutating_function::RcConditionalStatefulMutatingFunction;
168mod arc_conditional_stateful_mutating_function;
169pub use arc_conditional_stateful_mutating_function::ArcConditionalStatefulMutatingFunction;
170mod fn_stateful_mutating_function_ops;
171pub use fn_stateful_mutating_function_ops::FnStatefulMutatingFunctionOps;
172
173// =======================================================================
174// 1. StatefulMutatingFunction Trait - Unified Interface
175// =======================================================================
176
177/// StatefulMutatingFunction trait - Unified stateful mutating function
178/// interface
179///
180/// It is similar to the `FnMut(&mut T) -> R` trait in the standard library.
181///
182/// Defines the core behavior of all stateful mutating function types.
183/// Performs operations that accept a mutable reference, potentially modify
184/// both the function's internal state and the input, and return a result.
185///
186/// This trait is automatically implemented by:
187/// - All closures implementing `FnMut(&mut T) -> R`
188/// - `BoxStatefulMutatingFunction<T, R>`,
189///   `ArcStatefulMutatingFunction<T, R>`, and
190///   `RcStatefulMutatingFunction<T, R>`
191///
192/// # Design Rationale
193///
194/// The trait provides a unified abstraction over different ownership models
195/// for operations that need to maintain state while modifying input and
196/// returning results. This is useful for scenarios where you need to:
197/// - Track statistics or counts during modifications
198/// - Accumulate information across multiple calls
199/// - Implement stateful validators or transformers
200///
201/// # Features
202///
203/// - **Unified Interface**: All stateful mutating function types share the
204///   same `apply` method signature
205/// - **Automatic Implementation**: Closures automatically implement this
206///   trait
207/// - **Type Conversions**: Easy conversion between ownership models
208/// - **Generic Programming**: Write functions that work with any stateful
209///   mutating function type
210///
211/// # Examples
212///
213/// ## Generic Function
214///
215/// ```rust
216/// use qubit_function::{StatefulMutatingFunction,
217///                       BoxStatefulMutatingFunction};
218///
219/// fn apply_and_log<F: StatefulMutatingFunction<i32, i32>>(
220///     func: &mut F,
221///     value: i32
222/// ) -> i32 {
223///     let mut val = value;
224///     let result = func.apply(&mut val);
225///     println!("Modified: {} -> {}, returned: {}", value, val, result);
226///     result
227/// }
228///
229/// let mut counter = {
230///     let mut count = 0;
231///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
232///         count += 1;
233///         *x += 1;
234///         count
235///     })
236/// };
237/// assert_eq!(apply_and_log(&mut counter, 5), 1);
238/// ```
239///
240/// ## Type Conversion
241///
242/// ```rust
243/// use qubit_function::StatefulMutatingFunction;
244///
245/// let mut count = 0;
246/// let closure = move |x: &mut i32| {
247///     count += 1;
248///     *x *= 2;
249///     count
250/// };
251///
252/// // Convert to different ownership models
253/// let mut box_func = closure.into_box();
254/// // let mut rc_func = closure.into_rc();  // closure moved
255/// // let mut arc_func = closure.into_arc(); // closure moved
256/// ```
257///
258/// # Author
259///
260/// Haixing Hu
261pub trait StatefulMutatingFunction<T, R> {
262    /// Applies the function to the mutable reference and returns a result
263    ///
264    /// Executes an operation on the given mutable reference, potentially
265    /// modifying both the function's internal state and the input, and
266    /// returns a result value.
267    ///
268    /// # Parameters
269    ///
270    /// * `t` - A mutable reference to the input value
271    ///
272    /// # Returns
273    ///
274    /// The computed result value
275    ///
276    /// # Examples
277    ///
278    /// ```rust
279    /// use qubit_function::{StatefulMutatingFunction,
280    ///                       BoxStatefulMutatingFunction};
281    ///
282    /// let mut counter = {
283    ///     let mut count = 0;
284    ///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
285    ///         count += 1;
286    ///         let old = *x;
287    ///         *x += 1;
288    ///         (old, count)
289    ///     })
290    /// };
291    ///
292    /// let mut value = 5;
293    /// let (old_value, call_count) = counter.apply(&mut value);
294    /// assert_eq!(old_value, 5);
295    /// assert_eq!(call_count, 1);
296    /// assert_eq!(value, 6);
297    /// ```
298    fn apply(&mut self, t: &mut T) -> R;
299
300    /// Convert this function into a `BoxStatefulMutatingFunction<T, R>`.
301    ///
302    /// This consuming conversion takes ownership of `self` and returns a
303    /// boxed implementation that forwards calls to the original function.
304    /// Types that can provide a more efficient conversion may override the
305    /// default implementation.
306    ///
307    /// # Consumption
308    ///
309    /// This method consumes the function: the original value will no longer
310    /// be available after the call. For cloneable functions call `.clone()`
311    /// before converting if you need to retain the original instance.
312    ///
313    /// # Returns
314    ///
315    /// A `BoxStatefulMutatingFunction<T, R>` that forwards to the original
316    /// function.
317    ///
318    /// # Examples
319    ///
320    /// ```rust
321    /// use qubit_function::StatefulMutatingFunction;
322    ///
323    /// let mut count = 0;
324    /// let closure = move |x: &mut i32| {
325    ///     count += 1;
326    ///     *x *= 2;
327    ///     count
328    /// };
329    /// let mut boxed = closure.into_box();
330    /// let mut value = 5;
331    /// assert_eq!(boxed.apply(&mut value), 1);
332    /// ```
333    fn into_box(mut self) -> BoxStatefulMutatingFunction<T, R>
334    where
335        Self: Sized + 'static,
336    {
337        BoxStatefulMutatingFunction::new(move |t| self.apply(t))
338    }
339
340    /// Convert this function into an `RcStatefulMutatingFunction<T, R>`.
341    ///
342    /// This consuming conversion takes ownership of `self` and returns an
343    /// `Rc`-backed function that forwards calls to the original. Override to
344    /// provide a more direct or efficient conversion when available.
345    ///
346    /// # Consumption
347    ///
348    /// This method consumes the function. If you need to keep the original
349    /// instance, clone it prior to calling this method.
350    ///
351    /// # Returns
352    ///
353    /// An `RcStatefulMutatingFunction<T, R>` forwarding to the original
354    /// function.
355    ///
356    /// # Examples
357    ///
358    /// ```rust
359    /// use qubit_function::StatefulMutatingFunction;
360    ///
361    /// let mut count = 0;
362    /// let closure = move |x: &mut i32| {
363    ///     count += 1;
364    ///     *x *= 2;
365    ///     count
366    /// };
367    /// let mut rc = closure.into_rc();
368    /// let mut value = 5;
369    /// assert_eq!(rc.apply(&mut value), 1);
370    /// ```
371    fn into_rc(mut self) -> RcStatefulMutatingFunction<T, R>
372    where
373        Self: Sized + 'static,
374    {
375        RcStatefulMutatingFunction::new(move |t| self.apply(t))
376    }
377
378    /// Convert this function into an `ArcStatefulMutatingFunction<T, R>`.
379    ///
380    /// This consuming conversion takes ownership of `self` and returns an
381    /// `Arc`-wrapped, thread-safe function. Types may override the default
382    /// implementation to provide a more efficient conversion.
383    ///
384    /// # Consumption
385    ///
386    /// This method consumes the function. Clone the instance first if you
387    /// need to retain the original for further use.
388    ///
389    /// # Returns
390    ///
391    /// An `ArcStatefulMutatingFunction<T, R>` that forwards to the original
392    /// function.
393    ///
394    /// # Examples
395    ///
396    /// ```rust
397    /// use qubit_function::StatefulMutatingFunction;
398    ///
399    /// let mut count = 0;
400    /// let closure = move |x: &mut i32| {
401    ///     count += 1;
402    ///     *x *= 2;
403    ///     count
404    /// };
405    /// let mut arc = closure.into_arc();
406    /// let mut value = 5;
407    /// assert_eq!(arc.apply(&mut value), 1);
408    /// ```
409    fn into_arc(mut self) -> ArcStatefulMutatingFunction<T, R>
410    where
411        Self: Sized + Send + 'static,
412    {
413        ArcStatefulMutatingFunction::new(move |t| self.apply(t))
414    }
415
416    /// Consume the function and return an `FnMut(&mut T) -> R` closure.
417    ///
418    /// The returned closure forwards calls to the original function and is
419    /// suitable for use with iterator adapters or other contexts expecting
420    /// closures.
421    ///
422    /// # Consumption
423    ///
424    /// This method consumes the function. The original instance will not be
425    /// available after calling this method.
426    ///
427    /// # Returns
428    ///
429    /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
430    /// original function.
431    ///
432    /// # Examples
433    ///
434    /// ```rust
435    /// use qubit_function::{StatefulMutatingFunction,
436    ///                       BoxStatefulMutatingFunction};
437    ///
438    /// let func = {
439    ///     let mut sum = 0;
440    ///     BoxStatefulMutatingFunction::new(move |x: &mut i32| {
441    ///         *x *= 2;
442    ///         sum += *x;
443    ///         sum
444    ///     })
445    /// };
446    /// let mut closure = func.into_fn();
447    /// let mut value = 5;
448    /// assert_eq!(closure(&mut value), 10);
449    /// ```
450    fn into_fn(mut self) -> impl FnMut(&mut T) -> R
451    where
452        Self: Sized + 'static,
453    {
454        move |t| self.apply(t)
455    }
456
457    /// Consume the function and return an explicit `FnMut` closure.
458    ///
459    /// This is a naming alias of [`StatefulMutatingFunction::into_fn`] to make
460    /// the mutability of the returned closure explicit.
461    fn into_mut_fn(self) -> impl FnMut(&mut T) -> R
462    where
463        Self: Sized + 'static,
464    {
465        self.into_fn()
466    }
467
468    /// Create a non-consuming `BoxStatefulMutatingFunction<T, R>` that
469    /// forwards to `self`.
470    ///
471    /// The default implementation clones `self` (requires `Clone`) and
472    /// returns a boxed function that calls the cloned instance. Override this
473    /// method if a more efficient conversion exists.
474    ///
475    /// # Returns
476    ///
477    /// A `BoxStatefulMutatingFunction<T, R>` that forwards to a clone of
478    /// `self`.
479    fn to_box(&self) -> BoxStatefulMutatingFunction<T, R>
480    where
481        Self: Sized + Clone + 'static,
482    {
483        self.clone().into_box()
484    }
485
486    /// Create a non-consuming `RcStatefulMutatingFunction<T, R>` that
487    /// forwards to `self`.
488    ///
489    /// The default implementation clones `self` (requires `Clone`) and
490    /// returns an `Rc`-backed function that forwards calls to the clone.
491    /// Override to provide a more direct or efficient conversion if needed.
492    ///
493    /// # Returns
494    ///
495    /// An `RcStatefulMutatingFunction<T, R>` that forwards to a clone of
496    /// `self`.
497    fn to_rc(&self) -> RcStatefulMutatingFunction<T, R>
498    where
499        Self: Sized + Clone + 'static,
500    {
501        self.clone().into_rc()
502    }
503
504    /// Create a non-consuming `ArcStatefulMutatingFunction<T, R>` that
505    /// forwards to `self`.
506    ///
507    /// The default implementation clones `self` (requires
508    /// `Clone + Send`) and returns an `Arc`-wrapped function that forwards
509    /// calls to the clone. Override when a more efficient conversion is
510    /// available.
511    ///
512    /// # Returns
513    ///
514    /// An `ArcStatefulMutatingFunction<T, R>` that forwards to a clone of
515    /// `self`.
516    fn to_arc(&self) -> ArcStatefulMutatingFunction<T, R>
517    where
518        Self: Sized + Clone + Send + 'static,
519    {
520        self.clone().into_arc()
521    }
522
523    /// Create a boxed `FnMut(&mut T) -> R` closure that forwards to `self`.
524    ///
525    /// The default implementation clones `self` (requires `Clone`) and
526    /// returns a boxed closure that invokes the cloned instance. Override to
527    /// provide a more efficient conversion when possible.
528    ///
529    /// # Returns
530    ///
531    /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
532    /// original function.
533    fn to_fn(&self) -> impl FnMut(&mut T) -> R
534    where
535        Self: Sized + Clone + 'static,
536    {
537        self.clone().into_fn()
538    }
539
540    /// Create a non-consuming explicit `FnMut` closure from `self`.
541    ///
542    /// This is a naming alias of [`StatefulMutatingFunction::to_fn`] and
543    /// preserves the same clone-based behavior.
544    fn to_mut_fn(&self) -> impl FnMut(&mut T) -> R
545    where
546        Self: Sized + Clone + 'static,
547    {
548        self.to_fn()
549    }
550
551    /// Convert to StatefulMutatingFunctionOnce
552    ///
553    /// **⚠️ Consumes `self`**: The original function will be unavailable
554    /// after calling this method.
555    ///
556    /// Converts a reusable stateful mutating function to a one-time function
557    /// that consumes itself on use. This enables passing `StatefulMutatingFunction`
558    /// to functions that require `StatefulMutatingFunctionOnce`.
559    ///
560    /// # Returns
561    ///
562    /// Returns a `BoxMutatingFunctionOnce<T, R>`
563    ///
564    /// # Examples
565    ///
566    /// ```rust
567    /// use qubit_function::{MutatingFunctionOnce,
568    ///                       StatefulMutatingFunction,
569    ///                       BoxStatefulMutatingFunction};
570    ///
571    /// fn takes_once<F: MutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
572    ///     let result = func.apply(value);
573    ///     println!("Result: {}", result);
574    /// }
575    ///
576    /// let func = BoxStatefulMutatingFunction::new(|x: &mut i32| {
577    ///     *x *= 2;
578    ///     *x
579    /// });
580    /// let mut value = 5;
581    /// takes_once(func.into_once(), &mut value);
582    /// ```
583    fn into_once(mut self) -> BoxMutatingFunctionOnce<T, R>
584    where
585        Self: Sized + 'static,
586    {
587        BoxMutatingFunctionOnce::new(move |t| self.apply(t))
588    }
589
590    /// Convert to StatefulMutatingFunctionOnce without consuming self
591    ///
592    /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
593    /// Clones the current function and converts the clone to a one-time function.
594    ///
595    /// # Returns
596    ///
597    /// Returns a `BoxMutatingFunctionOnce<T, R>`
598    ///
599    /// # Examples
600    ///
601    /// ```rust
602    /// use qubit_function::{MutatingFunctionOnce,
603    ///                       StatefulMutatingFunction,
604    ///                       RcStatefulMutatingFunction};
605    ///
606    /// fn takes_once<F: MutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
607    ///     let result = func.apply(value);
608    ///     println!("Result: {}", result);
609    /// }
610    ///
611    /// let func = RcStatefulMutatingFunction::new(|x: &mut i32| {
612    ///     *x *= 2;
613    ///     *x
614    /// });
615    /// let mut value = 5;
616    /// takes_once(func.to_once(), &mut value);
617    /// ```
618    fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
619    where
620        Self: Clone + 'static,
621    {
622        self.clone().into_once()
623    }
624}
625
626// =======================================================================
627// 2. Type Aliases
628// =======================================================================
629
630/// Type alias for Arc-wrapped stateful mutating function
631type ArcStatefulMutatingFunctionFn<T, R> = Arc<Mutex<dyn FnMut(&mut T) -> R + Send + 'static>>;
632
633/// Type alias for Rc-wrapped stateful mutating function
634type RcStatefulMutatingFunctionFn<T, R> = Rc<RefCell<dyn FnMut(&mut T) -> R>>;