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