Skip to main content

qubit_function/transformers/
stateful_transformer.rs

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