qubit_function/transformers/transformer.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # Transformer Types
10//!
11//! Provides Rust implementations of transformer traits for type conversion
12//! and value transformation. Transformers consume input values (taking
13//! ownership) and produce output values. This is analogous to
14//! `Fn(T) -> R` in Rust's standard library.
15//!
16//! This module provides the `Transformer<T, R>` trait and three
17//! implementations:
18//!
19//! - [`BoxTransformer`]: Single ownership, not cloneable
20//! - [`ArcTransformer`]: Thread-safe shared ownership, cloneable
21//! - [`RcTransformer`]: Single-threaded shared ownership, cloneable
22//!
23//! # Author
24//!
25//! Haixing Hu
26use std::rc::Rc;
27use std::sync::Arc;
28
29use crate::macros::{
30 impl_arc_conversions,
31 impl_box_conversions,
32 impl_closure_trait,
33 impl_rc_conversions,
34};
35use crate::predicates::predicate::{
36 ArcPredicate,
37 BoxPredicate,
38 Predicate,
39 RcPredicate,
40};
41use crate::transformers::{
42 macros::{
43 impl_box_conditional_transformer,
44 impl_box_transformer_methods,
45 impl_conditional_transformer_clone,
46 impl_conditional_transformer_debug_display,
47 impl_shared_conditional_transformer,
48 impl_shared_transformer_methods,
49 impl_transformer_clone,
50 impl_transformer_common_methods,
51 impl_transformer_constant_method,
52 impl_transformer_debug_display,
53 },
54 transformer_once::BoxTransformerOnce,
55};
56
57// ============================================================================
58// Core Trait
59// ============================================================================
60
61/// Transformer trait - transforms values from type T to type R
62///
63/// Defines the behavior of a transformation: converting a value of type `T`
64/// to a value of type `R` by consuming the input. This is analogous to
65/// `Fn(T) -> R` in Rust's standard library.
66///
67/// # Type Parameters
68///
69/// * `T` - The type of the input value (consumed)
70/// * `R` - The type of the output value
71///
72/// # Author
73///
74/// Haixing Hu
75pub trait Transformer<T, R> {
76 /// Applies the transformation to the input value to produce an output value
77 ///
78 /// # Parameters
79 ///
80 /// * `input` - The input value to transform (consumed)
81 ///
82 /// # Returns
83 ///
84 /// The transformed output value
85 fn apply(&self, input: T) -> R;
86
87 /// Converts to BoxTransformer
88 ///
89 /// **⚠️ Consumes `self`**: The original transformer becomes
90 /// unavailable after calling this method.
91 ///
92 /// # Default Implementation
93 ///
94 /// The default implementation wraps `self` in a `Box` and creates a
95 /// `BoxTransformer`. Types can override this method to provide more
96 /// efficient conversions.
97 ///
98 /// # Returns
99 ///
100 /// Returns `BoxTransformer<T, R>`
101 fn into_box(self) -> BoxTransformer<T, R>
102 where
103 Self: Sized + 'static,
104 {
105 BoxTransformer::new(move |x| self.apply(x))
106 }
107
108 /// Converts to RcTransformer
109 ///
110 /// **⚠️ Consumes `self`**: The original transformer becomes
111 /// unavailable after calling this method.
112 ///
113 /// # Default Implementation
114 ///
115 /// The default implementation wraps `self` in an `Rc` and creates an
116 /// `RcTransformer`. Types can override this method to provide more
117 /// efficient conversions.
118 ///
119 /// # Returns
120 ///
121 /// Returns `RcTransformer<T, R>`
122 fn into_rc(self) -> RcTransformer<T, R>
123 where
124 Self: Sized + 'static,
125 {
126 RcTransformer::new(move |x| self.apply(x))
127 }
128
129 /// Converts to ArcTransformer
130 ///
131 /// **⚠️ Consumes `self`**: The original transformer becomes
132 /// unavailable after calling this method.
133 ///
134 /// # Default Implementation
135 ///
136 /// The default implementation wraps `self` in an `Arc` and creates
137 /// an `ArcTransformer`. Types can override this method to provide
138 /// more efficient conversions.
139 ///
140 /// # Returns
141 ///
142 /// Returns `ArcTransformer<T, R>`
143 fn into_arc(self) -> ArcTransformer<T, R>
144 where
145 Self: Sized + Send + Sync + 'static,
146 {
147 ArcTransformer::new(move |x| self.apply(x))
148 }
149
150 /// Converts transformer to a closure
151 ///
152 /// **⚠️ Consumes `self`**: The original transformer becomes
153 /// unavailable after calling this method.
154 ///
155 /// # Default Implementation
156 ///
157 /// The default implementation creates a closure that captures `self`
158 /// and calls its `transform` method. Types can override this method
159 /// to provide more efficient conversions.
160 ///
161 /// # Returns
162 ///
163 /// Returns a closure that implements `Fn(T) -> R`
164 fn into_fn(self) -> impl Fn(T) -> R
165 where
166 Self: Sized + 'static,
167 {
168 move |t: T| self.apply(t)
169 }
170
171 /// Converts to `BoxTransformerOnce`.
172 ///
173 /// This method has a default implementation that wraps the
174 /// transformer in a `BoxTransformerOnce`. Custom implementations
175 /// can override this method for optimization purposes.
176 ///
177 /// # Returns
178 ///
179 /// A new `BoxTransformerOnce<T, R>` instance
180 ///
181 /// # Examples
182 ///
183 /// ```rust
184 /// use qubit_function::Transformer;
185 ///
186 /// let closure = |x: i32| x * 2;
187 /// let once = closure.into_once();
188 /// assert_eq!(once.apply(5), 10);
189 /// ```
190 fn into_once(self) -> BoxTransformerOnce<T, R>
191 where
192 Self: Sized + 'static,
193 {
194 BoxTransformerOnce::new(move |t| self.apply(t))
195 }
196
197 /// Converts to BoxTransformer without consuming self
198 ///
199 /// **📌 Borrows `&self`**: The original transformer remains usable
200 /// after calling this method.
201 ///
202 /// # Default Implementation
203 ///
204 /// The default implementation creates a new `BoxTransformer` that
205 /// captures a reference-counted clone. Types implementing `Clone`
206 /// can override this method to provide more efficient conversions.
207 ///
208 /// # Returns
209 ///
210 /// Returns `BoxTransformer<T, R>`
211 ///
212 /// # Examples
213 ///
214 /// ```rust
215 /// use qubit_function::{ArcTransformer, Transformer};
216 ///
217 /// let double = ArcTransformer::new(|x: i32| x * 2);
218 /// let boxed = double.to_box();
219 ///
220 /// // Original transformer still usable
221 /// assert_eq!(double.apply(21), 42);
222 /// assert_eq!(boxed.apply(21), 42);
223 /// ```
224 fn to_box(&self) -> BoxTransformer<T, R>
225 where
226 Self: Clone + 'static,
227 {
228 self.clone().into_box()
229 }
230
231 /// Converts to RcTransformer without consuming self
232 ///
233 /// **📌 Borrows `&self`**: The original transformer remains usable
234 /// after calling this method.
235 ///
236 /// # Default Implementation
237 ///
238 /// The default implementation creates a new `RcTransformer` that
239 /// captures a reference-counted clone. Types implementing `Clone`
240 /// can override this method to provide more efficient conversions.
241 ///
242 /// # Returns
243 ///
244 /// Returns `RcTransformer<T, R>`
245 ///
246 /// # Examples
247 ///
248 /// ```rust
249 /// use qubit_function::{ArcTransformer, Transformer};
250 ///
251 /// let double = ArcTransformer::new(|x: i32| x * 2);
252 /// let rc = double.to_rc();
253 ///
254 /// // Original transformer still usable
255 /// assert_eq!(double.apply(21), 42);
256 /// assert_eq!(rc.apply(21), 42);
257 /// ```
258 fn to_rc(&self) -> RcTransformer<T, R>
259 where
260 Self: Clone + 'static,
261 {
262 self.clone().into_rc()
263 }
264
265 /// Converts to ArcTransformer without consuming self
266 ///
267 /// **📌 Borrows `&self`**: The original transformer remains usable
268 /// after calling this method.
269 ///
270 /// # Default Implementation
271 ///
272 /// The default implementation creates a new `ArcTransformer` that
273 /// captures a reference-counted clone. Types implementing `Clone`
274 /// can override this method to provide more efficient conversions.
275 ///
276 /// # Returns
277 ///
278 /// Returns `ArcTransformer<T, R>`
279 ///
280 /// # Examples
281 ///
282 /// ```rust
283 /// use qubit_function::{ArcTransformer, Transformer};
284 ///
285 /// let double = ArcTransformer::new(|x: i32| x * 2);
286 /// let arc = double.to_arc();
287 ///
288 /// // Original transformer still usable
289 /// assert_eq!(double.apply(21), 42);
290 /// assert_eq!(arc.apply(21), 42);
291 /// ```
292 fn to_arc(&self) -> ArcTransformer<T, R>
293 where
294 Self: Clone + Send + Sync + 'static,
295 {
296 self.clone().into_arc()
297 }
298
299 /// Converts transformer to a closure without consuming self
300 ///
301 /// **📌 Borrows `&self`**: The original transformer remains usable
302 /// after calling this method.
303 ///
304 /// # Default Implementation
305 ///
306 /// The default implementation creates a closure that captures a
307 /// clone of `self` and calls its `transform` method. Types can
308 /// override this method to provide more efficient conversions.
309 ///
310 /// # Returns
311 ///
312 /// Returns a closure that implements `Fn(T) -> R`
313 ///
314 /// # Examples
315 ///
316 /// ```rust
317 /// use qubit_function::{ArcTransformer, Transformer};
318 ///
319 /// let double = ArcTransformer::new(|x: i32| x * 2);
320 /// let closure = double.to_fn();
321 ///
322 /// // Original transformer still usable
323 /// assert_eq!(double.apply(21), 42);
324 /// assert_eq!(closure(21), 42);
325 /// ```
326 fn to_fn(&self) -> impl Fn(T) -> R
327 where
328 Self: Clone + 'static,
329 {
330 self.clone().into_fn()
331 }
332
333 /// Converts to `BoxTransformerOnce` without consuming self
334 ///
335 /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
336 /// Clones the current transformer and converts the clone to a one-time transformer.
337 ///
338 /// # Returns
339 ///
340 /// Returns a `BoxTransformerOnce<T, R>`
341 fn to_once(&self) -> BoxTransformerOnce<T, R>
342 where
343 Self: Clone + 'static,
344 {
345 self.clone().into_once()
346 }
347}
348
349// ============================================================================
350// BoxTransformer - Box<dyn Fn(T) -> R>
351// ============================================================================
352
353/// BoxTransformer - transformer wrapper based on `Box<dyn Fn>`
354///
355/// A transformer wrapper that provides single ownership with reusable
356/// transformation. The transformer consumes the input and can be called
357/// multiple times.
358///
359/// # Features
360///
361/// - **Based on**: `Box<dyn Fn(T) -> R>`
362/// - **Ownership**: Single ownership, cannot be cloned
363/// - **Reusability**: Can be called multiple times (each call consumes its
364/// input)
365/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
366///
367/// # Author
368///
369/// Haixing Hu
370pub struct BoxTransformer<T, R> {
371 function: Box<dyn Fn(T) -> R>,
372 name: Option<String>,
373}
374
375// Implement BoxTransformer
376impl<T, R> BoxTransformer<T, R> {
377 impl_transformer_common_methods!(
378 BoxTransformer<T, R>,
379 (Fn(T) -> R + 'static),
380 |f| Box::new(f)
381 );
382
383 impl_box_transformer_methods!(
384 BoxTransformer<T, R>,
385 BoxConditionalTransformer,
386 Transformer
387 );
388}
389
390// Implement constant method for BoxTransformer
391impl_transformer_constant_method!(BoxTransformer<T, R>);
392
393// Implement Debug and Display for BoxTransformer
394impl_transformer_debug_display!(BoxTransformer<T, R>);
395
396// Implement Transformer for BoxTransformer
397impl<T, R> Transformer<T, R> for BoxTransformer<T, R> {
398 fn apply(&self, input: T) -> R {
399 (self.function)(input)
400 }
401
402 // Generates: into_box(), into_rc(), into_fn(), into_once()
403 impl_box_conversions!(
404 BoxTransformer<T, R>,
405 RcTransformer,
406 Fn(T) -> R,
407 BoxTransformerOnce
408 );
409}
410
411// ============================================================================
412// RcTransformer - Rc<dyn Fn(T) -> R>
413// ============================================================================
414
415/// RcTransformer - single-threaded transformer wrapper
416///
417/// A single-threaded, clonable transformer wrapper optimized for scenarios
418/// that require sharing without thread-safety overhead.
419///
420/// # Features
421///
422/// - **Based on**: `Rc<dyn Fn(T) -> R>`
423/// - **Ownership**: Shared ownership via reference counting (non-atomic)
424/// - **Reusability**: Can be called multiple times (each call consumes its
425/// input)
426/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
427/// - **Clonable**: Cheap cloning via `Rc::clone`
428///
429/// # Author
430///
431/// Haixing Hu
432pub struct RcTransformer<T, R> {
433 function: Rc<dyn Fn(T) -> R>,
434 name: Option<String>,
435}
436
437// Implement RcTransformer
438impl<T, R> RcTransformer<T, R> {
439 impl_transformer_common_methods!(
440 RcTransformer<T, R>,
441 (Fn(T) -> R + 'static),
442 |f| Rc::new(f)
443 );
444
445 impl_shared_transformer_methods!(
446 RcTransformer<T, R>,
447 RcConditionalTransformer,
448 into_rc,
449 Transformer,
450 'static
451 );
452}
453
454impl_transformer_constant_method!(RcTransformer<T, R>);
455
456// Implement Debug and Display for RcTransformer
457impl_transformer_debug_display!(RcTransformer<T, R>);
458
459// Implement Clone for RcTransformer
460impl_transformer_clone!(RcTransformer<T, R>);
461
462// Implement Transformer for RcTransformer
463impl<T, R> Transformer<T, R> for RcTransformer<T, R> {
464 fn apply(&self, input: T) -> R {
465 (self.function)(input)
466 }
467
468 // Generate all conversion methods using the unified macro
469 impl_rc_conversions!(
470 RcTransformer<T, R>,
471 BoxTransformer,
472 BoxTransformerOnce,
473 Fn(input: T) -> R
474 );
475}
476
477// ============================================================================
478// ArcTransformer - Arc<dyn Fn(T) -> R + Send + Sync>
479// ============================================================================
480
481/// ArcTransformer - thread-safe transformer wrapper
482///
483/// A thread-safe, clonable transformer wrapper suitable for multi-threaded
484/// scenarios. Can be called multiple times and shared across threads.
485///
486/// # Features
487///
488/// - **Based on**: `Arc<dyn Fn(T) -> R + Send + Sync>`
489/// - **Ownership**: Shared ownership via reference counting
490/// - **Reusability**: Can be called multiple times (each call consumes its
491/// input)
492/// - **Thread Safety**: Thread-safe (`Send + Sync` required)
493/// - **Clonable**: Cheap cloning via `Arc::clone`
494///
495/// # Author
496///
497/// Haixing Hu
498pub struct ArcTransformer<T, R> {
499 function: Arc<dyn Fn(T) -> R + Send + Sync>,
500 name: Option<String>,
501}
502
503// Implement ArcTransformer
504impl<T, R> ArcTransformer<T, R> {
505 impl_transformer_common_methods!(
506 ArcTransformer<T, R>,
507 (Fn(T) -> R + Send + Sync + 'static),
508 |f| Arc::new(f)
509 );
510
511 impl_shared_transformer_methods!(
512 ArcTransformer<T, R>,
513 ArcConditionalTransformer,
514 into_arc,
515 Transformer,
516 Send + Sync + 'static
517 );
518}
519
520// Implement constant method for ArcTransformer
521impl_transformer_constant_method!(thread_safe ArcTransformer<T, R>);
522
523// Implement Debug and Display for ArcTransformer
524impl_transformer_debug_display!(ArcTransformer<T, R>);
525
526// Implement Clone for ArcTransformer
527impl_transformer_clone!(ArcTransformer<T, R>);
528
529// Implement Transformer for ArcTransformer
530impl<T, R> Transformer<T, R> for ArcTransformer<T, R> {
531 fn apply(&self, input: T) -> R {
532 (self.function)(input)
533 }
534
535 // Use macro to implement conversion methods
536 impl_arc_conversions!(
537 ArcTransformer<T, R>,
538 BoxTransformer,
539 RcTransformer,
540 BoxTransformerOnce,
541 Fn(t: T) -> R
542 );
543}
544
545// ============================================================================
546// Blanket implementation for standard Fn trait
547// ============================================================================
548
549// Implement Transformer<T, R> for any type that implements Fn(T) -> R
550impl_closure_trait!(
551 Transformer<T, R>,
552 apply,
553 BoxTransformerOnce,
554 Fn(input: T) -> R
555);
556
557// ============================================================================
558// FnTransformerOps - Extension trait for closure transformers
559// ============================================================================
560
561/// Extension trait for closures implementing `Fn(T) -> R`
562///
563/// Provides composition methods (`and_then`, `compose`, `when`) for closures
564/// and function pointers without requiring explicit wrapping in
565/// `BoxTransformer`, `RcTransformer`, or `ArcTransformer`.
566///
567/// This trait is automatically implemented for all closures and function
568/// pointers that implement `Fn(T) -> R`.
569///
570/// # Design Rationale
571///
572/// While closures automatically implement `Transformer<T, R>` through blanket
573/// implementation, they don't have access to instance methods like `and_then`,
574/// `compose`, and `when`. This extension trait provides those methods,
575/// returning `BoxTransformer` for maximum flexibility.
576///
577/// # Examples
578///
579/// ## Chain composition with and_then
580///
581/// ```rust
582/// use qubit_function::{Transformer, FnTransformerOps};
583///
584/// let double = |x: i32| x * 2;
585/// let to_string = |x: i32| x.to_string();
586///
587/// let composed = double.and_then(to_string);
588/// assert_eq!(composed.apply(21), "42");
589/// ```
590///
591/// ## Reverse composition with compose
592///
593/// ```rust
594/// use qubit_function::{Transformer, FnTransformerOps};
595///
596/// let double = |x: i32| x * 2;
597/// let add_one = |x: i32| x + 1;
598///
599/// let composed = double.compose(add_one);
600/// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
601/// ```
602///
603/// ## Conditional transformation with when
604///
605/// ```rust
606/// use qubit_function::{Transformer, FnTransformerOps};
607///
608/// let double = |x: i32| x * 2;
609/// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
610///
611/// assert_eq!(conditional.apply(5), 10);
612/// assert_eq!(conditional.apply(-5), 5);
613/// ```
614///
615/// # Author
616///
617/// Haixing Hu
618pub trait FnTransformerOps<T, R>: Fn(T) -> R + Sized {
619 /// Chain composition - applies self first, then after
620 ///
621 /// Creates a new transformer that applies this transformer first, then
622 /// applies the after transformer to the result. Consumes self and returns
623 /// a `BoxTransformer`.
624 ///
625 /// # Type Parameters
626 ///
627 /// * `S` - The output type of the after transformer
628 /// * `F` - The type of the after transformer (must implement Transformer<R, S>)
629 ///
630 /// # Parameters
631 ///
632 /// * `after` - The transformer to apply after self. **Note: This parameter
633 /// is passed by value and will transfer ownership.** If you need to
634 /// preserve the original transformer, clone it first (if it implements
635 /// `Clone`). Can be:
636 /// - A closure: `|x: R| -> S`
637 /// - A function pointer: `fn(R) -> S`
638 /// - A `BoxTransformer<R, S>`
639 /// - An `RcTransformer<R, S>`
640 /// - An `ArcTransformer<R, S>`
641 /// - Any type implementing `Transformer<R, S>`
642 ///
643 /// # Returns
644 ///
645 /// A new `BoxTransformer<T, S>` representing the composition
646 ///
647 /// # Examples
648 ///
649 /// ## Direct value passing (ownership transfer)
650 ///
651 /// ```rust
652 /// use qubit_function::{Transformer, FnTransformerOps, BoxTransformer};
653 ///
654 /// let double = |x: i32| x * 2;
655 /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
656 ///
657 /// // to_string is moved here
658 /// let composed = double.and_then(to_string);
659 /// assert_eq!(composed.apply(21), "42");
660 /// // to_string.apply(5); // Would not compile - moved
661 /// ```
662 ///
663 /// ## Preserving original with clone
664 ///
665 /// ```rust
666 /// use qubit_function::{Transformer, FnTransformerOps, BoxTransformer};
667 ///
668 /// let double = |x: i32| x * 2;
669 /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
670 ///
671 /// // Clone to preserve original
672 /// let composed = double.and_then(to_string.clone());
673 /// assert_eq!(composed.apply(21), "42");
674 ///
675 /// // Original still usable
676 /// assert_eq!(to_string.apply(5), "5");
677 /// ```
678 fn and_then<S, F>(self, after: F) -> BoxTransformer<T, S>
679 where
680 Self: 'static,
681 S: 'static,
682 F: Transformer<R, S> + 'static,
683 T: 'static,
684 R: 'static,
685 {
686 BoxTransformer::new(move |x: T| after.apply(self(x)))
687 }
688
689 /// Reverse composition - applies before first, then self
690 ///
691 /// Creates a new transformer that applies the before transformer first,
692 /// then applies this transformer to the result. Consumes self and returns
693 /// a `BoxTransformer`.
694 ///
695 /// # Type Parameters
696 ///
697 /// * `S` - The input type of the before transformer
698 /// * `F` - The type of the before transformer (must implement Transformer<S, T>)
699 ///
700 /// # Parameters
701 ///
702 /// * `before` - The transformer to apply before self. **Note: This parameter
703 /// is passed by value and will transfer ownership.** If you need to
704 /// preserve the original transformer, clone it first (if it implements
705 /// `Clone`). Can be:
706 /// - A closure: `|x: S| -> T`
707 /// - A function pointer: `fn(S) -> T`
708 /// - A `BoxTransformer<S, T>`
709 /// - An `RcTransformer<S, T>`
710 /// - An `ArcTransformer<S, T>`
711 /// - Any type implementing `Transformer<S, T>`
712 ///
713 /// # Returns
714 ///
715 /// A new `BoxTransformer<S, R>` representing the composition
716 ///
717 /// # Examples
718 ///
719 /// ## Direct value passing (ownership transfer)
720 ///
721 /// ```rust
722 /// use qubit_function::{Transformer, FnTransformerOps, BoxTransformer};
723 ///
724 /// let double = |x: i32| x * 2;
725 /// let add_one = BoxTransformer::new(|x: i32| x + 1);
726 ///
727 /// // add_one is moved here
728 /// let composed = double.compose(add_one);
729 /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
730 /// // add_one.apply(3); // Would not compile - moved
731 /// ```
732 ///
733 /// ## Preserving original with clone
734 ///
735 /// ```rust
736 /// use qubit_function::{Transformer, FnTransformerOps, BoxTransformer};
737 ///
738 /// let double = |x: i32| x * 2;
739 /// let add_one = BoxTransformer::new(|x: i32| x + 1);
740 ///
741 /// // Clone to preserve original
742 /// let composed = double.compose(add_one.clone());
743 /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
744 ///
745 /// // Original still usable
746 /// assert_eq!(add_one.apply(3), 4);
747 /// ```
748 fn compose<S, F>(self, before: F) -> BoxTransformer<S, R>
749 where
750 Self: 'static,
751 S: 'static,
752 F: Transformer<S, T> + 'static,
753 T: 'static,
754 R: 'static,
755 {
756 BoxTransformer::new(move |x: S| self(before.apply(x)))
757 }
758
759 /// Creates a conditional transformer
760 ///
761 /// Returns a transformer that only executes when a predicate is satisfied.
762 /// You must call `or_else()` to provide an alternative transformer for when
763 /// the condition is not satisfied.
764 ///
765 /// # Parameters
766 ///
767 /// * `predicate` - The condition to check. **Note: This parameter is passed
768 /// by value and will transfer ownership.** If you need to preserve the
769 /// original predicate, clone it first (if it implements `Clone`). Can be:
770 /// - A closure: `|x: &T| -> bool`
771 /// - A function pointer: `fn(&T) -> bool`
772 /// - A `BoxPredicate<T>`
773 /// - An `RcPredicate<T>`
774 /// - An `ArcPredicate<T>`
775 /// - Any type implementing `Predicate<T>`
776 ///
777 /// # Returns
778 ///
779 /// Returns `BoxConditionalTransformer<T, R>`
780 ///
781 /// # Examples
782 ///
783 /// ## Basic usage with or_else
784 ///
785 /// ```rust
786 /// use qubit_function::{Transformer, FnTransformerOps};
787 ///
788 /// let double = |x: i32| x * 2;
789 /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
790 ///
791 /// assert_eq!(conditional.apply(5), 10);
792 /// assert_eq!(conditional.apply(-5), 5);
793 /// ```
794 ///
795 /// ## Preserving predicate with clone
796 ///
797 /// ```rust
798 /// use qubit_function::{Transformer, FnTransformerOps, BoxPredicate};
799 ///
800 /// let double = |x: i32| x * 2;
801 /// let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
802 ///
803 /// // Clone to preserve original predicate
804 /// let conditional = double.when(is_positive.clone())
805 /// .or_else(|x: i32| -x);
806 ///
807 /// assert_eq!(conditional.apply(5), 10);
808 ///
809 /// // Original predicate still usable
810 /// assert!(is_positive.test(&3));
811 /// ```
812 fn when<P>(self, predicate: P) -> BoxConditionalTransformer<T, R>
813 where
814 Self: 'static,
815 P: Predicate<T> + 'static,
816 T: 'static,
817 R: 'static,
818 {
819 BoxTransformer::new(self).when(predicate)
820 }
821}
822
823/// Blanket implementation of FnTransformerOps for all closures
824///
825/// Automatically implements `FnTransformerOps<T, R>` for any type that
826/// implements `Fn(T) -> R`.
827///
828/// # Author
829///
830/// Haixing Hu
831impl<T, R, F> FnTransformerOps<T, R> for F where F: Fn(T) -> R {}
832
833// ============================================================================
834// UnaryOperator Trait - Marker trait for Transformer<T, T>
835// ============================================================================
836
837/// UnaryOperator trait - marker trait for unary operators
838///
839/// A unary operator transforms a value of type `T` to another value of the
840/// same type `T`. This trait extends `Transformer<T, T>` to provide semantic
841/// clarity for same-type transformations. Equivalent to Java's `UnaryOperator<T>`
842/// which extends `Function<T, T>`.
843///
844/// # Automatic Implementation
845///
846/// This trait is automatically implemented for all types that implement
847/// `Transformer<T, T>`, so you don't need to implement it manually.
848///
849/// # Type Parameters
850///
851/// * `T` - The type of both input and output values
852///
853/// # Examples
854///
855/// ## Using in generic constraints
856///
857/// ```rust
858/// use qubit_function::{UnaryOperator, Transformer};
859///
860/// fn apply_twice<T, O>(value: T, op: O) -> T
861/// where
862/// O: UnaryOperator<T>,
863/// T: Clone,
864/// {
865/// let result = op.apply(value.clone());
866/// op.apply(result)
867/// }
868///
869/// let increment = |x: i32| x + 1;
870/// assert_eq!(apply_twice(5, increment), 7); // (5 + 1) + 1
871/// ```
872///
873/// ## With concrete types
874///
875/// ```rust
876/// use qubit_function::{BoxUnaryOperator, UnaryOperator, Transformer};
877///
878/// fn create_incrementer() -> BoxUnaryOperator<i32> {
879/// BoxUnaryOperator::new(|x| x + 1)
880/// }
881///
882/// let op = create_incrementer();
883/// assert_eq!(op.apply(41), 42);
884/// ```
885///
886/// # Author
887///
888/// Haixing Hu
889pub trait UnaryOperator<T>: Transformer<T, T> {}
890
891/// Blanket implementation of UnaryOperator for all Transformer<T, T>
892///
893/// This automatically implements `UnaryOperator<T>` for any type that
894/// implements `Transformer<T, T>`.
895///
896/// # Author
897///
898/// Haixing Hu
899impl<F, T> UnaryOperator<T> for F
900where
901 F: Transformer<T, T>,
902{
903 // empty
904}
905
906// ============================================================================
907// Type Aliases for UnaryOperator (Transformer<T, T>)
908// ============================================================================
909
910/// Type alias for `BoxTransformer<T, T>`
911///
912/// Represents a unary operator that transforms a value of type `T` to another
913/// value of the same type `T`, with single ownership semantics. Equivalent to
914/// Java's `UnaryOperator<T>`.
915///
916/// # Examples
917///
918/// ```rust
919/// use qubit_function::{BoxUnaryOperator, Transformer};
920///
921/// let increment: BoxUnaryOperator<i32> = BoxUnaryOperator::new(|x| x + 1);
922/// assert_eq!(increment.apply(41), 42);
923/// ```
924///
925/// # Author
926///
927/// Haixing Hu
928pub type BoxUnaryOperator<T> = BoxTransformer<T, T>;
929
930/// Type alias for `ArcTransformer<T, T>`
931///
932/// Represents a thread-safe unary operator that transforms a value of type `T`
933/// to another value of the same type `T`. Equivalent to Java's `UnaryOperator<T>`
934/// with shared, thread-safe ownership.
935///
936/// # Examples
937///
938/// ```rust
939/// use qubit_function::{ArcUnaryOperator, Transformer};
940///
941/// let double: ArcUnaryOperator<i32> = ArcUnaryOperator::new(|x| x * 2);
942/// let double_clone = double.clone();
943/// assert_eq!(double.apply(21), 42);
944/// assert_eq!(double_clone.apply(21), 42);
945/// ```
946///
947/// # Author
948///
949/// Haixing Hu
950pub type ArcUnaryOperator<T> = ArcTransformer<T, T>;
951
952/// Type alias for `RcTransformer<T, T>`
953///
954/// Represents a single-threaded unary operator that transforms a value of type
955/// `T` to another value of the same type `T`. Equivalent to Java's
956/// `UnaryOperator<T>` with shared, single-threaded ownership.
957///
958/// # Examples
959///
960/// ```rust
961/// use qubit_function::{RcUnaryOperator, Transformer};
962///
963/// let negate: RcUnaryOperator<i32> = RcUnaryOperator::new(|x: i32| -x);
964/// let negate_clone = negate.clone();
965/// assert_eq!(negate.apply(42), -42);
966/// assert_eq!(negate_clone.apply(42), -42);
967/// ```
968///
969/// # Author
970///
971/// Haixing Hu
972pub type RcUnaryOperator<T> = RcTransformer<T, T>;
973
974// ============================================================================
975// BoxConditionalTransformer - Box-based Conditional Transformer
976// ============================================================================
977
978/// BoxConditionalTransformer struct
979///
980/// A conditional transformer that only executes when a predicate is satisfied.
981/// Uses `BoxTransformer` and `BoxPredicate` for single ownership semantics.
982///
983/// This type is typically created by calling `BoxTransformer::when()` and is
984/// designed to work with the `or_else()` method to create if-then-else logic.
985///
986/// # Features
987///
988/// - **Single Ownership**: Not cloneable, consumes `self` on use
989/// - **Conditional Execution**: Only transforms when predicate returns `true`
990/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
991/// - **Implements Transformer**: Can be used anywhere a `Transformer` is expected
992///
993/// # Examples
994///
995/// ## With or_else Branch
996///
997/// ```rust
998/// use qubit_function::{Transformer, BoxTransformer};
999///
1000/// let double = BoxTransformer::new(|x: i32| x * 2);
1001/// let negate = BoxTransformer::new(|x: i32| -x);
1002/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
1003///
1004/// assert_eq!(conditional.apply(5), 10); // when branch executed
1005/// assert_eq!(conditional.apply(-5), 5); // or_else branch executed
1006/// ```
1007///
1008/// # Author
1009///
1010/// Haixing Hu
1011pub struct BoxConditionalTransformer<T, R> {
1012 transformer: BoxTransformer<T, R>,
1013 predicate: BoxPredicate<T>,
1014}
1015
1016// Implement BoxConditionalTransformer
1017impl_box_conditional_transformer!(
1018 BoxConditionalTransformer<T, R>,
1019 BoxTransformer,
1020 Transformer
1021);
1022
1023// Use macro to generate Debug and Display implementations
1024impl_conditional_transformer_debug_display!(BoxConditionalTransformer<T, R>);
1025
1026// ============================================================================
1027// RcConditionalTransformer - Rc-based Conditional Transformer
1028// ============================================================================
1029
1030/// RcConditionalTransformer struct
1031///
1032/// A single-threaded conditional transformer that only executes when a
1033/// predicate is satisfied. Uses `RcTransformer` and `RcPredicate` for shared
1034/// ownership within a single thread.
1035///
1036/// This type is typically created by calling `RcTransformer::when()` and is
1037/// designed to work with the `or_else()` method to create if-then-else logic.
1038///
1039/// # Features
1040///
1041/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1042/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1043/// - **Conditional Execution**: Only transforms when predicate returns `true`
1044/// - **No Lock Overhead**: More efficient than `ArcConditionalTransformer`
1045///
1046/// # Examples
1047///
1048/// ```rust
1049/// use qubit_function::{Transformer, RcTransformer};
1050///
1051/// let double = RcTransformer::new(|x: i32| x * 2);
1052/// let identity = RcTransformer::<i32, i32>::identity();
1053/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1054///
1055/// let conditional_clone = conditional.clone();
1056///
1057/// assert_eq!(conditional.apply(5), 10);
1058/// assert_eq!(conditional_clone.apply(-5), -5);
1059/// ```
1060///
1061/// # Author
1062///
1063/// Haixing Hu
1064pub struct RcConditionalTransformer<T, R> {
1065 transformer: RcTransformer<T, R>,
1066 predicate: RcPredicate<T>,
1067}
1068
1069// Implement RcConditionalTransformer
1070impl_shared_conditional_transformer!(
1071 RcConditionalTransformer<T, R>,
1072 RcTransformer,
1073 Transformer,
1074 into_rc,
1075 'static
1076);
1077
1078// Use macro to generate Debug and Display implementations
1079impl_conditional_transformer_debug_display!(RcConditionalTransformer<T, R>);
1080
1081// Implement Clone for RcConditionalTransformer
1082impl_conditional_transformer_clone!(RcConditionalTransformer<T, R>);
1083
1084// ============================================================================
1085// ArcConditionalTransformer - Arc-based Conditional Transformer
1086// ============================================================================
1087
1088/// ArcConditionalTransformer struct
1089///
1090/// A thread-safe conditional transformer that only executes when a predicate is
1091/// satisfied. Uses `ArcTransformer` and `ArcPredicate` for shared ownership
1092/// across threads.
1093///
1094/// This type is typically created by calling `ArcTransformer::when()` and is
1095/// designed to work with the `or_else()` method to create if-then-else logic.
1096///
1097/// # Features
1098///
1099/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1100/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1101/// - **Conditional Execution**: Only transforms when predicate returns `true`
1102/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1103///
1104/// # Examples
1105///
1106/// ```rust
1107/// use qubit_function::{Transformer, ArcTransformer};
1108///
1109/// let double = ArcTransformer::new(|x: i32| x * 2);
1110/// let identity = ArcTransformer::<i32, i32>::identity();
1111/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1112///
1113/// let conditional_clone = conditional.clone();
1114///
1115/// assert_eq!(conditional.apply(5), 10);
1116/// assert_eq!(conditional_clone.apply(-5), -5);
1117/// ```
1118///
1119/// # Author
1120///
1121/// Haixing Hu
1122pub struct ArcConditionalTransformer<T, R> {
1123 transformer: ArcTransformer<T, R>,
1124 predicate: ArcPredicate<T>,
1125}
1126
1127// Implement ArcConditionalTransformer
1128impl_shared_conditional_transformer!(
1129 ArcConditionalTransformer<T, R>,
1130 ArcTransformer,
1131 Transformer,
1132 into_arc,
1133 Send + Sync + 'static
1134);
1135
1136// Use macro to generate Debug and Display implementations
1137impl_conditional_transformer_debug_display!(ArcConditionalTransformer<T, R>);
1138
1139// Implement Clone for ArcConditionalTransformer
1140impl_conditional_transformer_clone!(ArcConditionalTransformer<T, R>);