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
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 qubit_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 qubit_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 qubit_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 qubit_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 {
322 BoxStatefulMutatingFunction::new(move |t| self.apply(t))
323 }
324
325 /// Convert this function into an `RcStatefulMutatingFunction<T, R>`.
326 ///
327 /// This consuming conversion takes ownership of `self` and returns an
328 /// `Rc`-backed function that forwards calls to the original. Override to
329 /// provide a more direct or efficient conversion when available.
330 ///
331 /// # Consumption
332 ///
333 /// This method consumes the function. If you need to keep the original
334 /// instance, clone it prior to calling this method.
335 ///
336 /// # Returns
337 ///
338 /// An `RcStatefulMutatingFunction<T, R>` forwarding to the original
339 /// function.
340 ///
341 /// # Examples
342 ///
343 /// ```rust
344 /// use qubit_function::StatefulMutatingFunction;
345 ///
346 /// let mut count = 0;
347 /// let closure = move |x: &mut i32| {
348 /// count += 1;
349 /// *x *= 2;
350 /// count
351 /// };
352 /// let mut rc = closure.into_rc();
353 /// let mut value = 5;
354 /// assert_eq!(rc.apply(&mut value), 1);
355 /// ```
356 fn into_rc(mut self) -> RcStatefulMutatingFunction<T, R>
357 where
358 Self: Sized + 'static,
359 {
360 RcStatefulMutatingFunction::new(move |t| self.apply(t))
361 }
362
363 /// Convert this function into an `ArcStatefulMutatingFunction<T, R>`.
364 ///
365 /// This consuming conversion takes ownership of `self` and returns an
366 /// `Arc`-wrapped, thread-safe function. Types may override the default
367 /// implementation to provide a more efficient conversion.
368 ///
369 /// # Consumption
370 ///
371 /// This method consumes the function. Clone the instance first if you
372 /// need to retain the original for further use.
373 ///
374 /// # Returns
375 ///
376 /// An `ArcStatefulMutatingFunction<T, R>` that forwards to the original
377 /// function.
378 ///
379 /// # Examples
380 ///
381 /// ```rust
382 /// use qubit_function::StatefulMutatingFunction;
383 ///
384 /// let mut count = 0;
385 /// let closure = move |x: &mut i32| {
386 /// count += 1;
387 /// *x *= 2;
388 /// count
389 /// };
390 /// let mut arc = closure.into_arc();
391 /// let mut value = 5;
392 /// assert_eq!(arc.apply(&mut value), 1);
393 /// ```
394 fn into_arc(mut self) -> ArcStatefulMutatingFunction<T, R>
395 where
396 Self: Sized + Send + 'static,
397 {
398 ArcStatefulMutatingFunction::new(move |t| self.apply(t))
399 }
400
401 /// Consume the function and return an `FnMut(&mut T) -> R` closure.
402 ///
403 /// The returned closure forwards calls to the original function and is
404 /// suitable for use with iterator adapters or other contexts expecting
405 /// closures.
406 ///
407 /// # Consumption
408 ///
409 /// This method consumes the function. The original instance will not be
410 /// available after calling this method.
411 ///
412 /// # Returns
413 ///
414 /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
415 /// original function.
416 ///
417 /// # Examples
418 ///
419 /// ```rust
420 /// use qubit_function::{StatefulMutatingFunction,
421 /// BoxStatefulMutatingFunction};
422 ///
423 /// let func = {
424 /// let mut sum = 0;
425 /// BoxStatefulMutatingFunction::new(move |x: &mut i32| {
426 /// *x *= 2;
427 /// sum += *x;
428 /// sum
429 /// })
430 /// };
431 /// let mut closure = func.into_fn();
432 /// let mut value = 5;
433 /// assert_eq!(closure(&mut value), 10);
434 /// ```
435 fn into_fn(mut self) -> impl FnMut(&mut T) -> R
436 where
437 Self: Sized + 'static,
438 {
439 move |t| self.apply(t)
440 }
441
442 /// Create a non-consuming `BoxStatefulMutatingFunction<T, R>` that
443 /// forwards to `self`.
444 ///
445 /// The default implementation clones `self` (requires `Clone`) and
446 /// returns a boxed function that calls the cloned instance. Override this
447 /// method if a more efficient conversion exists.
448 ///
449 /// # Returns
450 ///
451 /// A `BoxStatefulMutatingFunction<T, R>` that forwards to a clone of
452 /// `self`.
453 fn to_box(&self) -> BoxStatefulMutatingFunction<T, R>
454 where
455 Self: Sized + Clone + 'static,
456 {
457 self.clone().into_box()
458 }
459
460 /// Create a non-consuming `RcStatefulMutatingFunction<T, R>` that
461 /// forwards to `self`.
462 ///
463 /// The default implementation clones `self` (requires `Clone`) and
464 /// returns an `Rc`-backed function that forwards calls to the clone.
465 /// Override to provide a more direct or efficient conversion if needed.
466 ///
467 /// # Returns
468 ///
469 /// An `RcStatefulMutatingFunction<T, R>` that forwards to a clone of
470 /// `self`.
471 fn to_rc(&self) -> RcStatefulMutatingFunction<T, R>
472 where
473 Self: Sized + Clone + 'static,
474 {
475 self.clone().into_rc()
476 }
477
478 /// Create a non-consuming `ArcStatefulMutatingFunction<T, R>` that
479 /// forwards to `self`.
480 ///
481 /// The default implementation clones `self` (requires
482 /// `Clone + Send`) and returns an `Arc`-wrapped function that forwards
483 /// calls to the clone. Override when a more efficient conversion is
484 /// available.
485 ///
486 /// # Returns
487 ///
488 /// An `ArcStatefulMutatingFunction<T, R>` that forwards to a clone of
489 /// `self`.
490 fn to_arc(&self) -> ArcStatefulMutatingFunction<T, R>
491 where
492 Self: Sized + Clone + Send + 'static,
493 {
494 self.clone().into_arc()
495 }
496
497 /// Create a boxed `FnMut(&mut T) -> R` closure that forwards to `self`.
498 ///
499 /// The default implementation clones `self` (requires `Clone`) and
500 /// returns a boxed closure that invokes the cloned instance. Override to
501 /// provide a more efficient conversion when possible.
502 ///
503 /// # Returns
504 ///
505 /// A closure implementing `FnMut(&mut T) -> R` which forwards to the
506 /// original function.
507 fn to_fn(&self) -> impl FnMut(&mut T) -> R
508 where
509 Self: Sized + Clone + 'static,
510 {
511 self.clone().into_fn()
512 }
513
514 /// Convert to StatefulMutatingFunctionOnce
515 ///
516 /// **⚠️ Consumes `self`**: The original function will be unavailable
517 /// after calling this method.
518 ///
519 /// Converts a reusable stateful mutating function to a one-time function
520 /// that consumes itself on use. This enables passing `StatefulMutatingFunction`
521 /// to functions that require `StatefulMutatingFunctionOnce`.
522 ///
523 /// # Returns
524 ///
525 /// Returns a `BoxMutatingFunctionOnce<T, R>`
526 ///
527 /// # Examples
528 ///
529 /// ```rust
530 /// use qubit_function::{StatefulMutatingFunctionOnce,
531 /// StatefulMutatingFunction,
532 /// BoxStatefulMutatingFunction};
533 ///
534 /// fn takes_once<F: StatefulMutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
535 /// let result = func.apply(value);
536 /// println!("Result: {}", result);
537 /// }
538 ///
539 /// let func = BoxStatefulMutatingFunction::new(|x: &mut i32| {
540 /// *x *= 2;
541 /// *x
542 /// });
543 /// let mut value = 5;
544 /// takes_once(func.into_once(), &mut value);
545 /// ```
546 fn into_once(mut self) -> BoxMutatingFunctionOnce<T, R>
547 where
548 Self: Sized + 'static,
549 {
550 BoxMutatingFunctionOnce::new(move |t| self.apply(t))
551 }
552
553 /// Convert to StatefulMutatingFunctionOnce without consuming self
554 ///
555 /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
556 /// Clones the current function and converts the clone to a one-time function.
557 ///
558 /// # Returns
559 ///
560 /// Returns a `BoxMutatingFunctionOnce<T, R>`
561 ///
562 /// # Examples
563 ///
564 /// ```rust
565 /// use qubit_function::{StatefulMutatingFunctionOnce,
566 /// StatefulMutatingFunction,
567 /// BoxStatefulMutatingFunction};
568 ///
569 /// fn takes_once<F: StatefulMutatingFunctionOnce<i32, i32>>(func: F, value: &mut i32) {
570 /// let result = func.apply(value);
571 /// println!("Result: {}", result);
572 /// }
573 ///
574 /// let func = BoxStatefulMutatingFunction::new(|x: &mut i32| {
575 /// *x *= 2;
576 /// *x
577 /// });
578 /// let mut value = 5;
579 /// takes_once(func.to_once(), &mut value);
580 /// ```
581 fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
582 where
583 Self: Clone + 'static,
584 {
585 self.clone().into_once()
586 }
587}
588
589// =======================================================================
590// 2. Type Aliases
591// =======================================================================
592
593/// Type alias for Arc-wrapped stateful mutating function
594type ArcStatefulMutatingFunctionFn<T, R> = Arc<Mutex<dyn FnMut(&mut T) -> R + Send + 'static>>;
595
596/// Type alias for Rc-wrapped stateful mutating function
597type RcStatefulMutatingFunctionFn<T, R> = Rc<RefCell<dyn FnMut(&mut T) -> R>>;
598
599// =======================================================================
600// 3. BoxStatefulMutatingFunction - Single Ownership Implementation
601// =======================================================================
602
603/// BoxStatefulMutatingFunction struct
604///
605/// A stateful mutating function implementation based on
606/// `Box<dyn FnMut(&mut T) -> R>` for single ownership scenarios. This is the
607/// simplest and most efficient stateful mutating function type when sharing
608/// is not required.
609///
610/// # Features
611///
612/// - **Single Ownership**: Not cloneable, ownership moves on use
613/// - **Zero Overhead**: No reference counting or locking
614/// - **Stateful**: Can modify captured environment (uses `FnMut`)
615/// - **Builder Pattern**: Method chaining consumes `self` naturally
616/// - **Factory Methods**: Convenient constructors for common patterns
617///
618/// # Use Cases
619///
620/// Choose `BoxStatefulMutatingFunction` when:
621/// - The function needs to maintain internal state
622/// - Building pipelines where ownership naturally flows
623/// - No need to share the function across contexts
624/// - Performance is critical and no sharing overhead is acceptable
625///
626/// # Performance
627///
628/// `BoxStatefulMutatingFunction` has the best performance among the three
629/// function types:
630/// - No reference counting overhead
631/// - No lock acquisition or runtime borrow checking
632/// - Direct function call through vtable
633/// - Minimal memory footprint (single pointer)
634///
635/// # Examples
636///
637/// ```rust
638/// use qubit_function::{StatefulMutatingFunction,
639/// BoxStatefulMutatingFunction};
640///
641/// let mut counter = {
642/// let mut count = 0;
643/// BoxStatefulMutatingFunction::new(move |x: &mut i32| {
644/// count += 1;
645/// *x *= 2;
646/// count
647/// })
648/// };
649/// let mut value = 5;
650/// assert_eq!(counter.apply(&mut value), 1);
651/// assert_eq!(value, 10);
652/// ```
653///
654/// # Author
655///
656/// Haixing Hu
657pub struct BoxStatefulMutatingFunction<T, R> {
658 function: Box<dyn FnMut(&mut T) -> R>,
659 name: Option<String>,
660}
661
662impl<T, R> BoxStatefulMutatingFunction<T, R> {
663 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
664 impl_function_common_methods!(
665 BoxStatefulMutatingFunction<T, R>,
666 (FnMut(&mut T) -> R + 'static),
667 |f| Box::new(f)
668 );
669
670 // Generates: when(), and_then(), compose()
671 impl_box_function_methods!(
672 BoxStatefulMutatingFunction<T, R>,
673 BoxConditionalStatefulMutatingFunction,
674 Function // chains a non-mutating function after this mutating function
675 );
676}
677
678// Generates: Debug and Display implementations for BoxStatefulMutatingFunction<T, R>
679impl_function_debug_display!(BoxStatefulMutatingFunction<T, R>);
680
681// Generates: identity() method for BoxStatefulMutatingFunction<T, T>
682impl_function_identity_method!(BoxStatefulMutatingFunction<T, T>, mutating);
683
684// Implement StatefulMutatingFunction trait for BoxStatefulMutatingFunction<T, R>
685impl<T, R> StatefulMutatingFunction<T, R> for BoxStatefulMutatingFunction<T, R> {
686 fn apply(&mut self, t: &mut T) -> R {
687 (self.function)(t)
688 }
689
690 // Generates: into_box(), into_rc(), into_fn(), into_once()
691 impl_box_conversions!(
692 BoxStatefulMutatingFunction<T, R>,
693 RcStatefulMutatingFunction,
694 FnMut(&mut T) -> R,
695 BoxMutatingFunctionOnce
696 );
697}
698
699// =======================================================================
700// 4. RcStatefulMutatingFunction - Single-Threaded Shared Ownership
701// =======================================================================
702
703/// RcStatefulMutatingFunction struct
704///
705/// A stateful mutating function implementation based on
706/// `Rc<RefCell<dyn FnMut(&mut T) -> R>>` for single-threaded shared
707/// ownership scenarios. This type allows multiple references to the same
708/// function without the overhead of thread safety.
709///
710/// # Features
711///
712/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
713/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
714/// - **Stateful**: Can modify captured environment (uses `FnMut`)
715/// - **Chainable**: Method chaining via `&self` (non-consuming)
716/// - **Performance**: More efficient than `ArcStatefulMutatingFunction` (no
717/// locking)
718///
719/// # Use Cases
720///
721/// Choose `RcStatefulMutatingFunction` when:
722/// - The function needs to be shared within a single thread for stateful
723/// operations
724/// - Thread safety is not required
725/// - Performance is important (avoiding lock overhead)
726///
727/// # Examples
728///
729/// ```rust
730/// use qubit_function::{StatefulMutatingFunction,
731/// RcStatefulMutatingFunction};
732///
733/// let counter = {
734/// let mut count = 0;
735/// RcStatefulMutatingFunction::new(move |x: &mut i32| {
736/// count += 1;
737/// *x *= 2;
738/// count
739/// })
740/// };
741/// let mut clone = counter.clone();
742///
743/// let mut value = 5;
744/// assert_eq!(clone.apply(&mut value), 1);
745/// ```
746///
747/// # Author
748///
749/// Haixing Hu
750pub struct RcStatefulMutatingFunction<T, R> {
751 function: RcStatefulMutatingFunctionFn<T, R>,
752 name: Option<String>,
753}
754
755impl<T, R> RcStatefulMutatingFunction<T, R> {
756 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
757 impl_function_common_methods!(
758 RcStatefulMutatingFunction<T, R>,
759 (FnMut(&mut T) -> R + 'static),
760 |f| Rc::new(RefCell::new(f))
761 );
762
763 // Generates: when(), and_then(), compose()
764 impl_shared_function_methods!(
765 RcStatefulMutatingFunction<T, R>,
766 RcConditionalStatefulMutatingFunction,
767 into_rc,
768 Function, // chains a non-mutating function after this mutating function
769 'static
770 );
771}
772
773// Generates: Clone implementation for RcStatefulMutatingFunction<T, R>
774impl_function_clone!(RcStatefulMutatingFunction<T, R>);
775
776// Generates: Debug and Display implementations for RcStatefulMutatingFunction<T, R>
777impl_function_debug_display!(RcStatefulMutatingFunction<T, R>);
778
779// Generates: identity() method for RcStatefulMutatingFunction<T, T>
780impl_function_identity_method!(RcStatefulMutatingFunction<T, T>, mutating);
781
782// Implement StatefulMutatingFunction trait for RcStatefulMutatingFunction<T, R>
783impl<T, R> StatefulMutatingFunction<T, R> for RcStatefulMutatingFunction<T, R> {
784 fn apply(&mut self, t: &mut T) -> R {
785 (self.function.borrow_mut())(t)
786 }
787
788 // Use macro to implement conversion methods
789 impl_rc_conversions!(
790 RcStatefulMutatingFunction<T, R>,
791 BoxStatefulMutatingFunction,
792 BoxMutatingFunctionOnce,
793 FnMut(input: &mut T) -> R
794 );
795}
796
797// =======================================================================
798// 5. ArcStatefulMutatingFunction - Thread-Safe Shared Ownership
799// =======================================================================
800
801/// ArcStatefulMutatingFunction struct
802///
803/// A stateful mutating function implementation based on
804/// `Arc<Mutex<dyn FnMut(&mut T) -> R + Send>>` for thread-safe shared
805/// ownership scenarios. This type allows the function to be safely shared
806/// and used across multiple threads.
807///
808/// # Features
809///
810/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
811/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
812/// - **Stateful**: Can modify captured environment (uses `FnMut`)
813/// - **Chainable**: Method chaining via `&self` (non-consuming)
814///
815/// # Use Cases
816///
817/// Choose `ArcStatefulMutatingFunction` when:
818/// - The function needs to be shared across multiple threads for stateful
819/// operations
820/// - Concurrent task processing (e.g., thread pools)
821/// - Thread safety is required (Send + Sync)
822///
823/// # Examples
824///
825/// ```rust
826/// use qubit_function::{StatefulMutatingFunction,
827/// ArcStatefulMutatingFunction};
828///
829/// let counter = {
830/// let mut count = 0;
831/// ArcStatefulMutatingFunction::new(move |x: &mut i32| {
832/// count += 1;
833/// *x *= 2;
834/// count
835/// })
836/// };
837/// let mut clone = counter.clone();
838///
839/// let mut value = 5;
840/// assert_eq!(clone.apply(&mut value), 1);
841/// ```
842///
843/// # Author
844///
845/// Haixing Hu
846pub struct ArcStatefulMutatingFunction<T, R> {
847 function: ArcStatefulMutatingFunctionFn<T, R>,
848 name: Option<String>,
849}
850
851impl<T, R> ArcStatefulMutatingFunction<T, R> {
852 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
853 impl_function_common_methods!(
854 ArcStatefulMutatingFunction<T, R>,
855 (FnMut(&mut T) -> R + Send + 'static),
856 |f| Arc::new(Mutex::new(f))
857 );
858
859 // Generates: when(), and_then(), compose()
860 impl_shared_function_methods!(
861 ArcStatefulMutatingFunction<T, R>,
862 ArcConditionalStatefulMutatingFunction,
863 into_arc,
864 Function, // chains a non-mutating function after this mutating function
865 Send + Sync + 'static
866 );
867}
868
869// Generates: Clone implementation for ArcStatefulMutatingFunction<T, R>
870impl_function_clone!(ArcStatefulMutatingFunction<T, R>);
871
872// Generates: Debug and Display implementations for ArcStatefulMutatingFunction<T, R>
873impl_function_debug_display!(ArcStatefulMutatingFunction<T, R>);
874
875// Generates: identity() method for ArcStatefulMutatingFunction<T, T>
876impl_function_identity_method!(ArcStatefulMutatingFunction<T, T>, mutating);
877
878// Implement StatefulMutatingFunction trait for ArcStatefulMutatingFunction<T, R>
879impl<T, R> StatefulMutatingFunction<T, R> for ArcStatefulMutatingFunction<T, R> {
880 fn apply(&mut self, t: &mut T) -> R {
881 (self.function.lock())(t)
882 }
883
884 // Use macro to implement conversion methods
885 impl_arc_conversions!(
886 ArcStatefulMutatingFunction<T, R>,
887 BoxStatefulMutatingFunction,
888 RcStatefulMutatingFunction,
889 BoxMutatingFunctionOnce,
890 FnMut(input: &mut T) -> R
891 );
892}
893
894// =======================================================================
895// 6. Implement StatefulMutatingFunction trait for closures
896// =======================================================================
897
898impl<T, R, F> StatefulMutatingFunction<T, R> for F
899where
900 F: FnMut(&mut T) -> R,
901{
902 fn apply(&mut self, input: &mut T) -> R {
903 self(input)
904 }
905
906 fn into_box(self) -> BoxStatefulMutatingFunction<T, R>
907 where
908 Self: Sized + 'static,
909 {
910 BoxStatefulMutatingFunction::new(self)
911 }
912
913 fn into_rc(self) -> RcStatefulMutatingFunction<T, R>
914 where
915 Self: Sized + 'static,
916 {
917 RcStatefulMutatingFunction::new(self)
918 }
919
920 fn into_arc(self) -> ArcStatefulMutatingFunction<T, R>
921 where
922 Self: Sized + Send + 'static,
923 {
924 ArcStatefulMutatingFunction::new(self)
925 }
926
927 fn into_fn(self) -> impl FnMut(&mut T) -> R
928 where
929 Self: Sized + 'static,
930 {
931 self
932 }
933
934 fn to_box(&self) -> BoxStatefulMutatingFunction<T, R>
935 where
936 Self: Sized + Clone + 'static,
937 {
938 let cloned = self.clone();
939 BoxStatefulMutatingFunction::new(cloned)
940 }
941
942 fn to_rc(&self) -> RcStatefulMutatingFunction<T, R>
943 where
944 Self: Sized + Clone + 'static,
945 {
946 let cloned = self.clone();
947 RcStatefulMutatingFunction::new(cloned)
948 }
949
950 fn to_arc(&self) -> ArcStatefulMutatingFunction<T, R>
951 where
952 Self: Sized + Clone + Send + 'static,
953 {
954 let cloned = self.clone();
955 ArcStatefulMutatingFunction::new(cloned)
956 }
957
958 fn to_fn(&self) -> impl FnMut(&mut T) -> R
959 where
960 Self: Sized + Clone + 'static,
961 {
962 self.clone()
963 }
964
965 fn into_once(self) -> BoxMutatingFunctionOnce<T, R>
966 where
967 Self: Sized + 'static,
968 {
969 BoxMutatingFunctionOnce::new(self)
970 }
971
972 fn to_once(&self) -> BoxMutatingFunctionOnce<T, R>
973 where
974 Self: Sized + Clone + 'static,
975 {
976 BoxMutatingFunctionOnce::new(self.clone())
977 }
978}
979
980// =======================================================================
981// 7. Provide extension methods for closures
982// =======================================================================
983
984// Generates: FnMutStatefulMutatingFunctionOps trait and blanket implementation
985impl_fn_ops_trait!(
986 (FnMut(&mut T) -> R),
987 FnStatefulMutatingFunctionOps,
988 BoxStatefulMutatingFunction,
989 StatefulMutatingFunction,
990 BoxConditionalStatefulMutatingFunction
991);
992
993// ============================================================================
994// BoxConditionalStatefulMutatingFunction - Box-based Conditional Stateful Mutating Function
995// ============================================================================
996
997/// BoxConditionalStatefulMutatingFunction struct
998///
999/// A conditional function that only executes when a predicate is satisfied.
1000/// Uses `BoxStatefulMutatingFunction` and `BoxPredicate` for single ownership semantics.
1001///
1002/// This type is typically created by calling `BoxStatefulMutatingFunction::when()` and is
1003/// designed to work with the `or_else()` method to create if-then-else logic.
1004///
1005/// # Features
1006///
1007/// - **Single Ownership**: Not cloneable, consumes `self` on use
1008/// - **Conditional Execution**: Only transforms when predicate returns `true`
1009/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1010/// - **Implements Function**: Can be used anywhere a `Function` is expected
1011///
1012/// # Examples
1013///
1014/// ## With or_else Branch
1015///
1016/// ```rust
1017/// use qubit_function::{StatefulMutatingFunction, BoxStatefulMutatingFunction};
1018///
1019/// let double = BoxStatefulMutatingFunction::new(|x: &mut i32| x * 2);
1020/// let negate = BoxStatefulMutatingFunction::new(|x: &mut i32| -x);
1021/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
1022///
1023/// assert_eq!(conditional.apply(5), 10); // when branch executed
1024/// assert_eq!(conditional.apply(-5), 5); // or_else branch executed
1025/// ```
1026///
1027/// # Author
1028///
1029/// Haixing Hu
1030pub struct BoxConditionalStatefulMutatingFunction<T, R> {
1031 function: BoxStatefulMutatingFunction<T, R>,
1032 predicate: BoxPredicate<T>,
1033}
1034
1035// Use macro to generate conditional function implementations
1036impl_box_conditional_function!(
1037 BoxConditionalStatefulMutatingFunction<T, R>,
1038 BoxStatefulMutatingFunction,
1039 StatefulMutatingFunction
1040);
1041
1042// Use macro to generate conditional function debug and display implementations
1043impl_conditional_function_debug_display!(BoxConditionalStatefulMutatingFunction<T, R>);
1044
1045// ============================================================================
1046// RcConditionalStatefulMutatingFunction - Rc-based Conditional Stateful Mutating Function
1047// ============================================================================
1048
1049/// RcConditionalStatefulMutatingFunction struct
1050///
1051/// A single-threaded conditional function that only executes when a
1052/// predicate is satisfied. Uses `RcStatefulMutatingFunction` and `RcPredicate` for shared
1053/// ownership within a single thread.
1054///
1055/// This type is typically created by calling `RcStatefulMutatingFunction::when()` and is
1056/// designed to work with the `or_else()` method to create if-then-else logic.
1057///
1058/// # Features
1059///
1060/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1061/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1062/// - **Conditional Execution**: Only transforms when predicate returns `true`
1063/// - **No Lock Overhead**: More efficient than `ArcConditionalFunction`
1064///
1065/// # Examples
1066///
1067/// ```rust
1068/// use qubit_function::{StatefulMutatingFunction, RcStatefulMutatingFunction};
1069///
1070/// let double = RcStatefulMutatingFunction::new(|x: &mut i32| x * 2);
1071/// let identity = RcStatefulMutatingFunction::<i32, i32>::identity();
1072/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1073///
1074/// let conditional_clone = conditional.clone();
1075///
1076/// assert_eq!(conditional.apply(5), 10);
1077/// assert_eq!(conditional_clone.apply(-5), -5);
1078/// ```
1079///
1080/// # Author
1081///
1082/// Haixing Hu
1083pub struct RcConditionalStatefulMutatingFunction<T, R> {
1084 function: RcStatefulMutatingFunction<T, R>,
1085 predicate: RcPredicate<T>,
1086}
1087
1088// Use macro to generate conditional function implementations
1089impl_shared_conditional_function!(
1090 RcConditionalStatefulMutatingFunction<T, R>,
1091 RcStatefulMutatingFunction,
1092 StatefulMutatingFunction,
1093 'static
1094);
1095
1096// Use macro to generate conditional function clone implementations
1097impl_conditional_function_clone!(RcConditionalStatefulMutatingFunction<T, R>);
1098
1099// Use macro to generate conditional function debug and display implementations
1100impl_conditional_function_debug_display!(RcConditionalStatefulMutatingFunction<T, R>);
1101
1102// ============================================================================
1103// ArcConditionalStatefulMutatingFunction - Arc-based Conditional Stateful Mutating Function
1104// ============================================================================
1105
1106/// ArcConditionalStatefulMutatingFunction struct
1107///
1108/// A thread-safe conditional function that only executes when a predicate is
1109/// satisfied. Uses `ArcStatefulMutatingFunction` and `ArcPredicate` for shared ownership
1110/// across threads.
1111///
1112/// This type is typically created by calling `ArcStatefulMutatingFunction::when()` and is
1113/// designed to work with the `or_else()` method to create if-then-else logic.
1114///
1115/// # Features
1116///
1117/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1118/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1119/// - **Conditional Execution**: Only transforms when predicate returns `true`
1120/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1121///
1122/// # Examples
1123///
1124/// ```rust
1125/// use qubit_function::{StatefulMutatingFunction, ArcStatefulMutatingFunction};
1126///
1127/// let double = ArcStatefulMutatingFunction::new(|x: &mut i32| x * 2);
1128/// let identity = ArcStatefulMutatingFunction::<i32, i32>::identity();
1129/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1130///
1131/// let conditional_clone = conditional.clone();
1132///
1133/// assert_eq!(conditional.apply(5), 10);
1134/// assert_eq!(conditional_clone.apply(-5), -5);
1135/// ```
1136///
1137/// # Author
1138///
1139/// Haixing Hu
1140pub struct ArcConditionalStatefulMutatingFunction<T, R> {
1141 function: ArcStatefulMutatingFunction<T, R>,
1142 predicate: ArcPredicate<T>,
1143}
1144
1145// Use macro to generate conditional function implementations
1146impl_shared_conditional_function!(
1147 ArcConditionalStatefulMutatingFunction<T, R>,
1148 ArcStatefulMutatingFunction,
1149 StatefulMutatingFunction,
1150 Send + Sync + 'static
1151);
1152
1153// Use macro to generate conditional function clone implementations
1154impl_conditional_function_clone!(ArcConditionalStatefulMutatingFunction<T, R>);
1155
1156// Use macro to generate conditional function debug and display implementations
1157impl_conditional_function_debug_display!(ArcConditionalStatefulMutatingFunction<T, R>);