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
102 /// creating a new closure that calls `self.apply()`. This is a lightweight
103 /// adapter, but it is not strictly zero-cost.
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 transformer to a mutable closure (`FnMut`) with an explicit
255 /// method name.
256 ///
257 /// This is a naming alias of [`StatefulTransformer::into_fn`] to make the
258 /// mutability of the returned closure explicit.
259 fn into_mut_fn(self) -> impl FnMut(T) -> R
260 where
261 Self: Sized + 'static,
262 {
263 self.into_fn()
264 }
265
266 /// Converts to `BoxTransformerOnce`.
267 ///
268 /// This method has a default implementation that wraps the
269 /// transformer in a `BoxTransformerOnce`. Custom implementations
270 /// can override this method for optimization purposes.
271 ///
272 /// # Returns
273 ///
274 /// A new `BoxTransformerOnce<T, R>` instance
275 ///
276 /// # Examples
277 ///
278 /// ```rust
279 /// use qubit_function::{StatefulTransformer, TransformerOnce};
280 ///
281 /// let closure = |x: i32| x * 2;
282 /// let once = closure.into_once();
283 /// assert_eq!(once.apply(5), 10);
284 /// ```
285 fn into_once(self) -> BoxTransformerOnce<T, R>
286 where
287 Self: Sized + 'static,
288 {
289 let mut transformer = self;
290 BoxTransformerOnce::new(move |t| transformer.apply(t))
291 }
292
293 /// Non-consuming conversion to `BoxStatefulTransformer`.
294 ///
295 /// Default implementation requires `Self: Clone` and wraps a cloned
296 /// instance in a `RefCell` so the returned transformer can mutate state
297 /// across calls.
298 fn to_box(&self) -> BoxStatefulTransformer<T, R>
299 where
300 Self: Sized + Clone + 'static,
301 {
302 self.clone().into_box()
303 }
304
305 /// Non-consuming conversion to `RcStatefulTransformer`.
306 ///
307 /// Default implementation clones `self` into an `Rc<RefCell<_>>` so the
308 /// resulting transformer can be shared within a single thread.
309 fn to_rc(&self) -> RcStatefulTransformer<T, R>
310 where
311 Self: Sized + Clone + 'static,
312 {
313 self.clone().into_rc()
314 }
315
316 /// Non-consuming conversion to `ArcStatefulTransformer` (thread-safe).
317 ///
318 /// Default implementation requires `Self: Clone + Send + Sync` and wraps
319 /// the cloned instance in `Arc<Mutex<_>>` so it can be used across
320 /// threads.
321 fn to_arc(&self) -> ArcStatefulTransformer<T, R>
322 where
323 Self: Sized + Clone + Send + 'static,
324 {
325 self.clone().into_arc()
326 }
327
328 /// Non-consuming conversion to a closure (`FnMut(T) -> R`).
329 ///
330 /// Default implementation clones `self` into a `RefCell` and returns a
331 /// closure that calls `apply` on the interior mutable value.
332 fn to_fn(&self) -> impl FnMut(T) -> R
333 where
334 Self: Sized + Clone + 'static,
335 {
336 self.clone().into_fn()
337 }
338
339 /// Non-consuming conversion to a mutable closure (`FnMut`) with an explicit
340 /// method name.
341 ///
342 /// This is a naming alias of [`StatefulTransformer::to_fn`] and preserves
343 /// the same clone-based behavior.
344 fn to_mut_fn(&self) -> impl FnMut(T) -> R
345 where
346 Self: Sized + Clone + 'static,
347 {
348 self.to_fn()
349 }
350
351 /// Creates a `BoxTransformerOnce` from a cloned transformer
352 ///
353 /// Uses `Clone` to obtain an owned copy and converts it into a
354 /// `BoxTransformerOnce`. Requires `Self: Clone`. Custom implementations
355 /// can override this for better performance.
356 fn to_once(&self) -> BoxTransformerOnce<T, R>
357 where
358 Self: Sized + Clone + 'static,
359 {
360 self.clone().into_once()
361 }
362}
363
364// ============================================================================
365// BoxStatefulTransformer - Box<dyn FnMut(T) -> R>
366// ============================================================================
367
368/// BoxStatefulTransformer - transformer wrapper based on `Box<dyn FnMut>`
369///
370/// A transformer wrapper that provides single ownership with reusable stateful
371/// transformation. The transformer consumes the input and can be called
372/// multiple times while maintaining internal state.
373///
374/// # Features
375///
376/// - **Based on**: `Box<dyn FnMut(T) -> R>`
377/// - **Ownership**: Single ownership, cannot be cloned
378/// - **Reusability**: Can be called multiple times (each call consumes
379/// its input)
380/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
381/// - **Statefulness**: Can modify internal state between calls
382///
383/// # Author
384///
385/// Haixing Hu
386pub struct BoxStatefulTransformer<T, R> {
387 function: Box<dyn FnMut(T) -> R>,
388 name: Option<String>,
389}
390
391impl<T, R> BoxStatefulTransformer<T, R> {
392 impl_transformer_common_methods!(
393 BoxStatefulTransformer<T, R>,
394 (FnMut(T) -> R + 'static),
395 |f| Box::new(f)
396 );
397
398 impl_box_transformer_methods!(
399 BoxStatefulTransformer<T, R>,
400 BoxConditionalStatefulTransformer,
401 StatefulTransformer
402 );
403}
404
405// Implement constant method for BoxStatefulTransformer
406impl_transformer_constant_method!(stateful BoxStatefulTransformer<T, R>);
407
408// Implement Debug and Display for BoxStatefulTransformer
409impl_transformer_debug_display!(BoxStatefulTransformer<T, R>);
410
411// Implement StatefulTransformer trait for BoxStatefulTransformer
412impl<T, R> StatefulTransformer<T, R> for BoxStatefulTransformer<T, R> {
413 fn apply(&mut self, input: T) -> R {
414 (self.function)(input)
415 }
416
417 // Generates: into_box(), into_rc(), into_fn(), into_once()
418 impl_box_conversions!(
419 BoxStatefulTransformer<T, R>,
420 RcStatefulTransformer,
421 FnMut(T) -> R,
422 BoxTransformerOnce
423 );
424
425 // do NOT override StatefulTransformer::to_xxx() because BoxStatefulTransformer is not Clone
426 // and calling BoxStatefulTransformer::to_xxx() will cause a compile error
427}
428
429// ============================================================================
430// RcStatefulTransformer - Rc<RefCell<dyn FnMut(T) -> R>>
431// ============================================================================
432
433/// RcStatefulTransformer - single-threaded transformer wrapper
434///
435/// A single-threaded, clonable transformer wrapper optimized for scenarios
436/// that require sharing without thread-safety overhead.
437///
438/// # Features
439///
440/// - **Based on**: `Rc<RefCell<dyn FnMut(T) -> R>>`
441/// - **Ownership**: Shared ownership via reference counting (non-atomic)
442/// - **Reusability**: Can be called multiple times (each call consumes
443/// its input)
444/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
445/// - **Clonable**: Cheap cloning via `Rc::clone`
446/// - **Statefulness**: Can modify internal state between calls
447///
448/// # Author
449///
450/// Haixing Hu
451pub struct RcStatefulTransformer<T, R> {
452 function: Rc<RefCell<dyn FnMut(T) -> R>>,
453 name: Option<String>,
454}
455
456// Implement RcStatefulTransformer
457impl<T, R> RcStatefulTransformer<T, R> {
458 impl_transformer_common_methods!(
459 RcStatefulTransformer<T, R>,
460 (FnMut(T) -> R + 'static),
461 |f| Rc::new(RefCell::new(f))
462 );
463
464 impl_shared_transformer_methods!(
465 RcStatefulTransformer<T, R>,
466 RcConditionalStatefulTransformer,
467 into_rc,
468 StatefulTransformer,
469 'static
470 );
471}
472
473// Implement constant method for RcStatefulTransformer
474impl_transformer_constant_method!(stateful RcStatefulTransformer<T, R>);
475
476// Implement Debug and Display for RcStatefulTransformer
477impl_transformer_debug_display!(RcStatefulTransformer<T, R>);
478
479// Implement Clone for RcStatefulTransformer
480impl_transformer_clone!(RcStatefulTransformer<T, R>);
481
482// Implement StatefulTransformer trait for RcStatefulTransformer
483impl<T, R> StatefulTransformer<T, R> for RcStatefulTransformer<T, R> {
484 fn apply(&mut self, input: T) -> R {
485 let mut self_fn = self.function.borrow_mut();
486 self_fn(input)
487 }
488
489 // Generate all conversion methods using the unified macro
490 impl_rc_conversions!(
491 RcStatefulTransformer<T, R>,
492 BoxStatefulTransformer,
493 BoxTransformerOnce,
494 FnMut(input: T) -> R
495 );
496}
497
498// ============================================================================
499// ArcStatefulTransformer - Arc<Mutex<dyn FnMut(T) -> R + Send>>
500// ============================================================================
501
502/// ArcStatefulTransformer - thread-safe transformer wrapper
503///
504/// A thread-safe, clonable transformer wrapper suitable for multi-threaded
505/// scenarios. Can be called multiple times and shared across threads
506/// while maintaining internal state.
507///
508/// # Features
509///
510/// - **Based on**: `Arc<Mutex<dyn FnMut(T) -> R + Send>>`
511/// - **Ownership**: Shared ownership via reference counting
512/// - **Reusability**: Can be called multiple times (each call consumes
513/// its input)
514/// - **Thread Safety**: Thread-safe (`Send` required)
515/// - **Clonable**: Cheap cloning via `Arc::clone`
516/// - **Statefulness**: Can modify internal state between calls
517///
518/// # Author
519///
520/// Haixing Hu
521pub struct ArcStatefulTransformer<T, R> {
522 function: Arc<Mutex<dyn FnMut(T) -> R + Send>>,
523 name: Option<String>,
524}
525
526impl<T, R> ArcStatefulTransformer<T, R> {
527 impl_transformer_common_methods!(
528 ArcStatefulTransformer<T, R>,
529 (FnMut(T) -> R + Send + 'static),
530 |f| Arc::new(Mutex::new(f))
531 );
532
533 impl_shared_transformer_methods!(
534 ArcStatefulTransformer<T, R>,
535 ArcConditionalStatefulTransformer,
536 into_arc,
537 StatefulTransformer,
538 Send + Sync + 'static
539 );
540}
541
542// Implement constant method for ArcStatefulTransformer
543impl_transformer_constant_method!(stateful thread_safe ArcStatefulTransformer<T, R>);
544
545// Implement Debug and Display for ArcStatefulTransformer
546impl_transformer_debug_display!(ArcStatefulTransformer<T, R>);
547
548// Implement Clone for ArcStatefulTransformer
549impl_transformer_clone!(ArcStatefulTransformer<T, R>);
550
551impl<T, R> StatefulTransformer<T, R> for ArcStatefulTransformer<T, R> {
552 fn apply(&mut self, input: T) -> R {
553 let mut func = self.function.lock();
554 func(input)
555 }
556
557 // Use macro to implement conversion methods
558 impl_arc_conversions!(
559 ArcStatefulTransformer<T, R>,
560 BoxStatefulTransformer,
561 RcStatefulTransformer,
562 BoxTransformerOnce,
563 FnMut(t: T) -> R
564 );
565}
566
567// ============================================================================
568// Blanket implementation for standard FnMut trait
569// ============================================================================
570
571// Implement StatefulTransformer<T, R> for any type that implements FnMut(T) -> R
572impl_closure_trait!(
573 StatefulTransformer<T, R>,
574 apply,
575 BoxTransformerOnce,
576 FnMut(input: T) -> R
577);
578
579// ============================================================================
580// FnStatefulTransformerOps - Extension trait for closure transformers
581// ============================================================================
582
583/// Extension trait for closures implementing `FnMut(T) -> R`
584///
585/// Provides composition methods (`and_then`, `compose`, `when`) for
586/// closures without requiring explicit wrapping in `BoxStatefulTransformer`,
587/// `RcStatefulTransformer`, or `ArcStatefulTransformer`.
588///
589/// This trait is automatically implemented for all closures that
590/// implement `FnMut(T) -> R`.
591///
592/// # Design Rationale
593///
594/// While closures automatically implement `StatefulTransformer<T, R>` through blanket
595/// implementation, they don't have access to instance methods like
596/// `and_then`, `compose`, and `when`. This extension trait provides
597/// those methods, returning `BoxStatefulTransformer` for maximum flexibility.
598///
599/// # Examples
600///
601/// ## Chain composition with and_then
602///
603/// ```rust
604/// use qubit_function::{StatefulTransformer, FnStatefulTransformerOps, FnTransformerOps, Transformer};
605///
606/// let mut counter1 = 0;
607/// let transformer1 = move |x: i32| {
608/// counter1 += 1;
609/// x + counter1
610/// };
611///
612/// let mut counter2 = 0;
613/// let transformer2 = move |x: i32| {
614/// counter2 += 1;
615/// x * counter2
616/// };
617///
618/// let mut composed = FnStatefulTransformerOps::and_then(transformer1, transformer2);
619/// assert_eq!(composed.apply(10), 11); // (10 + 1) * 1
620/// ```
621///
622/// ## Reverse composition with compose
623///
624/// ```rust
625/// use qubit_function::{StatefulTransformer, FnStatefulTransformerOps, FnTransformerOps, Transformer};
626///
627/// let transformer = |x: i32| x * 2;
628///
629/// let mut composed = transformer.compose(|x: i32| x + 1);
630/// assert_eq!(composed.apply(10), 22); // (10 + 1) * 2
631/// ```
632///
633/// ## Conditional mapping with when
634///
635/// ```rust
636/// use qubit_function::{StatefulTransformer, FnStatefulTransformerOps};
637///
638/// let mut transformer = (|x: i32| x * 2)
639/// .when(|x: &i32| *x > 0)
640/// .or_else(|x: i32| -x);
641///
642/// assert_eq!(transformer.apply(5), 10);
643/// assert_eq!(transformer.apply(-5), 5);
644/// ```
645///
646/// # Author
647///
648/// Haixing Hu
649pub trait FnStatefulTransformerOps<T, R>: FnMut(T) -> R + Sized {
650 /// Chain composition - applies self first, then after
651 ///
652 /// Creates a new transformer that applies this transformer first, then applies
653 /// the after transformer to the result. Consumes self and returns a
654 /// `BoxStatefulTransformer`.
655 ///
656 /// # Type Parameters
657 ///
658 /// * `S` - The output type of the after transformer
659 /// * `F` - The type of the after transformer (must implement StatefulTransformer<R, S>)
660 ///
661 /// # Parameters
662 ///
663 /// * `after` - The transformer to apply after self. Can be:
664 /// - A closure: `|x: R| -> S`
665 /// - A `BoxStatefulTransformer<R, S>`
666 /// - An `RcStatefulTransformer<R, S>`
667 /// - An `ArcStatefulTransformer<R, S>`
668 /// - Any type implementing `StatefulTransformer<R, S>`
669 ///
670 /// # Returns
671 ///
672 /// A new `BoxStatefulTransformer<T, S>` representing the composition
673 ///
674 /// # Examples
675 ///
676 /// ```rust
677 /// use qubit_function::{StatefulTransformer, FnStatefulTransformerOps, BoxStatefulTransformer};
678 ///
679 /// let mut counter1 = 0;
680 /// let transformer1 = move |x: i32| {
681 /// counter1 += 1;
682 /// x + counter1
683 /// };
684 ///
685 /// let mut counter2 = 0;
686 /// let transformer2 = BoxStatefulTransformer::new(move |x: i32| {
687 /// counter2 += 1;
688 /// x * counter2
689 /// });
690 ///
691 /// let mut composed = transformer1.and_then(transformer2);
692 /// assert_eq!(composed.apply(10), 11);
693 /// ```
694 fn and_then<S, F>(self, after: F) -> BoxStatefulTransformer<T, S>
695 where
696 Self: 'static,
697 S: 'static,
698 F: StatefulTransformer<R, S> + 'static,
699 T: 'static,
700 R: 'static,
701 {
702 BoxStatefulTransformer::new(self).and_then(after)
703 }
704
705 /// Creates a conditional transformer
706 ///
707 /// Returns a transformer that only executes when a predicate is satisfied.
708 /// You must call `or_else()` to provide an alternative transformer for
709 /// when the condition is not satisfied.
710 ///
711 /// # Parameters
712 ///
713 /// * `predicate` - The condition to check. Can be:
714 /// - A closure: `|x: &T| -> bool`
715 /// - A function pointer: `fn(&T) -> bool`
716 /// - A `BoxPredicate<T>`
717 /// - An `RcPredicate<T>`
718 /// - An `ArcPredicate<T>`
719 /// - Any type implementing `Predicate<T>`
720 ///
721 /// # Returns
722 ///
723 /// Returns `BoxConditionalStatefulTransformer<T, R>`
724 ///
725 /// # Examples
726 ///
727 /// ```rust
728 /// use qubit_function::{StatefulTransformer, FnStatefulTransformerOps};
729 ///
730 /// let mut transformer = (|x: i32| x * 2)
731 /// .when(|x: &i32| *x > 0)
732 /// .or_else(|x: i32| -x);
733 ///
734 /// assert_eq!(transformer.apply(5), 10);
735 /// assert_eq!(transformer.apply(-5), 5);
736 /// ```
737 fn when<P>(self, predicate: P) -> BoxConditionalStatefulTransformer<T, R>
738 where
739 Self: 'static,
740 P: Predicate<T> + 'static,
741 T: 'static,
742 R: 'static,
743 {
744 BoxStatefulTransformer::new(self).when(predicate)
745 }
746}
747
748/// Blanket implementation of FnStatefulTransformerOps for all closures
749///
750/// Automatically implements `FnStatefulTransformerOps<T, R>` for any type that
751/// implements `FnMut(T) -> R`.
752///
753/// # Author
754///
755/// Haixing Hu
756impl<T, R, F> FnStatefulTransformerOps<T, R> for F where F: FnMut(T) -> R {}
757
758// ============================================================================
759// BoxConditionalStatefulTransformer - Box-based Conditional StatefulTransformer
760// ============================================================================
761
762/// BoxConditionalStatefulTransformer struct
763///
764/// A conditional transformer that only executes when a predicate is satisfied.
765/// Uses `BoxStatefulTransformer` and `BoxPredicate` for single ownership semantics.
766///
767/// This type is typically created by calling `BoxStatefulTransformer::when()` and is
768/// designed to work with the `or_else()` method to create if-then-else
769/// logic.
770///
771/// # Features
772///
773/// - **Single Ownership**: Not cloneable, consumes `self` on use
774/// - **Conditional Execution**: Only maps when predicate returns `true`
775/// - **Chainable**: Can add `or_else` branch to create if-then-else
776/// logic
777/// - **Implements StatefulTransformer**: Can be used anywhere a `StatefulTransformer` is expected
778///
779/// # Examples
780///
781/// ```rust
782/// use qubit_function::{StatefulTransformer, BoxStatefulTransformer};
783///
784/// let mut high_count = 0;
785/// let mut low_count = 0;
786///
787/// let mut transformer = BoxStatefulTransformer::new(move |x: i32| {
788/// high_count += 1;
789/// x * 2
790/// })
791/// .when(|x: &i32| *x >= 10)
792/// .or_else(move |x| {
793/// low_count += 1;
794/// x + 1
795/// });
796///
797/// assert_eq!(transformer.apply(15), 30); // when branch executed
798/// assert_eq!(transformer.apply(5), 6); // or_else branch executed
799/// ```
800///
801/// # Author
802///
803/// Haixing Hu
804pub struct BoxConditionalStatefulTransformer<T, R> {
805 transformer: BoxStatefulTransformer<T, R>,
806 predicate: BoxPredicate<T>,
807}
808
809// Implement BoxConditionalTransformer
810impl_box_conditional_transformer!(
811 BoxConditionalStatefulTransformer<T, R>,
812 BoxStatefulTransformer,
813 StatefulTransformer
814);
815
816// Use macro to generate Debug and Display implementations
817impl_conditional_transformer_debug_display!(BoxConditionalStatefulTransformer<T, R>);
818
819// ============================================================================
820// RcConditionalStatefulTransformer - Rc-based Conditional StatefulTransformer
821// ============================================================================
822
823/// RcConditionalStatefulTransformer struct
824///
825/// A single-threaded conditional transformer that only executes when a
826/// predicate is satisfied. Uses `RcStatefulTransformer` and `RcPredicate` for shared
827/// ownership within a single thread.
828///
829/// This type is typically created by calling `RcStatefulTransformer::when()` and is
830/// designed to work with the `or_else()` method to create if-then-else
831/// logic.
832///
833/// # Features
834///
835/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
836/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
837/// - **Conditional Execution**: Only maps when predicate returns `true`
838/// - **No Lock Overhead**: More efficient than `ArcConditionalStatefulTransformer`
839///
840/// # Examples
841///
842/// ```rust
843/// use qubit_function::{StatefulTransformer, RcStatefulTransformer};
844///
845/// let mut transformer = RcStatefulTransformer::new(|x: i32| x * 2)
846/// .when(|x: &i32| *x > 0)
847/// .or_else(|x: i32| -x);
848///
849/// let mut transformer_clone = transformer.clone();
850///
851/// assert_eq!(transformer.apply(5), 10);
852/// assert_eq!(transformer_clone.apply(-5), 5);
853/// ```
854///
855/// # Author
856///
857/// Haixing Hu
858pub struct RcConditionalStatefulTransformer<T, R> {
859 transformer: RcStatefulTransformer<T, R>,
860 predicate: RcPredicate<T>,
861}
862
863// Implement RcConditionalStatefulTransformer
864impl_shared_conditional_transformer!(
865 RcConditionalStatefulTransformer<T, R>,
866 RcStatefulTransformer,
867 StatefulTransformer,
868 into_rc,
869 'static
870);
871
872// Use macro to generate Debug and Display implementations
873impl_conditional_transformer_debug_display!(RcConditionalStatefulTransformer<T, R>);
874
875// Implement Clone for RcConditionalStatefulTransformer
876impl_conditional_transformer_clone!(RcConditionalStatefulTransformer<T, R>);
877
878// ============================================================================
879// ArcConditionalStatefulTransformer - Arc-based Conditional StatefulTransformer
880// ============================================================================
881
882/// ArcConditionalStatefulTransformer struct
883///
884/// A thread-safe conditional transformer that only executes when a predicate
885/// is satisfied. Uses `ArcStatefulTransformer` and `ArcPredicate` for shared
886/// ownership across threads.
887///
888/// This type is typically created by calling `ArcStatefulTransformer::when()` and is
889/// designed to work with the `or_else()` method to create if-then-else
890/// logic.
891///
892/// # Features
893///
894/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
895/// - **Thread-Safe**: Implements `Send`, safe for concurrent use
896/// - **Conditional Execution**: Only maps when predicate returns `true`
897/// - **Chainable**: Can add `or_else` branch to create if-then-else
898/// logic
899///
900/// # Examples
901///
902/// ```rust
903/// use qubit_function::{StatefulTransformer, ArcStatefulTransformer};
904///
905/// let mut transformer = ArcStatefulTransformer::new(|x: i32| x * 2)
906/// .when(|x: &i32| *x > 0)
907/// .or_else(|x: i32| -x);
908///
909/// let mut transformer_clone = transformer.clone();
910///
911/// assert_eq!(transformer.apply(5), 10);
912/// assert_eq!(transformer_clone.apply(-5), 5);
913/// ```
914///
915/// # Author
916///
917/// Haixing Hu
918pub struct ArcConditionalStatefulTransformer<T, R> {
919 transformer: ArcStatefulTransformer<T, R>,
920 predicate: ArcPredicate<T>,
921}
922
923// Implement ArcConditionalStatefulTransformer
924impl_shared_conditional_transformer!(
925 ArcConditionalStatefulTransformer<T, R>,
926 ArcStatefulTransformer,
927 StatefulTransformer,
928 into_arc,
929 Send + Sync + 'static
930);
931
932// Use macro to generate Debug and Display implementations
933impl_conditional_transformer_debug_display!(ArcConditionalStatefulTransformer<T, R>);
934
935// Implement Clone for ArcConditionalStatefulTransformer
936impl_conditional_transformer_clone!(ArcConditionalStatefulTransformer<T, R>);