qubit_function/functions/stateful_mutating_function.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! # StatefulMutatingFunction Types
11//!
12//! Provides Java-like `StatefulMutatingFunction` interface implementations
13//! for performing operations that accept a mutable reference, potentially
14//! modify internal state, and return a result.
15//!
16//! It is similar to the `FnMut(&mut T) -> R` trait in the standard library.
17//!
18//! This module provides a unified `StatefulMutatingFunction` trait and three
19//! concrete implementations based on different ownership models:
20//!
21//! - **`BoxStatefulMutatingFunction<T, R>`**: Box-based single ownership
22//! implementation
23//! - **`ArcStatefulMutatingFunction<T, R>`**: Arc<Mutex<>>-based thread-safe
24//! shared ownership implementation
25//! - **`RcStatefulMutatingFunction<T, R>`**: Rc<RefCell<>>-based
26//! single-threaded shared ownership implementation
27//!
28//! # Design Philosophy
29//!
30//! `StatefulMutatingFunction` extends `MutatingFunction` with the ability to
31//! maintain internal state:
32//!
33//! - **MutatingFunction**: `Fn(&mut T) -> R` - stateless, immutable self
34//! - **StatefulMutatingFunction**: `FnMut(&mut T) -> R` - stateful, mutable
35//! self
36//!
37//! ## Comparison with Related Types
38//!
39//! | Type | Self | Input | Modifies Self? | Modifies Input? | Returns? |
40//! |------|------|-------|----------------|-----------------|----------|
41//! | **StatefulFunction** | `&mut self` | `&T` | ✅ | ❌ | ✅ |
42//! | **StatefulMutator** | `&mut self` | `&mut T` | ✅ | ✅ | ❌ |
43//! | **StatefulMutatingFunction** | `&mut self` | `&mut T` | ✅ | ✅ | ✅ |
44//!
45//! **Key Insight**: Use `StatefulMutatingFunction` when you need to:
46//! - Maintain internal state (counters, accumulators, etc.)
47//! - Modify the input value
48//! - Return information about the operation
49//!
50//! # Comparison Table
51//!
52//! | Feature | Box | Arc | Rc |
53//! |------------------|-----|-----|----|
54//! | Ownership | Single | Shared | Shared |
55//! | Cloneable | ❌ | ✅ | ✅ |
56//! | Thread-Safe | ❌ | ✅ | ❌ |
57//! | Interior Mut. | N/A | Mutex | RefCell |
58//! | `and_then` API | `self` | `&self` | `&self` |
59//! | Lock Overhead | None | Yes | None |
60//!
61//! # Use Cases
62//!
63//! ## Common Scenarios
64//!
65//! - **Stateful counters**: Increment and track modification count
66//! - **Accumulators**: Collect statistics while modifying data
67//! - **Rate limiters**: Track calls and conditionally modify
68//! - **Validators**: Accumulate errors while fixing data
69//! - **Stateful transformers**: Apply transformations based on history
70//!
71//! # Examples
72//!
73//! ## Basic Usage
74//!
75//! ```rust
76//! use qubit_function::{BoxStatefulMutatingFunction,
77//! StatefulMutatingFunction};
78//!
79//! // Counter that increments value and tracks calls
80//! let mut counter = {
81//! let mut call_count = 0;
82//! BoxStatefulMutatingFunction::new(move |x: &mut i32| {
83//! call_count += 1;
84//! *x += 1;
85//! call_count
86//! })
87//! };
88//!
89//! let mut value = 5;
90//! assert_eq!(counter.apply(&mut value), 1);
91//! assert_eq!(value, 6);
92//! assert_eq!(counter.apply(&mut value), 2);
93//! assert_eq!(value, 7);
94//! ```
95//!
96//! ## Accumulator Pattern
97//!
98//! ```rust
99//! use qubit_function::{BoxStatefulMutatingFunction,
100//! StatefulMutatingFunction};
101//!
102//! // Accumulate sum while doubling values
103//! let mut accumulator = {
104//! let mut sum = 0;
105//! BoxStatefulMutatingFunction::new(move |x: &mut i32| {
106//! *x *= 2;
107//! sum += *x;
108//! sum
109//! })
110//! };
111//!
112//! let mut value = 5;
113//! assert_eq!(accumulator.apply(&mut value), 10);
114//! assert_eq!(value, 10);
115//!
116//! let mut value2 = 3;
117//! assert_eq!(accumulator.apply(&mut value2), 16); // 10 + 6
118//! assert_eq!(value2, 6);
119//! ```
120//!
121use std::cell::RefCell;
122use std::rc::Rc;
123use std::sync::Arc;
124
125use parking_lot::Mutex;
126
127use crate::functions::{
128 function::Function,
129 macros::{
130 impl_box_conditional_function,
131 impl_box_function_methods,
132 impl_conditional_function_clone,
133 impl_conditional_function_debug_display,
134 impl_fn_ops_trait,
135 impl_function_clone,
136 impl_function_common_methods,
137 impl_function_debug_display,
138 impl_function_identity_method,
139 impl_shared_conditional_function,
140 impl_shared_function_methods,
141 },
142 mutating_function_once::BoxMutatingFunctionOnce,
143};
144use crate::macros::{
145 impl_arc_conversions,
146 impl_box_conversions,
147 impl_rc_conversions,
148};
149use crate::predicates::predicate::{
150 ArcPredicate,
151 BoxPredicate,
152 Predicate,
153 RcPredicate,
154};
155
156mod box_stateful_mutating_function;
157pub use box_stateful_mutating_function::BoxStatefulMutatingFunction;
158mod rc_stateful_mutating_function;
159pub use rc_stateful_mutating_function::RcStatefulMutatingFunction;
160mod arc_stateful_mutating_function;
161pub use arc_stateful_mutating_function::ArcStatefulMutatingFunction;
162mod box_conditional_stateful_mutating_function;
163pub use box_conditional_stateful_mutating_function::BoxConditionalStatefulMutatingFunction;
164mod rc_conditional_stateful_mutating_function;
165pub use rc_conditional_stateful_mutating_function::RcConditionalStatefulMutatingFunction;
166mod arc_conditional_stateful_mutating_function;
167pub use arc_conditional_stateful_mutating_function::ArcConditionalStatefulMutatingFunction;
168mod fn_stateful_mutating_function_ops;
169pub use fn_stateful_mutating_function_ops::FnStatefulMutatingFunctionOps;
170
171// =======================================================================
172// 1. StatefulMutatingFunction Trait - Unified Interface
173// =======================================================================
174
175/// StatefulMutatingFunction trait - Unified stateful mutating function
176/// interface
177///
178/// It is similar to the `FnMut(&mut T) -> R` trait in the standard library.
179///
180/// Defines the core behavior of all stateful mutating function types.
181/// Performs operations that accept a mutable reference, potentially modify
182/// both the function's internal state and the input, and return a result.
183///
184/// This trait is automatically implemented by:
185/// - All closures implementing `FnMut(&mut T) -> R`
186/// - `BoxStatefulMutatingFunction<T, R>`,
187/// `ArcStatefulMutatingFunction<T, R>`, and
188/// `RcStatefulMutatingFunction<T, R>`
189///
190/// # Design Rationale
191///
192/// The trait provides a unified abstraction over different ownership models
193/// for operations that need to maintain state while modifying input and
194/// returning results. This is useful for scenarios where you need to:
195/// - Track statistics or counts during modifications
196/// - Accumulate information across multiple calls
197/// - Implement stateful validators or transformers
198///
199/// # Features
200///
201/// - **Unified Interface**: All stateful mutating function types share the
202/// same `apply` method signature
203/// - **Automatic Implementation**: Closures automatically implement this
204/// trait
205/// - **Type Conversions**: Easy conversion between ownership models
206/// - **Generic Programming**: Write functions that work with any stateful
207/// mutating function type
208///
209/// # Examples
210///
211/// ## Generic Function
212///
213/// ```rust
214/// use qubit_function::{StatefulMutatingFunction,
215/// BoxStatefulMutatingFunction};
216///
217/// fn apply_and_log<F: StatefulMutatingFunction<i32, i32>>(
218/// func: &mut F,
219/// value: i32
220/// ) -> i32 {
221/// let mut val = value;
222/// let result = func.apply(&mut val);
223/// println!("Modified: {} -> {}, returned: {}", value, val, result);
224/// result
225/// }
226///
227/// let mut counter = {
228/// let mut count = 0;
229/// BoxStatefulMutatingFunction::new(move |x: &mut i32| {
230/// count += 1;
231/// *x += 1;
232/// count
233/// })
234/// };
235/// assert_eq!(apply_and_log(&mut counter, 5), 1);
236/// ```
237///
238/// ## Type Conversion
239///
240/// ```rust
241/// use qubit_function::StatefulMutatingFunction;
242///
243/// let mut count = 0;
244/// let closure = move |x: &mut i32| {
245/// count += 1;
246/// *x *= 2;
247/// count
248/// };
249///
250/// // Convert to different ownership models
251/// let mut box_func = closure.into_box();
252/// // let mut rc_func = closure.into_rc(); // closure moved
253/// // let mut arc_func = closure.into_arc(); // closure moved
254/// ```
255///
256pub trait StatefulMutatingFunction<T, R> {
257 /// Applies the function to the mutable reference and returns a result
258 ///
259 /// Executes an operation on the given mutable reference, potentially
260 /// modifying both the function's internal state and the input, and
261 /// returns a result value.
262 ///
263 /// # Parameters
264 ///
265 /// * `t` - A mutable reference to the input value
266 ///
267 /// # Returns
268 ///
269 /// The computed result value
270 ///
271 /// # Examples
272 ///
273 /// ```rust
274 /// use qubit_function::{StatefulMutatingFunction,
275 /// BoxStatefulMutatingFunction};
276 ///
277 /// let mut counter = {
278 /// let mut count = 0;
279 /// BoxStatefulMutatingFunction::new(move |x: &mut i32| {
280 /// count += 1;
281 /// let old = *x;
282 /// *x += 1;
283 /// (old, count)
284 /// })
285 /// };
286 ///
287 /// let mut value = 5;
288 /// let (old_value, call_count) = counter.apply(&mut value);
289 /// assert_eq!(old_value, 5);
290 /// assert_eq!(call_count, 1);
291 /// assert_eq!(value, 6);
292 /// ```
293 fn apply(&mut self, t: &mut T) -> R;
294
295 /// Convert this function into a `BoxStatefulMutatingFunction<T, R>`.
296 ///
297 /// This consuming conversion takes ownership of `self` and returns a
298 /// boxed implementation that forwards calls to the original function.
299 /// Types that can provide a more efficient conversion may override the
300 /// default implementation.
301 ///
302 /// # Consumption
303 ///
304 /// This method consumes the function: the original value will no longer
305 /// be available after the call. For cloneable functions call `.clone()`
306 /// before converting if you need to retain the original instance.
307 ///
308 /// # Returns
309 ///
310 /// A `BoxStatefulMutatingFunction<T, R>` that forwards to the original
311 /// function.
312 ///
313 /// # Examples
314 ///
315 /// ```rust
316 /// use qubit_function::StatefulMutatingFunction;
317 ///
318 /// let mut count = 0;
319 /// let closure = move |x: &mut i32| {
320 /// count += 1;
321 /// *x *= 2;
322 /// count
323 /// };
324 /// let mut boxed = closure.into_box();
325 /// let mut value = 5;
326 /// assert_eq!(boxed.apply(&mut value), 1);
327 /// ```
328 fn into_box(mut self) -> BoxStatefulMutatingFunction<T, R>
329 where
330 Self: Sized + 'static,
331 {
332 BoxStatefulMutatingFunction::new(move |t| self.apply(t))
333 }
334
335 /// Convert this function into an `RcStatefulMutatingFunction<T, R>`.
336 ///
337 /// This consuming conversion takes ownership of `self` and returns an
338 /// `Rc`-backed function that forwards calls to the original. Override to
339 /// provide a more direct or efficient conversion when available.
340 ///
341 /// # Consumption
342 ///
343 /// This method consumes the function. If you need to keep the original
344 /// instance, clone it prior to calling this method.
345 ///
346 /// # Returns
347 ///
348 /// An `RcStatefulMutatingFunction<T, R>` forwarding to the original
349 /// function.
350 ///
351 /// # Examples
352 ///
353 /// ```rust
354 /// use qubit_function::StatefulMutatingFunction;
355 ///
356 /// let mut count = 0;
357 /// let closure = move |x: &mut i32| {
358 /// count += 1;
359 /// *x *= 2;
360 /// count
361 /// };
362 /// let mut rc = closure.into_rc();
363 /// let mut value = 5;
364 /// assert_eq!(rc.apply(&mut value), 1);
365 /// ```
366 fn into_rc(mut self) -> RcStatefulMutatingFunction<T, R>
367 where
368 Self: Sized + 'static,
369 {
370 RcStatefulMutatingFunction::new(move |t| self.apply(t))
371 }
372
373 /// Convert this function into an `ArcStatefulMutatingFunction<T, R>`.
374 ///
375 /// This consuming conversion takes ownership of `self` and returns an
376 /// `Arc`-wrapped, thread-safe function. Types may override the default
377 /// implementation to provide a more efficient conversion.
378 ///
379 /// # Consumption
380 ///
381 /// This method consumes the function. Clone the instance first if you
382 /// need to retain the original for further use.
383 ///
384 /// # Returns
385 ///
386 /// An `ArcStatefulMutatingFunction<T, R>` that forwards to the original
387 /// function.
388 ///
389 /// # Examples
390 ///
391 /// ```rust
392 /// use qubit_function::StatefulMutatingFunction;
393 ///
394 /// let mut count = 0;
395 /// let closure = move |x: &mut i32| {
396 /// count += 1;
397 /// *x *= 2;
398 /// count
399 /// };
400 /// let mut arc = closure.into_arc();
401 /// let mut value = 5;
402 /// assert_eq!(arc.apply(&mut value), 1);
403 /// ```
404 fn into_arc(mut self) -> ArcStatefulMutatingFunction<T, R>
405 where
406 Self: Sized + Send + 'static,
407 {
408 ArcStatefulMutatingFunction::new(move |t| self.apply(t))
409 }
410
411 /// Consume the function and return an `FnMut(&mut T) -> R` closure.
412 ///
413 /// The returned closure forwards calls to the original function and is
414 /// suitable for use with iterator adapters or other contexts expecting
415 /// closures.
416 ///
417 /// # Consumption
418 ///
419 /// This method consumes the function. The original instance will not be
420 /// available after calling this method.
421 ///
422 /// # Returns
423 ///
424 /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
425 /// original function.
426 ///
427 /// # Examples
428 ///
429 /// ```rust
430 /// use qubit_function::{StatefulMutatingFunction,
431 /// BoxStatefulMutatingFunction};
432 ///
433 /// let func = {
434 /// let mut sum = 0;
435 /// BoxStatefulMutatingFunction::new(move |x: &mut i32| {
436 /// *x *= 2;
437 /// sum += *x;
438 /// sum
439 /// })
440 /// };
441 /// let mut closure = func.into_fn();
442 /// let mut value = 5;
443 /// assert_eq!(closure(&mut value), 10);
444 /// ```
445 fn into_fn(mut self) -> impl FnMut(&mut T) -> R
446 where
447 Self: Sized + 'static,
448 {
449 move |t| self.apply(t)
450 }
451
452 /// Consume the function and return an explicit `FnMut` closure.
453 ///
454 /// This is a naming alias of [`StatefulMutatingFunction::into_fn`] to make
455 /// the mutability of the returned closure explicit.
456 fn into_mut_fn(self) -> impl FnMut(&mut T) -> R
457 where
458 Self: Sized + 'static,
459 {
460 self.into_fn()
461 }
462
463 /// Create a non-consuming `BoxStatefulMutatingFunction<T, R>` that
464 /// forwards to `self`.
465 ///
466 /// The default implementation clones `self` (requires `Clone`) and
467 /// returns a boxed function that calls the cloned instance. Override this
468 /// method if a more efficient conversion exists.
469 ///
470 /// # Returns
471 ///
472 /// A `BoxStatefulMutatingFunction<T, R>` that forwards to a clone of
473 /// `self`.
474 fn to_box(&self) -> BoxStatefulMutatingFunction<T, R>
475 where
476 Self: Sized + Clone + 'static,
477 {
478 self.clone().into_box()
479 }
480
481 /// Create a non-consuming `RcStatefulMutatingFunction<T, R>` that
482 /// forwards to `self`.
483 ///
484 /// The default implementation clones `self` (requires `Clone`) and
485 /// returns an `Rc`-backed function that forwards calls to the clone.
486 /// Override to provide a more direct or efficient conversion if needed.
487 ///
488 /// # Returns
489 ///
490 /// An `RcStatefulMutatingFunction<T, R>` that forwards to a clone of
491 /// `self`.
492 fn to_rc(&self) -> RcStatefulMutatingFunction<T, R>
493 where
494 Self: Sized + Clone + 'static,
495 {
496 self.clone().into_rc()
497 }
498
499 /// Create a non-consuming `ArcStatefulMutatingFunction<T, R>` that
500 /// forwards to `self`.
501 ///
502 /// The default implementation clones `self` (requires
503 /// `Clone + Send`) and returns an `Arc`-wrapped function that forwards
504 /// calls to the clone. Override when a more efficient conversion is
505 /// available.
506 ///
507 /// # Returns
508 ///
509 /// An `ArcStatefulMutatingFunction<T, R>` that forwards to a clone of
510 /// `self`.
511 fn to_arc(&self) -> ArcStatefulMutatingFunction<T, R>
512 where
513 Self: Sized + Clone + Send + 'static,
514 {
515 self.clone().into_arc()
516 }
517
518 /// Create a boxed `FnMut(&mut T) -> R` closure that forwards to `self`.
519 ///
520 /// The default implementation clones `self` (requires `Clone`) and
521 /// returns a boxed closure that invokes the cloned instance. Override to
522 /// provide a more efficient conversion when possible.
523 ///
524 /// # Returns
525 ///
526 /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
527 /// original function.
528 fn to_fn(&self) -> impl FnMut(&mut T) -> R
529 where
530 Self: Sized + Clone + 'static,
531 {
532 self.clone().into_fn()
533 }
534
535 /// Create a non-consuming explicit `FnMut` closure from `self`.
536 ///
537 /// This is a naming alias of [`StatefulMutatingFunction::to_fn`] and
538 /// preserves the same clone-based behavior.
539 fn to_mut_fn(&self) -> impl FnMut(&mut T) -> R
540 where
541 Self: Sized + Clone + 'static,
542 {
543 self.to_fn()
544 }
545
546 /// Convert to StatefulMutatingFunctionOnce
547 ///
548 /// **⚠️ Consumes `self`**: The original function will be unavailable
549 /// after calling this method.
550 ///
551 /// Converts a reusable stateful mutating function to a one-time function
552 /// that consumes itself on use. This enables passing `StatefulMutatingFunction`
553 /// to functions that require `StatefulMutatingFunctionOnce`.
554 ///
555 /// # Returns
556 ///
557 /// Returns a `BoxMutatingFunctionOnce<T, R>`
558 ///
559 /// # Examples
560 ///
561 /// ```rust
562 /// use qubit_function::{MutatingFunctionOnce,
563 /// StatefulMutatingFunction,
564 /// BoxStatefulMutatingFunction};
565 ///
566 /// fn takes_once<F: MutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
567 /// let result = func.apply(value);
568 /// println!("Result: {}", result);
569 /// }
570 ///
571 /// let func = BoxStatefulMutatingFunction::new(|x: &mut i32| {
572 /// *x *= 2;
573 /// *x
574 /// });
575 /// let mut value = 5;
576 /// takes_once(func.into_once(), &mut value);
577 /// ```
578 fn into_once(mut self) -> BoxMutatingFunctionOnce<T, R>
579 where
580 Self: Sized + 'static,
581 {
582 BoxMutatingFunctionOnce::new(move |t| self.apply(t))
583 }
584
585 /// Convert to StatefulMutatingFunctionOnce without consuming self
586 ///
587 /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
588 /// Clones the current function and converts the clone to a one-time function.
589 ///
590 /// # Returns
591 ///
592 /// Returns a `BoxMutatingFunctionOnce<T, R>`
593 ///
594 /// # Examples
595 ///
596 /// ```rust
597 /// use qubit_function::{MutatingFunctionOnce,
598 /// StatefulMutatingFunction,
599 /// RcStatefulMutatingFunction};
600 ///
601 /// fn takes_once<F: MutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
602 /// let result = func.apply(value);
603 /// println!("Result: {}", result);
604 /// }
605 ///
606 /// let func = RcStatefulMutatingFunction::new(|x: &mut i32| {
607 /// *x *= 2;
608 /// *x
609 /// });
610 /// let mut value = 5;
611 /// takes_once(func.to_once(), &mut value);
612 /// ```
613 fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
614 where
615 Self: Clone + 'static,
616 {
617 self.clone().into_once()
618 }
619}
620
621// =======================================================================
622// 2. Type Aliases
623// =======================================================================
624
625/// Type alias for Arc-wrapped stateful mutating function
626type ArcStatefulMutatingFunctionFn<T, R> = Arc<Mutex<dyn FnMut(&mut T) -> R + Send + 'static>>;
627
628/// Type alias for Rc-wrapped stateful mutating function
629type RcStatefulMutatingFunctionFn<T, R> = Rc<RefCell<dyn FnMut(&mut T) -> R>>;