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