qubit_function/functions/stateful_function.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # StatefulFunction Types
10//!
11//! Provides Rust implementations of stateful function traits for stateful value
12//! transformation. StatefulFunctions consume input values (taking ownership) and
13//! produce output values while allowing internal state modification.
14//!
15//! It is similar to the `FnMut(&T) -> R` trait in the standard library.
16//!
17//! This module provides the `StatefulFunction<T, R>` trait and three implementations:
18//!
19//! - [`BoxStatefulFunction`]: Single ownership, not cloneable
20//! - [`ArcStatefulFunction`]: Thread-safe shared ownership, cloneable
21//! - [`RcStatefulFunction`]: Single-threaded shared ownership, cloneable
22//!
23//! # Author
24//!
25//! Haixing Hu
26use std::cell::RefCell;
27use std::rc::Rc;
28use std::sync::Arc;
29
30use parking_lot::Mutex;
31
32use crate::functions::{
33 function_once::BoxFunctionOnce,
34 macros::{
35 impl_box_conditional_function,
36 impl_box_function_methods,
37 impl_conditional_function_clone,
38 impl_conditional_function_debug_display,
39 impl_fn_ops_trait,
40 impl_function_clone,
41 impl_function_common_methods,
42 impl_function_constant_method,
43 impl_function_debug_display,
44 impl_function_identity_method,
45 impl_shared_conditional_function,
46 impl_shared_function_methods,
47 },
48};
49use crate::macros::{
50 impl_arc_conversions,
51 impl_box_conversions,
52 impl_rc_conversions,
53};
54use crate::predicates::predicate::{
55 ArcPredicate,
56 BoxPredicate,
57 Predicate,
58 RcPredicate,
59};
60
61// ============================================================================
62// Core Trait
63// ============================================================================
64
65/// StatefulFunction trait - transforms values from type T to type R with state
66///
67/// Defines the behavior of a stateful transformation: converting a value
68/// of type `T` to a value of type `R` by consuming the input while
69/// allowing modification of internal state. This is analogous to
70/// `FnMut(&T) -> R` in Rust's standard library.
71///
72/// # Type Parameters
73///
74/// * `T` - The type of the input value (consumed)
75/// * `R` - The type of the output value
76///
77/// # Author
78///
79/// Haixing Hu
80pub trait StatefulFunction<T, R> {
81 /// Applies the mapping to the input value to produce an output value
82 ///
83 /// # Parameters
84 ///
85 /// * `t` - The input value to transform (consumed)
86 ///
87 /// # Returns
88 ///
89 /// The transformed output value
90 fn apply(&mut self, t: &T) -> R;
91
92 /// Converts to BoxStatefulFunction
93 ///
94 /// **⚠️ Consumes `self`**: The original stateful function becomes unavailable
95 /// after calling this method.
96 ///
97 /// # Returns
98 ///
99 /// Returns `BoxStatefulFunction<T, R>`
100 ///
101 /// # Default Implementation
102 ///
103 /// The default implementation wraps `self` in a `BoxStatefulFunction` by
104 /// creating a new closure that calls `self.apply()`. This is a lightweight
105 /// adapter, but it is not strictly zero-cost.
106 ///
107 /// # Examples
108 ///
109 /// ```rust
110 /// use qubit_function::{StatefulFunction, BoxStatefulFunction};
111 ///
112 /// struct CustomStatefulFunction {
113 /// multiplier: i32,
114 /// }
115 ///
116 /// impl StatefulFunction<i32, i32> for CustomStatefulFunction {
117 /// fn apply(&mut self, input: &i32) -> i32 {
118 /// self.multiplier += 1;
119 /// input * self.multiplier
120 /// }
121 /// }
122 ///
123 /// let function = CustomStatefulFunction { multiplier: 0 };
124 /// let mut boxed = function.into_box();
125 /// assert_eq!(boxed.apply(&10), 10); // 10 * 1
126 /// assert_eq!(boxed.apply(&10), 20); // 10 * 2
127 /// ```
128 fn into_box(mut self) -> BoxStatefulFunction<T, R>
129 where
130 Self: Sized + 'static,
131 {
132 BoxStatefulFunction::new(move |t| self.apply(t))
133 }
134
135 /// Converts to RcStatefulFunction
136 ///
137 /// **⚠️ Consumes `self`**: The original stateful function becomes unavailable
138 /// after calling this method.
139 ///
140 /// # Returns
141 ///
142 /// Returns `RcStatefulFunction<T, R>`
143 ///
144 /// # Default Implementation
145 ///
146 /// The default implementation first converts to `BoxStatefulFunction` using
147 /// `into_box()`, then wraps it in `RcStatefulFunction`. Specific implementations
148 /// may override this for better efficiency.
149 ///
150 /// # Examples
151 ///
152 /// ```rust
153 /// use qubit_function::{StatefulFunction, RcStatefulFunction};
154 ///
155 /// struct CustomStatefulFunction {
156 /// multiplier: i32,
157 /// }
158 ///
159 /// impl StatefulFunction<i32, i32> for CustomStatefulFunction {
160 /// fn apply(&mut self, input: &i32) -> i32 {
161 /// self.multiplier += 1;
162 /// input * self.multiplier
163 /// }
164 /// }
165 ///
166 /// let function = CustomStatefulFunction { multiplier: 0 };
167 /// let mut rc_function = function.into_rc();
168 /// assert_eq!(rc_function.apply(&10), 10); // 10 * 1
169 /// assert_eq!(rc_function.apply(&10), 20); // 10 * 2
170 /// ```
171 fn into_rc(mut self) -> RcStatefulFunction<T, R>
172 where
173 Self: Sized + 'static,
174 {
175 RcStatefulFunction::new(move |t| self.apply(t))
176 }
177
178 /// Converts to ArcStatefulFunction
179 ///
180 /// **⚠️ Consumes `self`**: The original stateful function becomes unavailable
181 /// after calling this method.
182 ///
183 /// # Returns
184 ///
185 /// Returns `ArcStatefulFunction<T, R>`
186 ///
187 /// # Default Implementation
188 ///
189 /// The default implementation wraps `self` in an `ArcStatefulFunction` by creating
190 /// a new closure that calls `self.apply()`. Note that this requires `self`
191 /// to implement `Send` due to Arc's thread-safety requirements.
192 ///
193 /// # Examples
194 ///
195 /// ```rust
196 /// use qubit_function::{StatefulFunction, ArcStatefulFunction};
197 ///
198 /// struct CustomStatefulFunction {
199 /// multiplier: i32,
200 /// }
201 ///
202 /// impl StatefulFunction<i32, i32> for CustomStatefulFunction {
203 /// fn apply(&mut self, input: &i32) -> i32 {
204 /// self.multiplier += 1;
205 /// input * self.multiplier
206 /// }
207 /// }
208 ///
209 /// let function = CustomStatefulFunction { multiplier: 0 };
210 /// let mut arc_function = function.into_arc();
211 /// assert_eq!(arc_function.apply(&10), 10); // 10 * 1
212 /// assert_eq!(arc_function.apply(&10), 20); // 10 * 2
213 /// ```
214 fn into_arc(mut self) -> ArcStatefulFunction<T, R>
215 where
216 Self: Sized + Send + 'static,
217 {
218 ArcStatefulFunction::new(move |t| self.apply(t))
219 }
220
221 /// Converts to a closure implementing `FnMut(&T) -> R`
222 ///
223 /// **⚠️ Consumes `self`**: The original stateful function becomes unavailable
224 /// after calling this method.
225 ///
226 /// # Returns
227 ///
228 /// Returns an implementation of `FnMut(&T) -> R`
229 ///
230 /// # Default Implementation
231 ///
232 /// The default implementation creates a new closure that calls `self.apply()`.
233 /// Specific implementations may override this for better efficiency.
234 ///
235 /// # Examples
236 ///
237 /// ```rust
238 /// use qubit_function::{StatefulFunction, BoxStatefulFunction};
239 ///
240 /// let function = BoxStatefulFunction::new(|x: &i32| x * 2);
241 /// let mut closure = function.into_fn();
242 /// assert_eq!(closure(&10), 20);
243 /// assert_eq!(closure(&15), 30);
244 /// ```
245 fn into_fn(mut self) -> impl FnMut(&T) -> R
246 where
247 Self: Sized + 'static,
248 {
249 move |t| self.apply(t)
250 }
251
252 /// Converts to a mutable closure (`FnMut`) with an explicit method name.
253 ///
254 /// This is a naming alias of [`StatefulFunction::into_fn`] to make the
255 /// mutability of the returned closure explicit.
256 fn into_mut_fn(self) -> impl FnMut(&T) -> R
257 where
258 Self: Sized + 'static,
259 {
260 self.into_fn()
261 }
262
263 /// Convert to StatefulFunctionOnce
264 ///
265 /// **⚠️ Consumes `self`**: The original function will be unavailable
266 /// after calling this method.
267 ///
268 /// Converts a reusable stateful function to a one-time function that
269 /// consumes itself on use. This enables passing `StatefulFunction` to
270 /// functions that require `StatefulFunctionOnce`.
271 ///
272 /// # Returns
273 ///
274 /// Returns a `BoxFunctionOnce<T, R>`
275 ///
276 /// # Examples
277 ///
278 /// ```rust
279 /// use qubit_function::{FunctionOnce, StatefulFunction,
280 /// RcStatefulFunction};
281 ///
282 /// fn takes_once<F: FunctionOnce<i32, i32>>(func: F, value: &i32) {
283 /// let result = func.apply(value);
284 /// println!("Result: {}", result);
285 /// }
286 ///
287 /// let func = RcStatefulFunction::new(|x: &i32| x * 2);
288 /// takes_once(func.into_once(), &5);
289 /// ```
290 fn into_once(mut self) -> BoxFunctionOnce<T, R>
291 where
292 Self: Sized + 'static,
293 {
294 BoxFunctionOnce::new(move |t| self.apply(t))
295 }
296
297 /// Non-consuming conversion to `BoxStatefulFunction`.
298 ///
299 /// Default implementation requires `Self: Clone` and wraps a cloned
300 /// instance in a `RefCell` so the returned stateful function can mutate state
301 /// across calls.
302 fn to_box(&self) -> BoxStatefulFunction<T, R>
303 where
304 Self: Clone + 'static,
305 {
306 self.clone().into_box()
307 }
308
309 /// Non-consuming conversion to `RcStatefulFunction`.
310 ///
311 /// Default implementation clones `self` into an `Rc<RefCell<_>>` so the
312 /// resulting stateful function can be shared within a single thread.
313 fn to_rc(&self) -> RcStatefulFunction<T, R>
314 where
315 Self: Clone + 'static,
316 {
317 self.clone().into_rc()
318 }
319
320 /// Non-consuming conversion to `ArcStatefulFunction` (thread-safe).
321 ///
322 /// Default implementation requires `Self: Clone + Send + Sync` and wraps
323 /// the cloned instance in `Arc<Mutex<_>>` so it can be used across
324 /// threads.
325 fn to_arc(&self) -> ArcStatefulFunction<T, R>
326 where
327 Self: Clone + Send + 'static,
328 {
329 self.clone().into_arc()
330 }
331
332 /// Non-consuming conversion to a closure (`FnMut(&T) -> R`).
333 ///
334 /// Default implementation clones `self` into a `RefCell` and returns a
335 /// closure that calls `apply` on the interior mutable value.
336 fn to_fn(&self) -> impl FnMut(&T) -> R
337 where
338 Self: Sized + Clone + 'static,
339 {
340 self.clone().into_fn()
341 }
342
343 /// Non-consuming conversion to a mutable closure (`FnMut`) with an explicit
344 /// method name.
345 ///
346 /// This is a naming alias of [`StatefulFunction::to_fn`] and preserves the
347 /// same clone-based behavior.
348 fn to_mut_fn(&self) -> impl FnMut(&T) -> R
349 where
350 Self: Sized + Clone + 'static,
351 {
352 self.to_fn()
353 }
354
355 /// Convert to StatefulFunctionOnce without consuming self
356 ///
357 /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
358 /// Clones the current function and converts the clone to a one-time function.
359 ///
360 /// # Returns
361 ///
362 /// Returns a `BoxFunctionOnce<T, R>`
363 ///
364 /// # Examples
365 ///
366 /// ```rust
367 /// use qubit_function::{FunctionOnce, StatefulFunction,
368 /// RcStatefulFunction};
369 ///
370 /// fn takes_once<F: FunctionOnce<i32, i32>>(func: F, value: &i32) {
371 /// let result = func.apply(value);
372 /// println!("Result: {}", result);
373 /// }
374 ///
375 /// let func = RcStatefulFunction::new(|x: &i32| x * 2);
376 /// takes_once(func.to_once(), &5);
377 /// ```
378 fn to_once(&self) -> BoxFunctionOnce<T, R>
379 where
380 Self: Clone + 'static,
381 {
382 self.clone().into_once()
383 }
384}
385
386// ============================================================================
387// BoxStatefulFunction - Box<dyn FnMut(&T) -> R>
388// ============================================================================
389
390/// BoxStatefulFunction - stateful function wrapper based on `Box<dyn FnMut>`
391///
392/// A stateful function wrapper that provides single ownership with reusable stateful
393/// transformation. The stateful function consumes the input and can be called
394/// multiple times while maintaining internal state.
395///
396/// # Features
397///
398/// - **Based on**: `Box<dyn FnMut(&T) -> R>`
399/// - **Ownership**: Single ownership, cannot be cloned
400/// - **Reusability**: Can be called multiple times (each call consumes
401/// its input)
402/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
403/// - **Statefulness**: Can modify internal state between calls
404///
405/// # Author
406///
407/// Haixing Hu
408pub struct BoxStatefulFunction<T, R> {
409 function: Box<dyn FnMut(&T) -> R>,
410 name: Option<String>,
411}
412
413impl<T, R> BoxStatefulFunction<T, R> {
414 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
415 impl_function_common_methods!(
416 BoxStatefulFunction<T, R>,
417 (FnMut(&T) -> R + 'static),
418 |f| Box::new(f)
419 );
420
421 // Generates: when(), and_then(), compose()
422 impl_box_function_methods!(
423 BoxStatefulFunction<T, R>,
424 BoxConditionalStatefulFunction,
425 StatefulFunction
426 );
427}
428
429// Generates: constant() method for BoxStatefulFunction<T, R>
430impl_function_constant_method!(BoxStatefulFunction<T, R>, 'static);
431
432// Generates: identity() method for BoxStatefulFunction<T, T>
433impl_function_identity_method!(BoxStatefulFunction<T, T>);
434
435// Generates: Debug and Display implementations for BoxStatefulFunction<T, R>
436impl_function_debug_display!(BoxStatefulFunction<T, R>);
437
438// Implement StatefulFunction trait for BoxStatefulFunction<T, R>
439impl<T, R> StatefulFunction<T, R> for BoxStatefulFunction<T, R> {
440 fn apply(&mut self, t: &T) -> R {
441 (self.function)(t)
442 }
443
444 // Generates: into_box(), into_rc(), into_fn(), into_once()
445 impl_box_conversions!(
446 BoxStatefulFunction<T, R>,
447 RcStatefulFunction,
448 FnMut(&T) -> R,
449 BoxFunctionOnce
450 );
451}
452
453// ============================================================================
454// RcStatefulFunction - Rc<RefCell<dyn FnMut(&T) -> R>>
455// ============================================================================
456
457/// RcStatefulFunction - single-threaded function wrapper
458///
459/// A single-threaded, clonable function wrapper optimized for scenarios
460/// that require sharing without thread-safety overhead.
461///
462/// # Features
463///
464/// - **Based on**: `Rc<RefCell<dyn FnMut(&T) -> R>>`
465/// - **Ownership**: Shared ownership via reference counting (non-atomic)
466/// - **Reusability**: Can be called multiple times (each call consumes
467/// its input)
468/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
469/// - **Clonable**: Cheap cloning via `Rc::clone`
470/// - **Statefulness**: Can modify internal state between calls
471///
472/// # Author
473///
474/// Haixing Hu
475pub struct RcStatefulFunction<T, R> {
476 function: RcStatefulFn<T, R>,
477 name: Option<String>,
478}
479
480type RcStatefulFn<T, R> = Rc<RefCell<dyn FnMut(&T) -> R>>;
481
482impl<T, R> RcStatefulFunction<T, R> {
483 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
484 impl_function_common_methods!(
485 RcStatefulFunction<T, R>,
486 (FnMut(&T) -> R + 'static),
487 |f| Rc::new(RefCell::new(f))
488 );
489
490 // Generates: when(), and_then(), compose()
491 impl_shared_function_methods!(
492 RcStatefulFunction<T, R>,
493 RcConditionalStatefulFunction,
494 into_rc,
495 StatefulFunction,
496 'static
497 );
498}
499
500// Generates: constant() method for RcStatefulFunction<T, R>
501impl_function_constant_method!(RcStatefulFunction<T, R>, 'static);
502
503// Generates: identity() method for RcStatefulFunction<T, T>
504impl_function_identity_method!(RcStatefulFunction<T, T>);
505
506// Generates: Clone implementation for RcStatefulFunction<T, R>
507impl_function_clone!(RcStatefulFunction<T, R>);
508
509// Generates: Debug and Display implementations for RcStatefulFunction<T, R>
510impl_function_debug_display!(RcStatefulFunction<T, R>);
511
512// Implement StatefulFunction trait for RcStatefulFunction<T, R>
513impl<T, R> StatefulFunction<T, R> for RcStatefulFunction<T, R> {
514 fn apply(&mut self, t: &T) -> R {
515 (self.function.borrow_mut())(t)
516 }
517
518 // Use macro to implement conversion methods
519 impl_rc_conversions!(
520 RcStatefulFunction<T, R>,
521 BoxStatefulFunction,
522 BoxFunctionOnce,
523 FnMut(t: &T) -> R
524 );
525}
526
527// ============================================================================
528// ArcStatefulFunction - Arc<Mutex<dyn FnMut(&T) -> R + Send>>
529// ============================================================================
530
531/// ArcStatefulFunction - thread-safe function wrapper
532///
533/// A thread-safe, clonable function wrapper suitable for multi-threaded
534/// scenarios. Can be called multiple times and shared across threads
535/// while maintaining internal state.
536///
537/// # Features
538///
539/// - **Based on**: `Arc<Mutex<dyn FnMut(&T) -> R + Send>>`
540/// - **Ownership**: Shared ownership via reference counting
541/// - **Reusability**: Can be called multiple times (each call consumes
542/// its input)
543/// - **Thread Safety**: Thread-safe (`Send` required)
544/// - **Clonable**: Cheap cloning via `Arc::clone`
545/// - **Statefulness**: Can modify internal state between calls
546///
547/// # Author
548///
549/// Haixing Hu
550pub struct ArcStatefulFunction<T, R> {
551 function: ArcStatefulFn<T, R>,
552 name: Option<String>,
553}
554
555type ArcStatefulFn<T, R> = Arc<Mutex<dyn FnMut(&T) -> R + Send + 'static>>;
556
557impl<T, R> ArcStatefulFunction<T, R> {
558 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
559 impl_function_common_methods!(
560 ArcStatefulFunction<T, R>,
561 (FnMut(&T) -> R + Send + 'static),
562 |f| Arc::new(Mutex::new(f))
563 );
564
565 // Generates: when(), and_then(), compose()
566 impl_shared_function_methods!(
567 ArcStatefulFunction<T, R>,
568 ArcConditionalStatefulFunction,
569 into_arc,
570 StatefulFunction,
571 Send + Sync + 'static
572 );
573}
574
575// Generates: constant() method for ArcStatefulFunction<T, R>
576impl_function_constant_method!(ArcStatefulFunction<T, R>, Send + Sync + 'static);
577
578// Generates: identity() method for ArcStatefulFunction<T, T>
579impl_function_identity_method!(ArcStatefulFunction<T, T>);
580
581// Generates: Clone implementation for ArcStatefulFunction<T, R>
582impl_function_clone!(ArcStatefulFunction<T, R>);
583
584// Generates: Debug and Display implementations for ArcStatefulFunction<T, R>
585impl_function_debug_display!(ArcStatefulFunction<T, R>);
586
587// Implement StatefulFunction trait for ArcStatefulFunction<T, R>
588impl<T, R> StatefulFunction<T, R> for ArcStatefulFunction<T, R> {
589 fn apply(&mut self, t: &T) -> R {
590 (self.function.lock())(t)
591 }
592
593 // Use macro to implement conversion methods
594 impl_arc_conversions!(
595 ArcStatefulFunction<T, R>,
596 BoxStatefulFunction,
597 RcStatefulFunction,
598 BoxFunctionOnce,
599 FnMut(t: &T) -> R
600 );
601}
602
603// ============================================================================
604// Blanket implementation for standard FnMut trait
605// ============================================================================
606
607/// Implement StatefulFunction<T, R> for any type that implements FnMut(&T) -> R
608///
609/// This allows closures to be used directly with our StatefulFunction trait
610/// without wrapping.
611///
612/// # Examples
613///
614/// ```rust
615/// use qubit_function::StatefulFunction;
616///
617/// let mut counter = 0;
618/// let mut function = |x: &i32| {
619/// counter += 1;
620/// *x + counter
621/// };
622///
623/// assert_eq!(function.apply(&10), 11);
624/// assert_eq!(function.apply(&10), 12);
625/// ```
626///
627/// # Author
628///
629/// Haixing Hu
630impl<F, T, R> StatefulFunction<T, R> for F
631where
632 F: FnMut(&T) -> R,
633{
634 fn apply(&mut self, t: &T) -> R {
635 self(t)
636 }
637
638 fn into_box(self) -> BoxStatefulFunction<T, R>
639 where
640 Self: Sized + 'static,
641 {
642 BoxStatefulFunction::new(self)
643 }
644
645 fn into_rc(self) -> RcStatefulFunction<T, R>
646 where
647 Self: Sized + 'static,
648 {
649 RcStatefulFunction::new(self)
650 }
651
652 fn into_arc(self) -> ArcStatefulFunction<T, R>
653 where
654 Self: Sized + Send + 'static,
655 {
656 ArcStatefulFunction::new(self)
657 }
658
659 fn into_fn(self) -> impl FnMut(&T) -> R
660 where
661 Self: Sized + 'static,
662 {
663 self
664 }
665
666 fn to_box(&self) -> BoxStatefulFunction<T, R>
667 where
668 Self: Sized + Clone + 'static,
669 {
670 self.clone().into_box()
671 }
672
673 fn to_rc(&self) -> RcStatefulFunction<T, R>
674 where
675 Self: Sized + Clone + 'static,
676 {
677 self.clone().into_rc()
678 }
679
680 fn to_arc(&self) -> ArcStatefulFunction<T, R>
681 where
682 Self: Sized + Clone + Send + 'static,
683 {
684 self.clone().into_arc()
685 }
686
687 fn to_fn(&self) -> impl FnMut(&T) -> R
688 where
689 Self: Sized + Clone + 'static,
690 {
691 self.clone()
692 }
693
694 fn into_once(self) -> BoxFunctionOnce<T, R>
695 where
696 Self: Sized + 'static,
697 {
698 BoxFunctionOnce::new(self)
699 }
700
701 fn to_once(&self) -> BoxFunctionOnce<T, R>
702 where
703 Self: Sized + Clone + 'static,
704 {
705 BoxFunctionOnce::new(self.clone())
706 }
707}
708
709// ============================================================================
710// FnStatefulFunctionOps - Extension trait for closure functions
711// ============================================================================
712
713// Generates: FnStatefulFunctionOps trait and blanket implementation
714impl_fn_ops_trait!(
715 (FnMut(&T) -> R),
716 FnStatefulFunctionOps,
717 BoxStatefulFunction,
718 StatefulFunction,
719 BoxConditionalStatefulFunction
720);
721
722// ============================================================================
723// BoxConditionalStatefulFunction - Box-based Conditional StatefulFunction
724// ============================================================================
725
726/// BoxConditionalStatefulFunction struct
727///
728/// A conditional function that only executes when a predicate is satisfied.
729/// Uses `BoxStatefulFunction` and `BoxPredicate` for single ownership semantics.
730///
731/// This type is typically created by calling `BoxStatefulFunction::when()` and is
732/// designed to work with the `or_else()` method to create if-then-else
733/// logic.
734///
735/// # Features
736///
737/// - **Single Ownership**: Not cloneable, consumes `self` on use
738/// - **Conditional Execution**: Only maps when predicate returns `true`
739/// - **Chainable**: Can add `or_else` branch to create if-then-else
740/// logic
741/// - **Implements StatefulFunction**: Can be used anywhere a `StatefulFunction` is expected
742///
743/// # Examples
744///
745/// ```rust
746/// use qubit_function::{StatefulFunction, BoxStatefulFunction};
747///
748/// let mut high_count = 0;
749/// let mut low_count = 0;
750///
751/// let mut function = BoxStatefulFunction::new(move |x: &i32| {
752/// high_count += 1;
753/// x * 2
754/// })
755/// .when(|x: &i32| *x >= 10)
756/// .or_else(move |x: &i32| {
757/// low_count += 1;
758/// x + 1
759/// });
760///
761/// assert_eq!(function.apply(&15), 30); // when branch executed
762/// assert_eq!(function.apply(&5), 6); // or_else branch executed
763/// ```
764///
765/// # Author
766///
767/// Haixing Hu
768pub struct BoxConditionalStatefulFunction<T, R> {
769 function: BoxStatefulFunction<T, R>,
770 predicate: BoxPredicate<T>,
771}
772
773// Use macro to generate conditional function implementations
774impl_box_conditional_function!(
775 BoxConditionalStatefulFunction<T, R>,
776 BoxStatefulFunction,
777 StatefulFunction
778);
779
780// Use macro to generate conditional function debug and display implementations
781impl_conditional_function_debug_display!(BoxConditionalStatefulFunction<T, R>);
782
783// ============================================================================
784// RcConditionalStatefulFunction - Rc-based Conditional StatefulFunction
785// ============================================================================
786
787/// RcConditionalStatefulFunction struct
788///
789/// A single-threaded conditional function that only executes when a
790/// predicate is satisfied. Uses `RcStatefulFunction` and `RcPredicate` for shared
791/// ownership within a single thread.
792///
793/// This type is typically created by calling `RcStatefulFunction::when()` and is
794/// designed to work with the `or_else()` method to create if-then-else
795/// logic.
796///
797/// # Features
798///
799/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
800/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
801/// - **Conditional Execution**: Only maps when predicate returns `true`
802/// - **No Lock Overhead**: More efficient than `ArcConditionalStatefulFunction`
803///
804/// # Examples
805///
806/// ```rust
807/// use qubit_function::{StatefulFunction, RcStatefulFunction};
808///
809/// let mut function = RcStatefulFunction::new(|x: &i32| x * 2)
810/// .when(|x: &i32| *x > 0)
811/// .or_else(|x: &i32| -x);
812///
813/// let mut function_clone = function.clone();
814///
815/// assert_eq!(function.apply(&5), 10);
816/// assert_eq!(function_clone.apply(&-5), 5);
817/// ```
818///
819/// # Author
820///
821/// Haixing Hu
822pub struct RcConditionalStatefulFunction<T, R> {
823 function: RcStatefulFunction<T, R>,
824 predicate: RcPredicate<T>,
825}
826
827// Use macro to generate conditional function implementations
828impl_shared_conditional_function!(
829 RcConditionalStatefulFunction<T, R>,
830 RcStatefulFunction,
831 StatefulFunction,
832 'static
833);
834
835// Use macro to generate conditional function clone implementations
836impl_conditional_function_clone!(RcConditionalStatefulFunction<T, R>);
837
838// Use macro to generate conditional function debug and display implementations
839impl_conditional_function_debug_display!(RcConditionalStatefulFunction<T, R>);
840
841// ============================================================================
842// ArcConditionalStatefulFunction - Arc-based Conditional StatefulFunction
843// ============================================================================
844
845/// ArcConditionalStatefulFunction struct
846///
847/// A thread-safe conditional function that only executes when a predicate
848/// is satisfied. Uses `ArcStatefulFunction` and `ArcPredicate` for shared
849/// ownership across threads.
850///
851/// This type is typically created by calling `ArcStatefulFunction::when()` and is
852/// designed to work with the `or_else()` method to create if-then-else
853/// logic.
854///
855/// # Features
856///
857/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
858/// - **Thread-Safe**: Implements `Send`, safe for concurrent use
859/// - **Conditional Execution**: Only maps when predicate returns `true`
860/// - **Chainable**: Can add `or_else` branch to create if-then-else
861/// logic
862///
863/// # Examples
864///
865/// ```rust
866/// use qubit_function::{StatefulFunction, ArcStatefulFunction};
867///
868/// let mut function = ArcStatefulFunction::new(|x: &i32| x * 2)
869/// .when(|x: &i32| *x > 0)
870/// .or_else(|x: &i32| -x);
871///
872/// let mut function_clone = function.clone();
873///
874/// assert_eq!(function.apply(&5), 10);
875/// assert_eq!(function_clone.apply(&-5), 5);
876/// ```
877///
878/// # Author
879///
880/// Haixing Hu
881pub struct ArcConditionalStatefulFunction<T, R> {
882 function: ArcStatefulFunction<T, R>,
883 predicate: ArcPredicate<T>,
884}
885
886// Use macro to generate conditional function implementations
887impl_shared_conditional_function!(
888 ArcConditionalStatefulFunction<T, R>,
889 ArcStatefulFunction,
890 StatefulFunction,
891 Send + Sync + 'static
892);
893
894// Use macro to generate conditional function clone implementations
895impl_conditional_function_clone!(ArcConditionalStatefulFunction<T, R>);
896
897// Use macro to generate conditional function debug and display implementations
898impl_conditional_function_debug_display!(ArcConditionalStatefulFunction<T, R>);