prism3_function/
transformer.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism 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.
14//!
15//! This module provides the `Transformer<T, R>` trait and three
16//! implementations:
17//!
18//! - [`BoxTransformer`]: Single ownership, not cloneable
19//! - [`ArcTransformer`]: Thread-safe shared ownership, cloneable
20//! - [`RcTransformer`]: Single-threaded shared ownership, cloneable
21//!
22//! # Author
23//!
24//! Hu Haixing
25
26use std::rc::Rc;
27use std::sync::Arc;
28
29use crate::predicate::{ArcPredicate, BoxPredicate, Predicate, RcPredicate};
30use crate::transformer_once::BoxTransformerOnce;
31
32// ============================================================================
33// Core Trait
34// ============================================================================
35
36/// Transformer trait - transforms values from type T to type R
37///
38/// Defines the behavior of a transformation: converting a value of type `T`
39/// to a value of type `R` by consuming the input. This is analogous to
40/// `Fn(T) -> R` in Rust's standard library.
41///
42/// # Type Parameters
43///
44/// * `T` - The type of the input value (consumed)
45/// * `R` - The type of the output value
46///
47/// # Author
48///
49/// Hu Haixing
50pub trait Transformer<T, R> {
51    /// Applies the transformation to the input value to produce an output value
52    ///
53    /// # Parameters
54    ///
55    /// * `input` - The input value to transform (consumed)
56    ///
57    /// # Returns
58    ///
59    /// The transformed output value
60    fn apply(&self, input: T) -> R;
61
62    /// Converts to BoxTransformer
63    ///
64    /// **⚠️ Consumes `self`**: The original transformer becomes
65    /// unavailable after calling this method.
66    ///
67    /// # Default Implementation
68    ///
69    /// The default implementation wraps `self` in a `Box` and creates a
70    /// `BoxTransformer`. Types can override this method to provide more
71    /// efficient conversions.
72    ///
73    /// # Returns
74    ///
75    /// Returns `BoxTransformer<T, R>`
76    fn into_box(self) -> BoxTransformer<T, R>
77    where
78        Self: Sized + 'static,
79        T: 'static,
80        R: 'static,
81    {
82        BoxTransformer::new(move |x| self.apply(x))
83    }
84
85    /// Converts to RcTransformer
86    ///
87    /// **⚠️ Consumes `self`**: The original transformer becomes
88    /// unavailable after calling this method.
89    ///
90    /// # Default Implementation
91    ///
92    /// The default implementation wraps `self` in an `Rc` and creates an
93    /// `RcTransformer`. Types can override this method to provide more
94    /// efficient conversions.
95    ///
96    /// # Returns
97    ///
98    /// Returns `RcTransformer<T, R>`
99    fn into_rc(self) -> RcTransformer<T, R>
100    where
101        Self: Sized + 'static,
102        T: 'static,
103        R: 'static,
104    {
105        RcTransformer::new(move |x| self.apply(x))
106    }
107
108    /// Converts to ArcTransformer
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 `Arc` and creates
116    /// an `ArcTransformer`. Types can override this method to provide
117    /// more efficient conversions.
118    ///
119    /// # Returns
120    ///
121    /// Returns `ArcTransformer<T, R>`
122    fn into_arc(self) -> ArcTransformer<T, R>
123    where
124        Self: Sized + Send + Sync + 'static,
125        T: Send + Sync + 'static,
126        R: Send + Sync + 'static,
127    {
128        ArcTransformer::new(move |x| self.apply(x))
129    }
130
131    /// Converts transformer to a closure
132    ///
133    /// **⚠️ Consumes `self`**: The original transformer becomes
134    /// unavailable after calling this method.
135    ///
136    /// # Default Implementation
137    ///
138    /// The default implementation creates a closure that captures `self`
139    /// and calls its `transform` method. Types can override this method
140    /// to provide more efficient conversions.
141    ///
142    /// # Returns
143    ///
144    /// Returns a closure that implements `Fn(T) -> R`
145    fn into_fn(self) -> impl Fn(T) -> R
146    where
147        Self: Sized + 'static,
148        T: 'static,
149        R: 'static,
150    {
151        move |t: T| self.apply(t)
152    }
153
154    /// Converts to BoxTransformer without consuming self
155    ///
156    /// **📌 Borrows `&self`**: The original transformer remains usable
157    /// after calling this method.
158    ///
159    /// # Default Implementation
160    ///
161    /// The default implementation creates a new `BoxTransformer` that
162    /// captures a reference-counted clone. Types implementing `Clone`
163    /// can override this method to provide more efficient conversions.
164    ///
165    /// # Returns
166    ///
167    /// Returns `BoxTransformer<T, R>`
168    ///
169    /// # Examples
170    ///
171    /// ```rust
172    /// use prism3_function::{ArcTransformer, Transformer};
173    ///
174    /// let double = ArcTransformer::new(|x: i32| x * 2);
175    /// let boxed = double.to_box();
176    ///
177    /// // Original transformer still usable
178    /// assert_eq!(double.apply(21), 42);
179    /// assert_eq!(boxed.apply(21), 42);
180    /// ```
181    fn to_box(&self) -> BoxTransformer<T, R>
182    where
183        Self: Clone + 'static,
184        T: 'static,
185        R: 'static,
186    {
187        self.clone().into_box()
188    }
189
190    /// Converts to RcTransformer without consuming self
191    ///
192    /// **📌 Borrows `&self`**: The original transformer remains usable
193    /// after calling this method.
194    ///
195    /// # Default Implementation
196    ///
197    /// The default implementation creates a new `RcTransformer` that
198    /// captures a reference-counted clone. Types implementing `Clone`
199    /// can override this method to provide more efficient conversions.
200    ///
201    /// # Returns
202    ///
203    /// Returns `RcTransformer<T, R>`
204    ///
205    /// # Examples
206    ///
207    /// ```rust
208    /// use prism3_function::{ArcTransformer, Transformer};
209    ///
210    /// let double = ArcTransformer::new(|x: i32| x * 2);
211    /// let rc = double.to_rc();
212    ///
213    /// // Original transformer still usable
214    /// assert_eq!(double.apply(21), 42);
215    /// assert_eq!(rc.apply(21), 42);
216    /// ```
217    fn to_rc(&self) -> RcTransformer<T, R>
218    where
219        Self: Clone + 'static,
220        T: 'static,
221        R: 'static,
222    {
223        self.clone().into_rc()
224    }
225
226    /// Converts to ArcTransformer without consuming self
227    ///
228    /// **📌 Borrows `&self`**: The original transformer remains usable
229    /// after calling this method.
230    ///
231    /// # Default Implementation
232    ///
233    /// The default implementation creates a new `ArcTransformer` that
234    /// captures a reference-counted clone. Types implementing `Clone`
235    /// can override this method to provide more efficient conversions.
236    ///
237    /// # Returns
238    ///
239    /// Returns `ArcTransformer<T, R>`
240    ///
241    /// # Examples
242    ///
243    /// ```rust
244    /// use prism3_function::{ArcTransformer, Transformer};
245    ///
246    /// let double = ArcTransformer::new(|x: i32| x * 2);
247    /// let arc = double.to_arc();
248    ///
249    /// // Original transformer still usable
250    /// assert_eq!(double.apply(21), 42);
251    /// assert_eq!(arc.apply(21), 42);
252    /// ```
253    fn to_arc(&self) -> ArcTransformer<T, R>
254    where
255        Self: Clone + Send + Sync + 'static,
256        T: Send + Sync + 'static,
257        R: Send + Sync + 'static,
258    {
259        self.clone().into_arc()
260    }
261
262    /// Converts transformer to a closure without consuming self
263    ///
264    /// **📌 Borrows `&self`**: The original transformer remains usable
265    /// after calling this method.
266    ///
267    /// # Default Implementation
268    ///
269    /// The default implementation creates a closure that captures a
270    /// clone of `self` and calls its `transform` method. Types can
271    /// override this method to provide more efficient conversions.
272    ///
273    /// # Returns
274    ///
275    /// Returns a closure that implements `Fn(T) -> R`
276    ///
277    /// # Examples
278    ///
279    /// ```rust
280    /// use prism3_function::{ArcTransformer, Transformer};
281    ///
282    /// let double = ArcTransformer::new(|x: i32| x * 2);
283    /// let closure = double.to_fn();
284    ///
285    /// // Original transformer still usable
286    /// assert_eq!(double.apply(21), 42);
287    /// assert_eq!(closure(21), 42);
288    /// ```
289    fn to_fn(&self) -> impl Fn(T) -> R
290    where
291        Self: Clone + 'static,
292        T: 'static,
293        R: 'static,
294    {
295        self.clone().into_fn()
296    }
297}
298
299// ============================================================================
300// BoxTransformer - Box<dyn Fn(T) -> R>
301// ============================================================================
302
303/// BoxTransformer - transformer wrapper based on `Box<dyn Fn>`
304///
305/// A transformer wrapper that provides single ownership with reusable
306/// transformation. The transformer consumes the input and can be called
307/// multiple times.
308///
309/// # Features
310///
311/// - **Based on**: `Box<dyn Fn(T) -> R>`
312/// - **Ownership**: Single ownership, cannot be cloned
313/// - **Reusability**: Can be called multiple times (each call consumes its
314///   input)
315/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
316///
317/// # Author
318///
319/// Hu Haixing
320pub struct BoxTransformer<T, R> {
321    function: Box<dyn Fn(T) -> R>,
322}
323
324impl<T, R> BoxTransformer<T, R>
325where
326    T: 'static,
327    R: 'static,
328{
329    /// Creates a new BoxTransformer
330    ///
331    /// # Parameters
332    ///
333    /// * `f` - The closure or function to wrap
334    ///
335    /// # Examples
336    ///
337    /// ```rust
338    /// use prism3_function::{BoxTransformer, Transformer};
339    ///
340    /// let double = BoxTransformer::new(|x: i32| x * 2);
341    /// assert_eq!(double.apply(21), 42);
342    /// ```
343    pub fn new<F>(f: F) -> Self
344    where
345        F: Fn(T) -> R + 'static,
346    {
347        BoxTransformer {
348            function: Box::new(f),
349        }
350    }
351
352    /// Creates an identity transformer
353    ///
354    /// # Examples
355    ///
356    /// ```rust
357    /// use prism3_function::{BoxTransformer, Transformer};
358    ///
359    /// let identity = BoxTransformer::<i32, i32>::identity();
360    /// assert_eq!(identity.apply(42), 42);
361    /// ```
362    pub fn identity() -> BoxTransformer<T, T> {
363        BoxTransformer::new(|x| x)
364    }
365
366    /// Chain composition - applies self first, then after
367    ///
368    /// Creates a new transformer that applies this transformer first, then
369    /// applies the after transformer to the result. Consumes self.
370    ///
371    /// # Type Parameters
372    ///
373    /// * `S` - The output type of the after transformer
374    /// * `F` - The type of the after transformer (must implement
375    ///   Transformer<R, S>)
376    ///
377    /// # Parameters
378    ///
379    /// * `after` - The transformer to apply after self. **Note: This parameter
380    ///   is passed by value and will transfer ownership.** If you need to
381    ///   preserve the original transformer, clone it first (if it implements
382    ///   `Clone`). Can be:
383    ///   - A closure: `|x: R| -> S`
384    ///   - A function pointer: `fn(R) -> S`
385    ///   - A `BoxTransformer<R, S>`
386    ///   - An `RcTransformer<R, S>`
387    ///   - An `ArcTransformer<R, S>`
388    ///   - Any type implementing `Transformer<R, S>`
389    ///
390    /// # Returns
391    ///
392    /// A new BoxTransformer representing the composition
393    ///
394    /// # Examples
395    ///
396    /// ## Direct value passing (ownership transfer)
397    ///
398    /// ```rust
399    /// use prism3_function::{BoxTransformer, Transformer};
400    ///
401    /// let double = BoxTransformer::new(|x: i32| x * 2);
402    /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
403    ///
404    /// // to_string is moved here
405    /// let composed = double.and_then(to_string);
406    /// assert_eq!(composed.apply(21), "42");
407    /// // to_string.apply(5); // Would not compile - moved
408    /// ```
409    ///
410    /// ## Preserving original with clone
411    ///
412    /// ```rust
413    /// use prism3_function::{BoxTransformer, Transformer};
414    ///
415    /// let double = BoxTransformer::new(|x: i32| x * 2);
416    /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
417    ///
418    /// // Clone to preserve original
419    /// let composed = double.and_then(to_string.clone());
420    /// assert_eq!(composed.apply(21), "42");
421    ///
422    /// // Original still usable
423    /// assert_eq!(to_string.apply(5), "5");
424    /// ```
425    pub fn and_then<S, F>(self, after: F) -> BoxTransformer<T, S>
426    where
427        S: 'static,
428        F: Transformer<R, S> + 'static,
429    {
430        let self_fn = self.function;
431        BoxTransformer::new(move |x: T| after.apply(self_fn(x)))
432    }
433
434    /// Reverse composition - applies before first, then self
435    ///
436    /// Creates a new transformer that applies the before transformer first,
437    /// then applies this transformer to the result. Consumes self.
438    ///
439    /// # Type Parameters
440    ///
441    /// * `S` - The input type of the before transformer
442    /// * `F` - The type of the before transformer (must implement
443    ///   Transformer<S, T>)
444    ///
445    /// # Parameters
446    ///
447    /// * `before` - The transformer to apply before self. **Note: This parameter
448    ///   is passed by value and will transfer ownership.** If you need to
449    ///   preserve the original transformer, clone it first (if it implements
450    ///   `Clone`). Can be:
451    ///   - A closure: `|x: S| -> T`
452    ///   - A function pointer: `fn(S) -> T`
453    ///   - A `BoxTransformer<S, T>`
454    ///   - An `RcTransformer<S, T>`
455    ///   - An `ArcTransformer<S, T>`
456    ///   - Any type implementing `Transformer<S, T>`
457    ///
458    /// # Returns
459    ///
460    /// A new BoxTransformer representing the composition
461    ///
462    /// # Examples
463    ///
464    /// ## Direct value passing (ownership transfer)
465    ///
466    /// ```rust
467    /// use prism3_function::{BoxTransformer, Transformer};
468    ///
469    /// let double = BoxTransformer::new(|x: i32| x * 2);
470    /// let add_one = BoxTransformer::new(|x: i32| x + 1);
471    ///
472    /// // add_one is moved here
473    /// let composed = double.compose(add_one);
474    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
475    /// // add_one.apply(3); // Would not compile - moved
476    /// ```
477    ///
478    /// ## Preserving original with clone
479    ///
480    /// ```rust
481    /// use prism3_function::{BoxTransformer, Transformer};
482    ///
483    /// let double = BoxTransformer::new(|x: i32| x * 2);
484    /// let add_one = BoxTransformer::new(|x: i32| x + 1);
485    ///
486    /// // Clone to preserve original
487    /// let composed = double.compose(add_one.clone());
488    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
489    ///
490    /// // Original still usable
491    /// assert_eq!(add_one.apply(3), 4);
492    /// ```
493    pub fn compose<S, F>(self, before: F) -> BoxTransformer<S, R>
494    where
495        S: 'static,
496        F: Transformer<S, T> + 'static,
497    {
498        let self_fn = self.function;
499        BoxTransformer::new(move |x: S| self_fn(before.apply(x)))
500    }
501
502    /// Creates a conditional transformer
503    ///
504    /// Returns a transformer that only executes when a predicate is satisfied.
505    /// You must call `or_else()` to provide an alternative transformer for when
506    /// the condition is not satisfied.
507    ///
508    /// # Parameters
509    ///
510    /// * `predicate` - The condition to check. **Note: This parameter is passed
511    ///   by value and will transfer ownership.** If you need to preserve the
512    ///   original predicate, clone it first (if it implements `Clone`). Can be:
513    ///   - A closure: `|x: &T| -> bool`
514    ///   - A function pointer: `fn(&T) -> bool`
515    ///   - A `BoxPredicate<T>`
516    ///   - An `RcPredicate<T>`
517    ///   - An `ArcPredicate<T>`
518    ///   - Any type implementing `Predicate<T>`
519    ///
520    /// # Returns
521    ///
522    /// Returns `BoxConditionalTransformer<T, R>`
523    ///
524    /// # Examples
525    ///
526    /// ## Basic usage with or_else
527    ///
528    /// ```rust
529    /// use prism3_function::{Transformer, BoxTransformer};
530    ///
531    /// let double = BoxTransformer::new(|x: i32| x * 2);
532    /// let identity = BoxTransformer::<i32, i32>::identity();
533    /// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
534    ///
535    /// assert_eq!(conditional.apply(5), 10);
536    /// assert_eq!(conditional.apply(-5), -5); // identity
537    /// ```
538    ///
539    /// ## Preserving predicate with clone
540    ///
541    /// ```rust
542    /// use prism3_function::{Transformer, BoxTransformer, BoxPredicate};
543    ///
544    /// let double = BoxTransformer::new(|x: i32| x * 2);
545    /// let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
546    ///
547    /// // Clone to preserve original predicate
548    /// let conditional = double.when(is_positive.clone())
549    ///     .or_else(BoxTransformer::identity());
550    ///
551    /// assert_eq!(conditional.apply(5), 10);
552    ///
553    /// // Original predicate still usable
554    /// assert!(is_positive.test(&3));
555    /// ```
556    pub fn when<P>(self, predicate: P) -> BoxConditionalTransformer<T, R>
557    where
558        P: Predicate<T> + 'static,
559    {
560        BoxConditionalTransformer {
561            transformer: self,
562            predicate: predicate.into_box(),
563        }
564    }
565}
566
567impl<T, R> BoxTransformer<T, R>
568where
569    T: 'static,
570    R: Clone + 'static,
571{
572    /// Creates a constant transformer
573    ///
574    /// # Examples
575    ///
576    /// ```rust
577    /// use prism3_function::{BoxTransformer, Transformer};
578    ///
579    /// let constant = BoxTransformer::constant("hello");
580    /// assert_eq!(constant.apply(123), "hello");
581    /// ```
582    pub fn constant(value: R) -> BoxTransformer<T, R> {
583        BoxTransformer::new(move |_| value.clone())
584    }
585}
586
587impl<T, R> Transformer<T, R> for BoxTransformer<T, R> {
588    fn apply(&self, input: T) -> R {
589        (self.function)(input)
590    }
591
592    // Override with zero-cost implementation: directly return itself
593    fn into_box(self) -> BoxTransformer<T, R>
594    where
595        T: 'static,
596        R: 'static,
597    {
598        self
599    }
600
601    // Override with optimized implementation: convert Box to Rc
602    fn into_rc(self) -> RcTransformer<T, R>
603    where
604        T: 'static,
605        R: 'static,
606    {
607        RcTransformer {
608            function: Rc::from(self.function),
609        }
610    }
611
612    // do NOT override BoxTransformer::into_arc() because BoxTransformer is not Send + Sync
613    // and calling BoxTransformer::to_arc() will cause a compile error
614
615    // Override with optimized implementation: directly return the
616    // underlying function by unwrapping the Box
617    fn into_fn(self) -> impl Fn(T) -> R
618    where
619        T: 'static,
620        R: 'static,
621    {
622        self.function
623    }
624
625    // Note: BoxTransformer doesn't implement Clone, so the default to_xxx()
626    // implementations that require Clone cannot be used. We need to provide
627    // special implementations that create new transformers by wrapping the
628    // function reference.
629
630    // Override: BoxTransformer doesn't implement Clone, can't use default
631    // We create a new BoxTransformer that references self through a closure
632    // This requires T and R to be Clone-independent
633    // Users should prefer using RcTransformer if they need sharing
634
635    // Note: We intentionally don't override to_box(), to_rc(), to_arc(), to_fn()
636    // for BoxTransformer because:
637    // 1. BoxTransformer doesn't implement Clone
638    // 2. We can't share ownership of Box<dyn Fn> without cloning
639    // 3. Users should convert to RcTransformer or ArcTransformer first if they
640    //    need to create multiple references
641    // 4. The default implementations will fail to compile (as expected), which
642    //    guides users to the correct usage pattern
643}
644
645// ============================================================================
646// BoxTransformer TransformerOnce implementation
647// ============================================================================
648
649use crate::transformer_once::TransformerOnce;
650
651impl<T, R> TransformerOnce<T, R> for BoxTransformer<T, R>
652where
653    T: 'static,
654    R: 'static,
655{
656    /// Transforms the input value, consuming both self and input
657    ///
658    /// # Parameters
659    ///
660    /// * `input` - The input value (consumed)
661    ///
662    /// # Returns
663    ///
664    /// The transformed output value
665    ///
666    /// # Examples
667    ///
668    /// ```rust
669    /// use prism3_function::{BoxTransformer, TransformerOnce};
670    ///
671    /// let double = BoxTransformer::new(|x: i32| x * 2);
672    /// let result = double.apply_once(21);
673    /// assert_eq!(result, 42);
674    /// ```
675    ///
676    /// # Author
677    ///
678    /// Hu Haixing
679    fn apply_once(self, input: T) -> R {
680        (self.function)(input)
681    }
682}
683
684// ============================================================================
685// BoxConditionalTransformer - Box-based Conditional Transformer
686// ============================================================================
687
688/// BoxConditionalTransformer struct
689///
690/// A conditional transformer that only executes when a predicate is satisfied.
691/// Uses `BoxTransformer` and `BoxPredicate` for single ownership semantics.
692///
693/// This type is typically created by calling `BoxTransformer::when()` and is
694/// designed to work with the `or_else()` method to create if-then-else logic.
695///
696/// # Features
697///
698/// - **Single Ownership**: Not cloneable, consumes `self` on use
699/// - **Conditional Execution**: Only transforms when predicate returns `true`
700/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
701/// - **Implements Transformer**: Can be used anywhere a `Transformer` is expected
702///
703/// # Examples
704///
705/// ## With or_else Branch
706///
707/// ```rust
708/// use prism3_function::{Transformer, BoxTransformer};
709///
710/// let double = BoxTransformer::new(|x: i32| x * 2);
711/// let negate = BoxTransformer::new(|x: i32| -x);
712/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
713///
714/// assert_eq!(conditional.apply(5), 10); // when branch executed
715/// assert_eq!(conditional.apply(-5), 5); // or_else branch executed
716/// ```
717///
718/// # Author
719///
720/// Haixing Hu
721pub struct BoxConditionalTransformer<T, R> {
722    transformer: BoxTransformer<T, R>,
723    predicate: BoxPredicate<T>,
724}
725
726impl<T, R> BoxConditionalTransformer<T, R>
727where
728    T: 'static,
729    R: 'static,
730{
731    /// Adds an else branch
732    ///
733    /// Executes the original transformer when the condition is satisfied,
734    /// otherwise executes else_transformer.
735    ///
736    /// # Parameters
737    ///
738    /// * `else_transformer` - The transformer for the else branch, can be:
739    ///   - Closure: `|x: T| -> R`
740    ///   - `BoxTransformer<T, R>`, `RcTransformer<T, R>`, `ArcTransformer<T, R>`
741    ///   - Any type implementing `Transformer<T, R>`
742    ///
743    /// # Returns
744    ///
745    /// Returns the composed `BoxTransformer<T, R>`
746    ///
747    /// # Examples
748    ///
749    /// ## Using a closure (recommended)
750    ///
751    /// ```rust
752    /// use prism3_function::{Transformer, BoxTransformer};
753    ///
754    /// let double = BoxTransformer::new(|x: i32| x * 2);
755    /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
756    ///
757    /// assert_eq!(conditional.apply(5), 10); // Condition satisfied, execute double
758    /// assert_eq!(conditional.apply(-5), 5); // Condition not satisfied, execute negate
759    /// ```
760    pub fn or_else<F>(self, else_transformer: F) -> BoxTransformer<T, R>
761    where
762        F: Transformer<T, R> + 'static,
763    {
764        let pred = self.predicate;
765        let then_trans = self.transformer;
766        BoxTransformer::new(move |t| {
767            if pred.test(&t) {
768                then_trans.apply(t)
769            } else {
770                else_transformer.apply(t)
771            }
772        })
773    }
774}
775
776// ============================================================================
777// ArcTransformer - Arc<dyn Fn(T) -> R + Send + Sync>
778// ============================================================================
779
780/// ArcTransformer - thread-safe transformer wrapper
781///
782/// A thread-safe, clonable transformer wrapper suitable for multi-threaded
783/// scenarios. Can be called multiple times and shared across threads.
784///
785/// # Features
786///
787/// - **Based on**: `Arc<dyn Fn(T) -> R + Send + Sync>`
788/// - **Ownership**: Shared ownership via reference counting
789/// - **Reusability**: Can be called multiple times (each call consumes its
790///   input)
791/// - **Thread Safety**: Thread-safe (`Send + Sync` required)
792/// - **Clonable**: Cheap cloning via `Arc::clone`
793///
794/// # Author
795///
796/// Hu Haixing
797pub struct ArcTransformer<T, R> {
798    function: Arc<dyn Fn(T) -> R + Send + Sync>,
799}
800
801impl<T, R> ArcTransformer<T, R>
802where
803    T: Send + Sync + 'static,
804    R: 'static,
805{
806    /// Creates a new ArcTransformer
807    ///
808    /// # Parameters
809    ///
810    /// * `f` - The closure or function to wrap (must be Send + Sync)
811    ///
812    /// # Examples
813    ///
814    /// ```rust
815    /// use prism3_function::{ArcTransformer, Transformer};
816    ///
817    /// let double = ArcTransformer::new(|x: i32| x * 2);
818    /// assert_eq!(double.apply(21), 42);
819    /// ```
820    pub fn new<F>(f: F) -> Self
821    where
822        F: Fn(T) -> R + Send + Sync + 'static,
823    {
824        ArcTransformer {
825            function: Arc::new(f),
826        }
827    }
828
829    /// Creates an identity transformer
830    ///
831    /// # Examples
832    ///
833    /// ```rust
834    /// use prism3_function::{ArcTransformer, Transformer};
835    ///
836    /// let identity = ArcTransformer::<i32, i32>::identity();
837    /// assert_eq!(identity.apply(42), 42);
838    /// ```
839    pub fn identity() -> ArcTransformer<T, T> {
840        ArcTransformer::new(|x| x)
841    }
842
843    /// Chain composition - applies self first, then after
844    ///
845    /// Creates a new transformer that applies this transformer first, then
846    /// applies the after transformer to the result. Uses &self, so original
847    /// transformer remains usable.
848    ///
849    /// # Type Parameters
850    ///
851    /// * `S` - The output type of the after transformer
852    /// * `F` - The type of the after transformer (must implement
853    ///   Transformer<R, S>)
854    ///
855    /// # Parameters
856    ///
857    /// * `after` - The transformer to apply after self. **Note: This parameter
858    ///   is passed by value and will transfer ownership.** If you need to
859    ///   preserve the original transformer, clone it first (if it implements
860    ///   `Clone`). Can be:
861    ///   - A closure: `|x: R| -> S`
862    ///   - A function pointer: `fn(R) -> S`
863    ///   - A `BoxTransformer<R, S>`
864    ///   - An `RcTransformer<R, S>`
865    ///   - An `ArcTransformer<R, S>` (will be moved)
866    ///   - Any type implementing `Transformer<R, S> + Send + Sync`
867    ///
868    /// # Returns
869    ///
870    /// A new ArcTransformer representing the composition
871    ///
872    /// # Examples
873    ///
874    /// ## Direct value passing (ownership transfer)
875    ///
876    /// ```rust
877    /// use prism3_function::{ArcTransformer, Transformer};
878    ///
879    /// let double = ArcTransformer::new(|x: i32| x * 2);
880    /// let to_string = ArcTransformer::new(|x: i32| x.to_string());
881    ///
882    /// // to_string is moved here
883    /// let composed = double.and_then(to_string);
884    ///
885    /// // Original double transformer still usable (uses &self)
886    /// assert_eq!(double.apply(21), 42);
887    /// assert_eq!(composed.apply(21), "42");
888    /// // to_string.apply(5); // Would not compile - moved
889    /// ```
890    ///
891    /// ## Preserving original with clone
892    ///
893    /// ```rust
894    /// use prism3_function::{ArcTransformer, Transformer};
895    ///
896    /// let double = ArcTransformer::new(|x: i32| x * 2);
897    /// let to_string = ArcTransformer::new(|x: i32| x.to_string());
898    ///
899    /// // Clone to preserve original
900    /// let composed = double.and_then(to_string.clone());
901    /// assert_eq!(composed.apply(21), "42");
902    ///
903    /// // Both originals still usable
904    /// assert_eq!(double.apply(21), 42);
905    /// assert_eq!(to_string.apply(5), "5");
906    /// ```
907    pub fn and_then<S, F>(&self, after: F) -> ArcTransformer<T, S>
908    where
909        S: Send + Sync + 'static,
910        F: Transformer<R, S> + Send + Sync + 'static,
911    {
912        let self_fn = self.function.clone();
913        ArcTransformer {
914            function: Arc::new(move |x: T| after.apply(self_fn(x))),
915        }
916    }
917
918    /// Reverse composition - applies before first, then self
919    ///
920    /// Creates a new transformer that applies the before transformer first,
921    /// then applies this transformer to the result. Uses &self, so original
922    /// transformer remains usable.
923    ///
924    /// # Type Parameters
925    ///
926    /// * `S` - The input type of the before transformer
927    /// * `F` - The type of the before transformer (must implement
928    ///   Transformer<S, T>)
929    ///
930    /// # Parameters
931    ///
932    /// * `before` - The transformer to apply before self. **Note: This parameter
933    ///   is passed by value and will transfer ownership.** If you need to
934    ///   preserve the original transformer, clone it first (if it implements
935    ///   `Clone`). Can be:
936    ///   - A closure: `|x: S| -> T`
937    ///   - A function pointer: `fn(S) -> T`
938    ///   - A `BoxTransformer<S, T>`
939    ///   - An `RcTransformer<S, T>`
940    ///   - An `ArcTransformer<S, T>` (will be moved)
941    ///   - Any type implementing `Transformer<S, T> + Send + Sync`
942    ///
943    /// # Returns
944    ///
945    /// A new ArcTransformer representing the composition
946    ///
947    /// # Examples
948    ///
949    /// ## Direct value passing (ownership transfer)
950    ///
951    /// ```rust
952    /// use prism3_function::{ArcTransformer, Transformer};
953    ///
954    /// let double = ArcTransformer::new(|x: i32| x * 2);
955    /// let add_one = ArcTransformer::new(|x: i32| x + 1);
956    ///
957    /// // add_one is moved here
958    /// let composed = double.compose(add_one);
959    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
960    /// // add_one.apply(3); // Would not compile - moved
961    /// ```
962    ///
963    /// ## Preserving original with clone
964    ///
965    /// ```rust
966    /// use prism3_function::{ArcTransformer, Transformer};
967    ///
968    /// let double = ArcTransformer::new(|x: i32| x * 2);
969    /// let add_one = ArcTransformer::new(|x: i32| x + 1);
970    ///
971    /// // Clone to preserve original
972    /// let composed = double.compose(add_one.clone());
973    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
974    ///
975    /// // Both originals still usable
976    /// assert_eq!(double.apply(10), 20);
977    /// assert_eq!(add_one.apply(3), 4);
978    /// ```
979    pub fn compose<S, F>(&self, before: F) -> ArcTransformer<S, R>
980    where
981        S: Send + Sync + 'static,
982        F: Transformer<S, T> + Send + Sync + 'static,
983    {
984        let self_fn = self.function.clone();
985        ArcTransformer {
986            function: Arc::new(move |x: S| self_fn(before.apply(x))),
987        }
988    }
989
990    /// Creates a conditional transformer (thread-safe version)
991    ///
992    /// Returns a transformer that only executes when a predicate is satisfied.
993    /// You must call `or_else()` to provide an alternative transformer.
994    ///
995    /// # Parameters
996    ///
997    /// * `predicate` - The condition to check. **Note: This parameter is passed
998    ///   by value and will transfer ownership.** If you need to preserve the
999    ///   original predicate, clone it first (if it implements `Clone`). Must be
1000    ///   `Send + Sync`, can be:
1001    ///   - A closure: `|x: &T| -> bool` (requires `Send + Sync`)
1002    ///   - A function pointer: `fn(&T) -> bool`
1003    ///   - An `ArcPredicate<T>`
1004    ///   - Any type implementing `Predicate<T> + Send + Sync`
1005    ///
1006    /// # Returns
1007    ///
1008    /// Returns `ArcConditionalTransformer<T, R>`
1009    ///
1010    /// # Examples
1011    ///
1012    /// ## Basic usage with or_else
1013    ///
1014    /// ```rust
1015    /// use prism3_function::{Transformer, ArcTransformer};
1016    ///
1017    /// let double = ArcTransformer::new(|x: i32| x * 2);
1018    /// let identity = ArcTransformer::<i32, i32>::identity();
1019    /// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1020    ///
1021    /// let conditional_clone = conditional.clone();
1022    ///
1023    /// assert_eq!(conditional.apply(5), 10);
1024    /// assert_eq!(conditional_clone.apply(-5), -5);
1025    /// ```
1026    ///
1027    /// ## Preserving predicate with clone
1028    ///
1029    /// ```rust
1030    /// use prism3_function::{Transformer, ArcTransformer, ArcPredicate};
1031    ///
1032    /// let double = ArcTransformer::new(|x: i32| x * 2);
1033    /// let is_positive = ArcPredicate::new(|x: &i32| *x > 0);
1034    ///
1035    /// // Clone to preserve original predicate
1036    /// let conditional = double.when(is_positive.clone())
1037    ///     .or_else(ArcTransformer::identity());
1038    ///
1039    /// assert_eq!(conditional.apply(5), 10);
1040    ///
1041    /// // Original predicate still usable
1042    /// assert!(is_positive.test(&3));
1043    /// ```
1044    pub fn when<P>(&self, predicate: P) -> ArcConditionalTransformer<T, R>
1045    where
1046        P: Predicate<T> + Send + Sync + 'static,
1047    {
1048        ArcConditionalTransformer {
1049            transformer: self.clone(),
1050            predicate: predicate.into_arc(),
1051        }
1052    }
1053}
1054
1055impl<T, R> ArcTransformer<T, R>
1056where
1057    T: Send + Sync + 'static,
1058    R: Clone + 'static,
1059{
1060    /// Creates a constant transformer
1061    ///
1062    /// # Examples
1063    ///
1064    /// ```rust
1065    /// use prism3_function::{ArcTransformer, Transformer};
1066    ///
1067    /// let constant = ArcTransformer::constant("hello");
1068    /// assert_eq!(constant.apply(123), "hello");
1069    /// ```
1070    pub fn constant(value: R) -> ArcTransformer<T, R>
1071    where
1072        R: Send + Sync,
1073    {
1074        ArcTransformer::new(move |_| value.clone())
1075    }
1076}
1077
1078impl<T, R> Transformer<T, R> for ArcTransformer<T, R> {
1079    fn apply(&self, input: T) -> R {
1080        (self.function)(input)
1081    }
1082
1083    fn into_box(self) -> BoxTransformer<T, R>
1084    where
1085        T: 'static,
1086        R: 'static,
1087    {
1088        BoxTransformer::new(move |t| (self.function)(t))
1089    }
1090
1091    fn into_rc(self) -> RcTransformer<T, R>
1092    where
1093        T: 'static,
1094        R: 'static,
1095    {
1096        RcTransformer::new(move |t| (self.function)(t))
1097    }
1098
1099    fn into_arc(self) -> ArcTransformer<T, R>
1100    where
1101        T: Send + Sync + 'static,
1102        R: Send + Sync + 'static,
1103    {
1104        self
1105    }
1106
1107    fn into_fn(self) -> impl Fn(T) -> R
1108    where
1109        T: 'static,
1110        R: 'static,
1111    {
1112        move |t| (self.function)(t)
1113    }
1114
1115    fn to_box(&self) -> BoxTransformer<T, R>
1116    where
1117        T: 'static,
1118        R: 'static,
1119    {
1120        let self_fn = self.function.clone();
1121        BoxTransformer::new(move |t| self_fn(t))
1122    }
1123
1124    fn to_rc(&self) -> RcTransformer<T, R>
1125    where
1126        T: 'static,
1127        R: 'static,
1128    {
1129        let self_fn = self.function.clone();
1130        RcTransformer::new(move |t| self_fn(t))
1131    }
1132
1133    fn to_arc(&self) -> ArcTransformer<T, R>
1134    where
1135        T: Send + Sync + 'static,
1136        R: Send + Sync + 'static,
1137    {
1138        self.clone()
1139    }
1140
1141    fn to_fn(&self) -> impl Fn(T) -> R
1142    where
1143        T: 'static,
1144        R: 'static,
1145    {
1146        let self_fn = self.function.clone();
1147        move |t| self_fn(t)
1148    }
1149}
1150
1151impl<T, R> Clone for ArcTransformer<T, R> {
1152    fn clone(&self) -> Self {
1153        ArcTransformer {
1154            function: Arc::clone(&self.function),
1155        }
1156    }
1157}
1158
1159// ============================================================================
1160// ArcTransformer TransformerOnce implementation
1161// ============================================================================
1162
1163impl<T, R> TransformerOnce<T, R> for ArcTransformer<T, R>
1164where
1165    T: Send + Sync + 'static,
1166    R: 'static,
1167{
1168    /// Transforms the input value, consuming both self and input
1169    ///
1170    /// # Parameters
1171    ///
1172    /// * `input` - The input value (consumed)
1173    ///
1174    /// # Returns
1175    ///
1176    /// The transformed output value
1177    ///
1178    /// # Examples
1179    ///
1180    /// ```rust
1181    /// use prism3_function::{ArcTransformer, TransformerOnce};
1182    ///
1183    /// let double = ArcTransformer::new(|x: i32| x * 2);
1184    /// let result = double.apply_once(21);
1185    /// assert_eq!(result, 42);
1186    /// ```
1187    ///
1188    /// # Author
1189    ///
1190    /// Hu Haixing
1191    fn apply_once(self, input: T) -> R {
1192        (self.function)(input)
1193    }
1194
1195    /// Converts to BoxTransformerOnce
1196    ///
1197    /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
1198    /// after calling this method.
1199    ///
1200    /// # Returns
1201    ///
1202    /// Returns `BoxTransformerOnce<T, R>`
1203    ///
1204    /// # Examples
1205    ///
1206    /// ```rust
1207    /// use prism3_function::{ArcTransformer, TransformerOnce};
1208    ///
1209    /// let double = ArcTransformer::new(|x: i32| x * 2);
1210    /// let boxed = double.into_box_once();
1211    /// assert_eq!(boxed.apply_once(21), 42);
1212    /// ```
1213    fn into_box_once(self) -> BoxTransformerOnce<T, R>
1214    where
1215        T: 'static,
1216        R: 'static,
1217    {
1218        BoxTransformerOnce::new(move |t| (self.function)(t))
1219    }
1220
1221    /// Converts transformer to a closure
1222    ///
1223    /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
1224    /// after calling this method.
1225    ///
1226    /// # Returns
1227    ///
1228    /// Returns a closure that implements `FnOnce(T) -> R`
1229    ///
1230    /// # Examples
1231    ///
1232    /// ```rust
1233    /// use prism3_function::{ArcTransformer, TransformerOnce};
1234    ///
1235    /// let double = ArcTransformer::new(|x: i32| x * 2);
1236    /// let func = double.into_fn_once();
1237    /// assert_eq!(func(21), 42);
1238    /// ```
1239    fn into_fn_once(self) -> impl FnOnce(T) -> R
1240    where
1241        T: 'static,
1242        R: 'static,
1243    {
1244        move |t| (self.function)(t)
1245    }
1246
1247    /// Converts to BoxTransformerOnce without consuming self
1248    ///
1249    /// **📌 Borrows `&self`**: The original transformer remains usable
1250    /// after calling this method.
1251    ///
1252    /// # Returns
1253    ///
1254    /// Returns `BoxTransformerOnce<T, R>`
1255    ///
1256    /// # Examples
1257    ///
1258    /// ```rust
1259    /// use prism3_function::{ArcTransformer, TransformerOnce};
1260    ///
1261    /// let double = ArcTransformer::new(|x: i32| x * 2);
1262    /// let boxed = double.to_box_once();
1263    /// assert_eq!(boxed.apply_once(21), 42);
1264    ///
1265    /// // Original transformer still usable
1266    /// assert_eq!(double.apply(21), 42);
1267    /// ```
1268    fn to_box_once(&self) -> BoxTransformerOnce<T, R>
1269    where
1270        T: 'static,
1271        R: 'static,
1272    {
1273        let self_fn = self.function.clone();
1274        BoxTransformerOnce::new(move |t| self_fn(t))
1275    }
1276
1277    /// Converts transformer to a closure without consuming self
1278    ///
1279    /// **📌 Borrows `&self`**: The original transformer remains usable
1280    /// after calling this method.
1281    ///
1282    /// # Returns
1283    ///
1284    /// Returns a closure that implements `FnOnce(T) -> R`
1285    ///
1286    /// # Examples
1287    ///
1288    /// ```rust
1289    /// use prism3_function::{ArcTransformer, TransformerOnce};
1290    ///
1291    /// let double = ArcTransformer::new(|x: i32| x * 2);
1292    /// let func = double.to_fn_once();
1293    /// assert_eq!(func(21), 42);
1294    ///
1295    /// // Original transformer still usable
1296    /// assert_eq!(double.apply(21), 42);
1297    /// ```
1298    fn to_fn_once(&self) -> impl FnOnce(T) -> R
1299    where
1300        T: 'static,
1301        R: 'static,
1302    {
1303        let self_fn = self.function.clone();
1304        move |t| self_fn(t)
1305    }
1306}
1307
1308// ============================================================================
1309// ArcConditionalTransformer - Arc-based Conditional Transformer
1310// ============================================================================
1311
1312/// ArcConditionalTransformer struct
1313///
1314/// A thread-safe conditional transformer that only executes when a predicate is
1315/// satisfied. Uses `ArcTransformer` and `ArcPredicate` for shared ownership
1316/// across threads.
1317///
1318/// This type is typically created by calling `ArcTransformer::when()` and is
1319/// designed to work with the `or_else()` method to create if-then-else logic.
1320///
1321/// # Features
1322///
1323/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
1324/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
1325/// - **Conditional Execution**: Only transforms when predicate returns `true`
1326/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
1327///
1328/// # Examples
1329///
1330/// ```rust
1331/// use prism3_function::{Transformer, ArcTransformer};
1332///
1333/// let double = ArcTransformer::new(|x: i32| x * 2);
1334/// let identity = ArcTransformer::<i32, i32>::identity();
1335/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1336///
1337/// let conditional_clone = conditional.clone();
1338///
1339/// assert_eq!(conditional.apply(5), 10);
1340/// assert_eq!(conditional_clone.apply(-5), -5);
1341/// ```
1342///
1343/// # Author
1344///
1345/// Haixing Hu
1346pub struct ArcConditionalTransformer<T, R> {
1347    transformer: ArcTransformer<T, R>,
1348    predicate: ArcPredicate<T>,
1349}
1350
1351impl<T, R> ArcConditionalTransformer<T, R>
1352where
1353    T: Send + Sync + 'static,
1354    R: 'static,
1355{
1356    /// Adds an else branch (thread-safe version)
1357    ///
1358    /// Executes the original transformer when the condition is satisfied,
1359    /// otherwise executes else_transformer.
1360    ///
1361    /// # Parameters
1362    ///
1363    /// * `else_transformer` - The transformer for the else branch, can be:
1364    ///   - Closure: `|x: T| -> R` (must be `Send + Sync`)
1365    ///   - `ArcTransformer<T, R>`, `BoxTransformer<T, R>`
1366    ///   - Any type implementing `Transformer<T, R> + Send + Sync`
1367    ///
1368    /// # Returns
1369    ///
1370    /// Returns the composed `ArcTransformer<T, R>`
1371    ///
1372    /// # Examples
1373    ///
1374    /// ## Using a closure (recommended)
1375    ///
1376    /// ```rust
1377    /// use prism3_function::{Transformer, ArcTransformer};
1378    ///
1379    /// let double = ArcTransformer::new(|x: i32| x * 2);
1380    /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
1381    ///
1382    /// assert_eq!(conditional.apply(5), 10);
1383    /// assert_eq!(conditional.apply(-5), 5);
1384    /// ```
1385    pub fn or_else<F>(self, else_transformer: F) -> ArcTransformer<T, R>
1386    where
1387        F: Transformer<T, R> + Send + Sync + 'static,
1388        R: Send + Sync,
1389    {
1390        let pred = self.predicate;
1391        let then_trans = self.transformer;
1392        ArcTransformer::new(move |t| {
1393            if pred.test(&t) {
1394                then_trans.apply(t)
1395            } else {
1396                else_transformer.apply(t)
1397            }
1398        })
1399    }
1400}
1401
1402impl<T, R> Clone for ArcConditionalTransformer<T, R> {
1403    /// Clones the conditional transformer
1404    ///
1405    /// Creates a new instance that shares the underlying transformer and
1406    /// predicate with the original instance.
1407    fn clone(&self) -> Self {
1408        Self {
1409            transformer: self.transformer.clone(),
1410            predicate: self.predicate.clone(),
1411        }
1412    }
1413}
1414
1415// ============================================================================
1416// RcTransformer - Rc<dyn Fn(T) -> R>
1417// ============================================================================
1418
1419/// RcTransformer - single-threaded transformer wrapper
1420///
1421/// A single-threaded, clonable transformer wrapper optimized for scenarios
1422/// that require sharing without thread-safety overhead.
1423///
1424/// # Features
1425///
1426/// - **Based on**: `Rc<dyn Fn(T) -> R>`
1427/// - **Ownership**: Shared ownership via reference counting (non-atomic)
1428/// - **Reusability**: Can be called multiple times (each call consumes its
1429///   input)
1430/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
1431/// - **Clonable**: Cheap cloning via `Rc::clone`
1432///
1433/// # Author
1434///
1435/// Hu Haixing
1436pub struct RcTransformer<T, R> {
1437    function: Rc<dyn Fn(T) -> R>,
1438}
1439
1440impl<T, R> RcTransformer<T, R>
1441where
1442    T: 'static,
1443    R: 'static,
1444{
1445    /// Creates a new RcTransformer
1446    ///
1447    /// # Parameters
1448    ///
1449    /// * `f` - The closure or function to wrap
1450    ///
1451    /// # Examples
1452    ///
1453    /// ```rust
1454    /// use prism3_function::{RcTransformer, Transformer};
1455    ///
1456    /// let double = RcTransformer::new(|x: i32| x * 2);
1457    /// assert_eq!(double.apply(21), 42);
1458    /// ```
1459    pub fn new<F>(f: F) -> Self
1460    where
1461        F: Fn(T) -> R + 'static,
1462    {
1463        RcTransformer {
1464            function: Rc::new(f),
1465        }
1466    }
1467
1468    /// Creates an identity transformer
1469    ///
1470    /// # Examples
1471    ///
1472    /// ```rust
1473    /// use prism3_function::{RcTransformer, Transformer};
1474    ///
1475    /// let identity = RcTransformer::<i32, i32>::identity();
1476    /// assert_eq!(identity.apply(42), 42);
1477    /// ```
1478    pub fn identity() -> RcTransformer<T, T> {
1479        RcTransformer::new(|x| x)
1480    }
1481
1482    /// Chain composition - applies self first, then after
1483    ///
1484    /// Creates a new transformer that applies this transformer first, then
1485    /// applies the after transformer to the result. Uses &self, so original
1486    /// transformer remains usable.
1487    ///
1488    /// # Type Parameters
1489    ///
1490    /// * `S` - The output type of the after transformer
1491    /// * `F` - The type of the after transformer (must implement
1492    ///   Transformer<R, S>)
1493    ///
1494    /// # Parameters
1495    ///
1496    /// * `after` - The transformer to apply after self. **Note: This parameter
1497    ///   is passed by value and will transfer ownership.** If you need to
1498    ///   preserve the original transformer, clone it first (if it implements
1499    ///   `Clone`). Can be:
1500    ///   - A closure: `|x: R| -> S`
1501    ///   - A function pointer: `fn(R) -> S`
1502    ///   - A `BoxTransformer<R, S>`
1503    ///   - An `RcTransformer<R, S>` (will be moved)
1504    ///   - An `ArcTransformer<R, S>`
1505    ///   - Any type implementing `Transformer<R, S>`
1506    ///
1507    /// # Returns
1508    ///
1509    /// A new RcTransformer representing the composition
1510    ///
1511    /// # Examples
1512    ///
1513    /// ## Direct value passing (ownership transfer)
1514    ///
1515    /// ```rust
1516    /// use prism3_function::{RcTransformer, Transformer};
1517    ///
1518    /// let double = RcTransformer::new(|x: i32| x * 2);
1519    /// let to_string = RcTransformer::new(|x: i32| x.to_string());
1520    ///
1521    /// // to_string is moved here
1522    /// let composed = double.and_then(to_string);
1523    ///
1524    /// // Original double transformer still usable (uses &self)
1525    /// assert_eq!(double.apply(21), 42);
1526    /// assert_eq!(composed.apply(21), "42");
1527    /// // to_string.apply(5); // Would not compile - moved
1528    /// ```
1529    ///
1530    /// ## Preserving original with clone
1531    ///
1532    /// ```rust
1533    /// use prism3_function::{RcTransformer, Transformer};
1534    ///
1535    /// let double = RcTransformer::new(|x: i32| x * 2);
1536    /// let to_string = RcTransformer::new(|x: i32| x.to_string());
1537    ///
1538    /// // Clone to preserve original
1539    /// let composed = double.and_then(to_string.clone());
1540    /// assert_eq!(composed.apply(21), "42");
1541    ///
1542    /// // Both originals still usable
1543    /// assert_eq!(double.apply(21), 42);
1544    /// assert_eq!(to_string.apply(5), "5");
1545    /// ```
1546    pub fn and_then<S, F>(&self, after: F) -> RcTransformer<T, S>
1547    where
1548        S: 'static,
1549        F: Transformer<R, S> + 'static,
1550    {
1551        let self_fn = self.function.clone();
1552        RcTransformer {
1553            function: Rc::new(move |x: T| after.apply(self_fn(x))),
1554        }
1555    }
1556
1557    /// Reverse composition - applies before first, then self
1558    ///
1559    /// Creates a new transformer that applies the before transformer first,
1560    /// then applies this transformer to the result. Uses &self, so original
1561    /// transformer remains usable.
1562    ///
1563    /// # Type Parameters
1564    ///
1565    /// * `S` - The input type of the before transformer
1566    /// * `F` - The type of the before transformer (must implement
1567    ///   Transformer<S, T>)
1568    ///
1569    /// # Parameters
1570    ///
1571    /// * `before` - The transformer to apply before self. **Note: This parameter
1572    ///   is passed by value and will transfer ownership.** If you need to
1573    ///   preserve the original transformer, clone it first (if it implements
1574    ///   `Clone`). Can be:
1575    ///   - A closure: `|x: S| -> T`
1576    ///   - A function pointer: `fn(S) -> T`
1577    ///   - A `BoxTransformer<S, T>`
1578    ///   - An `RcTransformer<S, T>` (will be moved)
1579    ///   - An `ArcTransformer<S, T>`
1580    ///   - Any type implementing `Transformer<S, T>`
1581    ///
1582    /// # Returns
1583    ///
1584    /// A new RcTransformer representing the composition
1585    ///
1586    /// # Examples
1587    ///
1588    /// ## Direct value passing (ownership transfer)
1589    ///
1590    /// ```rust
1591    /// use prism3_function::{RcTransformer, Transformer};
1592    ///
1593    /// let double = RcTransformer::new(|x: i32| x * 2);
1594    /// let add_one = RcTransformer::new(|x: i32| x + 1);
1595    ///
1596    /// // add_one is moved here
1597    /// let composed = double.compose(add_one);
1598    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
1599    /// // add_one.apply(3); // Would not compile - moved
1600    /// ```
1601    ///
1602    /// ## Preserving original with clone
1603    ///
1604    /// ```rust
1605    /// use prism3_function::{RcTransformer, Transformer};
1606    ///
1607    /// let double = RcTransformer::new(|x: i32| x * 2);
1608    /// let add_one = RcTransformer::new(|x: i32| x + 1);
1609    ///
1610    /// // Clone to preserve original
1611    /// let composed = double.compose(add_one.clone());
1612    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
1613    ///
1614    /// // Both originals still usable
1615    /// assert_eq!(double.apply(10), 20);
1616    /// assert_eq!(add_one.apply(3), 4);
1617    /// ```
1618    pub fn compose<S, F>(&self, before: F) -> RcTransformer<S, R>
1619    where
1620        S: 'static,
1621        F: Transformer<S, T> + 'static,
1622    {
1623        let self_clone = Rc::clone(&self.function);
1624        RcTransformer {
1625            function: Rc::new(move |x: S| self_clone(before.apply(x))),
1626        }
1627    }
1628
1629    /// Creates a conditional transformer (single-threaded shared version)
1630    ///
1631    /// Returns a transformer that only executes when a predicate is satisfied.
1632    /// You must call `or_else()` to provide an alternative transformer.
1633    ///
1634    /// # Parameters
1635    ///
1636    /// * `predicate` - The condition to check. **Note: This parameter is passed
1637    ///   by value and will transfer ownership.** If you need to preserve the
1638    ///   original predicate, clone it first (if it implements `Clone`). Can be:
1639    ///   - A closure: `|x: &T| -> bool`
1640    ///   - A function pointer: `fn(&T) -> bool`
1641    ///   - A `BoxPredicate<T>`
1642    ///   - An `RcPredicate<T>`
1643    ///   - An `ArcPredicate<T>`
1644    ///   - Any type implementing `Predicate<T>`
1645    ///
1646    /// # Returns
1647    ///
1648    /// Returns `RcConditionalTransformer<T, R>`
1649    ///
1650    /// # Examples
1651    ///
1652    /// ## Basic usage with or_else
1653    ///
1654    /// ```rust
1655    /// use prism3_function::{Transformer, RcTransformer};
1656    ///
1657    /// let double = RcTransformer::new(|x: i32| x * 2);
1658    /// let identity = RcTransformer::<i32, i32>::identity();
1659    /// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1660    ///
1661    /// let conditional_clone = conditional.clone();
1662    ///
1663    /// assert_eq!(conditional.apply(5), 10);
1664    /// assert_eq!(conditional_clone.apply(-5), -5);
1665    /// ```
1666    ///
1667    /// ## Preserving predicate with clone
1668    ///
1669    /// ```rust
1670    /// use prism3_function::{Transformer, RcTransformer, RcPredicate};
1671    ///
1672    /// let double = RcTransformer::new(|x: i32| x * 2);
1673    /// let is_positive = RcPredicate::new(|x: &i32| *x > 0);
1674    ///
1675    /// // Clone to preserve original predicate
1676    /// let conditional = double.when(is_positive.clone())
1677    ///     .or_else(RcTransformer::identity());
1678    ///
1679    /// assert_eq!(conditional.apply(5), 10);
1680    ///
1681    /// // Original predicate still usable
1682    /// assert!(is_positive.test(&3));
1683    /// ```
1684    pub fn when<P>(&self, predicate: P) -> RcConditionalTransformer<T, R>
1685    where
1686        P: Predicate<T> + 'static,
1687    {
1688        RcConditionalTransformer {
1689            transformer: self.clone(),
1690            predicate: predicate.into_rc(),
1691        }
1692    }
1693}
1694
1695impl<T, R> RcTransformer<T, R>
1696where
1697    T: 'static,
1698    R: Clone + 'static,
1699{
1700    /// Creates a constant transformer
1701    ///
1702    /// # Examples
1703    ///
1704    /// ```rust
1705    /// use prism3_function::{RcTransformer, Transformer};
1706    ///
1707    /// let constant = RcTransformer::constant("hello");
1708    /// assert_eq!(constant.apply(123), "hello");
1709    /// ```
1710    pub fn constant(value: R) -> RcTransformer<T, R> {
1711        RcTransformer::new(move |_| value.clone())
1712    }
1713}
1714
1715impl<T, R> Transformer<T, R> for RcTransformer<T, R> {
1716    fn apply(&self, input: T) -> R {
1717        (self.function)(input)
1718    }
1719
1720    // RcTransformer::into_box() is implemented by the default implementation
1721    // of Transformer::into_box()
1722
1723    fn into_box(self) -> BoxTransformer<T, R>
1724    where
1725        T: 'static,
1726        R: 'static,
1727    {
1728        BoxTransformer::new(move |t| (self.function)(t))
1729    }
1730
1731    // Override with zero-cost implementation: directly return itself
1732    fn into_rc(self) -> RcTransformer<T, R>
1733    where
1734        T: 'static,
1735        R: 'static,
1736    {
1737        self
1738    }
1739
1740    // do NOT override RcTransformer::into_arc() because RcTransformer is not Send + Sync
1741    // and calling RcTransformer::into_arc() will cause a compile error
1742
1743    // Override with optimized implementation: wrap the Rc in a
1744    // closure to avoid double indirection
1745    fn into_fn(self) -> impl Fn(T) -> R
1746    where
1747        T: 'static,
1748        R: 'static,
1749    {
1750        move |t| (self.function)(t)
1751    }
1752
1753    // Override with optimized implementation: clone the Rc (cheap)
1754    fn to_box(&self) -> BoxTransformer<T, R>
1755    where
1756        T: 'static,
1757        R: 'static,
1758    {
1759        let self_fn = self.function.clone();
1760        BoxTransformer::new(move |t| self_fn(t))
1761    }
1762
1763    // Override with zero-cost implementation: clone itself
1764    fn to_rc(&self) -> RcTransformer<T, R>
1765    where
1766        T: 'static,
1767        R: 'static,
1768    {
1769        self.clone()
1770    }
1771
1772    // do NOT override RcTransformer::to_arc() because RcTransformer is not Send + Sync
1773    // and calling RcTransformer::to_arc() will cause a compile error
1774
1775    // Override with optimized implementation: clone the Rc (cheap)
1776    fn to_fn(&self) -> impl Fn(T) -> R
1777    where
1778        T: 'static,
1779        R: 'static,
1780    {
1781        let self_fn = self.function.clone();
1782        move |t| self_fn(t)
1783    }
1784}
1785
1786impl<T, R> Clone for RcTransformer<T, R> {
1787    fn clone(&self) -> Self {
1788        RcTransformer {
1789            function: Rc::clone(&self.function),
1790        }
1791    }
1792}
1793
1794// ============================================================================
1795// RcTransformer TransformerOnce implementation
1796// ============================================================================
1797
1798impl<T, R> TransformerOnce<T, R> for RcTransformer<T, R>
1799where
1800    T: 'static,
1801    R: 'static,
1802{
1803    /// Transforms the input value, consuming both self and input
1804    ///
1805    /// # Parameters
1806    ///
1807    /// * `input` - The input value (consumed)
1808    ///
1809    /// # Returns
1810    ///
1811    /// The transformed output value
1812    ///
1813    /// # Examples
1814    ///
1815    /// ```rust
1816    /// use prism3_function::{RcTransformer, TransformerOnce};
1817    ///
1818    /// let double = RcTransformer::new(|x: i32| x * 2);
1819    /// let result = double.apply_once(21);
1820    /// assert_eq!(result, 42);
1821    /// ```
1822    ///
1823    /// # Author
1824    ///
1825    /// Hu Haixing
1826    fn apply_once(self, input: T) -> R {
1827        (self.function)(input)
1828    }
1829
1830    /// Converts to BoxTransformerOnce
1831    ///
1832    /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
1833    /// after calling this method.
1834    ///
1835    /// # Returns
1836    ///
1837    /// Returns `BoxTransformerOnce<T, R>`
1838    ///
1839    /// # Examples
1840    ///
1841    /// ```rust
1842    /// use prism3_function::{RcTransformer, TransformerOnce};
1843    ///
1844    /// let double = RcTransformer::new(|x: i32| x * 2);
1845    /// let boxed = double.into_box_once();
1846    /// assert_eq!(boxed.apply_once(21), 42);
1847    /// ```
1848    fn into_box_once(self) -> BoxTransformerOnce<T, R>
1849    where
1850        T: 'static,
1851        R: 'static,
1852    {
1853        BoxTransformerOnce::new(move |t| (self.function)(t))
1854    }
1855
1856    /// Converts transformer to a closure
1857    ///
1858    /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
1859    /// after calling this method.
1860    ///
1861    /// # Returns
1862    ///
1863    /// Returns a closure that implements `FnOnce(T) -> R`
1864    ///
1865    /// # Examples
1866    ///
1867    /// ```rust
1868    /// use prism3_function::{RcTransformer, TransformerOnce};
1869    ///
1870    /// let double = RcTransformer::new(|x: i32| x * 2);
1871    /// let func = double.into_fn_once();
1872    /// assert_eq!(func(21), 42);
1873    /// ```
1874    fn into_fn_once(self) -> impl FnOnce(T) -> R
1875    where
1876        T: 'static,
1877        R: 'static,
1878    {
1879        move |t| (self.function)(t)
1880    }
1881
1882    /// Converts to BoxTransformerOnce without consuming self
1883    ///
1884    /// **📌 Borrows `&self`**: The original transformer remains usable
1885    /// after calling this method.
1886    ///
1887    /// # Returns
1888    ///
1889    /// Returns `BoxTransformerOnce<T, R>`
1890    ///
1891    /// # Examples
1892    ///
1893    /// ```rust
1894    /// use prism3_function::{RcTransformer, TransformerOnce};
1895    ///
1896    /// let double = RcTransformer::new(|x: i32| x * 2);
1897    /// let boxed = double.to_box_once();
1898    /// assert_eq!(boxed.apply_once(21), 42);
1899    ///
1900    /// // Original transformer still usable
1901    /// assert_eq!(double.apply(21), 42);
1902    /// ```
1903    fn to_box_once(&self) -> BoxTransformerOnce<T, R>
1904    where
1905        T: 'static,
1906        R: 'static,
1907    {
1908        let self_fn = self.function.clone();
1909        BoxTransformerOnce::new(move |t| self_fn(t))
1910    }
1911
1912    /// Converts transformer to a closure without consuming self
1913    ///
1914    /// **📌 Borrows `&self`**: The original transformer remains usable
1915    /// after calling this method.
1916    ///
1917    /// # Returns
1918    ///
1919    /// Returns a closure that implements `FnOnce(T) -> R`
1920    ///
1921    /// # Examples
1922    ///
1923    /// ```rust
1924    /// use prism3_function::{RcTransformer, TransformerOnce};
1925    ///
1926    /// let double = RcTransformer::new(|x: i32| x * 2);
1927    /// let func = double.to_fn_once();
1928    /// assert_eq!(func(21), 42);
1929    ///
1930    /// // Original transformer still usable
1931    /// assert_eq!(double.apply(21), 42);
1932    /// ```
1933    fn to_fn_once(&self) -> impl FnOnce(T) -> R
1934    where
1935        T: 'static,
1936        R: 'static,
1937    {
1938        let self_fn = self.function.clone();
1939        move |t| self_fn(t)
1940    }
1941}
1942
1943// ============================================================================
1944// RcConditionalTransformer - Rc-based Conditional Transformer
1945// ============================================================================
1946
1947/// RcConditionalTransformer struct
1948///
1949/// A single-threaded conditional transformer that only executes when a
1950/// predicate is satisfied. Uses `RcTransformer` and `RcPredicate` for shared
1951/// ownership within a single thread.
1952///
1953/// This type is typically created by calling `RcTransformer::when()` and is
1954/// designed to work with the `or_else()` method to create if-then-else logic.
1955///
1956/// # Features
1957///
1958/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
1959/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
1960/// - **Conditional Execution**: Only transforms when predicate returns `true`
1961/// - **No Lock Overhead**: More efficient than `ArcConditionalTransformer`
1962///
1963/// # Examples
1964///
1965/// ```rust
1966/// use prism3_function::{Transformer, RcTransformer};
1967///
1968/// let double = RcTransformer::new(|x: i32| x * 2);
1969/// let identity = RcTransformer::<i32, i32>::identity();
1970/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
1971///
1972/// let conditional_clone = conditional.clone();
1973///
1974/// assert_eq!(conditional.apply(5), 10);
1975/// assert_eq!(conditional_clone.apply(-5), -5);
1976/// ```
1977///
1978/// # Author
1979///
1980/// Haixing Hu
1981pub struct RcConditionalTransformer<T, R> {
1982    transformer: RcTransformer<T, R>,
1983    predicate: RcPredicate<T>,
1984}
1985
1986impl<T, R> RcConditionalTransformer<T, R>
1987where
1988    T: 'static,
1989    R: 'static,
1990{
1991    /// Adds an else branch (single-threaded shared version)
1992    ///
1993    /// Executes the original transformer when the condition is satisfied,
1994    /// otherwise executes else_transformer.
1995    ///
1996    /// # Parameters
1997    ///
1998    /// * `else_transformer` - The transformer for the else branch, can be:
1999    ///   - Closure: `|x: T| -> R`
2000    ///   - `RcTransformer<T, R>`, `BoxTransformer<T, R>`
2001    ///   - Any type implementing `Transformer<T, R>`
2002    ///
2003    /// # Returns
2004    ///
2005    /// Returns the composed `RcTransformer<T, R>`
2006    ///
2007    /// # Examples
2008    ///
2009    /// ## Using a closure (recommended)
2010    ///
2011    /// ```rust
2012    /// use prism3_function::{Transformer, RcTransformer};
2013    ///
2014    /// let double = RcTransformer::new(|x: i32| x * 2);
2015    /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
2016    ///
2017    /// assert_eq!(conditional.apply(5), 10);
2018    /// assert_eq!(conditional.apply(-5), 5);
2019    /// ```
2020    pub fn or_else<F>(self, else_transformer: F) -> RcTransformer<T, R>
2021    where
2022        F: Transformer<T, R> + 'static,
2023    {
2024        let pred = self.predicate;
2025        let then_trans = self.transformer;
2026        RcTransformer::new(move |t| {
2027            if pred.test(&t) {
2028                then_trans.apply(t)
2029            } else {
2030                else_transformer.apply(t)
2031            }
2032        })
2033    }
2034}
2035
2036impl<T, R> Clone for RcConditionalTransformer<T, R> {
2037    /// Clones the conditional transformer
2038    ///
2039    /// Creates a new instance that shares the underlying transformer and
2040    /// predicate with the original instance.
2041    fn clone(&self) -> Self {
2042        Self {
2043            transformer: self.transformer.clone(),
2044            predicate: self.predicate.clone(),
2045        }
2046    }
2047}
2048
2049// ============================================================================
2050// Blanket implementation for standard Fn trait
2051// ============================================================================
2052
2053/// Implement Transformer<T, R> for any type that implements Fn(T) -> R
2054///
2055/// This allows closures and function pointers to be used directly with our
2056/// Transformer trait without wrapping.
2057///
2058/// # Examples
2059///
2060/// ```rust
2061/// use prism3_function::Transformer;
2062///
2063/// fn double(x: i32) -> i32 { x * 2 }
2064///
2065/// assert_eq!(double.apply(21), 42);
2066///
2067/// let triple = |x: i32| x * 3;
2068/// assert_eq!(triple.apply(14), 42);
2069/// ```
2070///
2071/// # Author
2072///
2073/// Hu Haixing
2074impl<F, T, R> Transformer<T, R> for F
2075where
2076    F: Fn(T) -> R,
2077    T: 'static,
2078    R: 'static,
2079{
2080    fn apply(&self, input: T) -> R {
2081        self(input)
2082    }
2083
2084    fn into_box(self) -> BoxTransformer<T, R>
2085    where
2086        Self: Sized + 'static,
2087    {
2088        BoxTransformer::new(self)
2089    }
2090
2091    fn into_rc(self) -> RcTransformer<T, R>
2092    where
2093        Self: Sized + 'static,
2094    {
2095        RcTransformer::new(self)
2096    }
2097
2098    fn into_arc(self) -> ArcTransformer<T, R>
2099    where
2100        Self: Sized + Send + Sync + 'static,
2101        T: Send + Sync + 'static,
2102        R: Send + Sync + 'static,
2103    {
2104        ArcTransformer::new(self)
2105    }
2106
2107    fn into_fn(self) -> impl Fn(T) -> R
2108    where
2109        Self: Sized + 'static,
2110    {
2111        self
2112    }
2113
2114    fn to_box(&self) -> BoxTransformer<T, R>
2115    where
2116        Self: Clone + Sized + 'static,
2117    {
2118        self.clone().into_box()
2119    }
2120
2121    fn to_rc(&self) -> RcTransformer<T, R>
2122    where
2123        Self: Clone + Sized + 'static,
2124    {
2125        self.clone().into_rc()
2126    }
2127
2128    fn to_arc(&self) -> ArcTransformer<T, R>
2129    where
2130        Self: Clone + Sized + Send + Sync + 'static,
2131        T: Send + Sync + 'static,
2132        R: Send + Sync + 'static,
2133    {
2134        self.clone().into_arc()
2135    }
2136
2137    fn to_fn(&self) -> impl Fn(T) -> R
2138    where
2139        Self: Clone + Sized + 'static,
2140    {
2141        self.clone()
2142    }
2143}
2144
2145// ============================================================================
2146// FnTransformerOps - Extension trait for closure transformers
2147// ============================================================================
2148
2149/// Extension trait for closures implementing `Fn(T) -> R`
2150///
2151/// Provides composition methods (`and_then`, `compose`, `when`) for closures
2152/// and function pointers without requiring explicit wrapping in
2153/// `BoxTransformer`, `RcTransformer`, or `ArcTransformer`.
2154///
2155/// This trait is automatically implemented for all closures and function
2156/// pointers that implement `Fn(T) -> R`.
2157///
2158/// # Design Rationale
2159///
2160/// While closures automatically implement `Transformer<T, R>` through blanket
2161/// implementation, they don't have access to instance methods like `and_then`,
2162/// `compose`, and `when`. This extension trait provides those methods,
2163/// returning `BoxTransformer` for maximum flexibility.
2164///
2165/// # Examples
2166///
2167/// ## Chain composition with and_then
2168///
2169/// ```rust
2170/// use prism3_function::{Transformer, FnTransformerOps};
2171///
2172/// let double = |x: i32| x * 2;
2173/// let to_string = |x: i32| x.to_string();
2174///
2175/// let composed = double.and_then(to_string);
2176/// assert_eq!(composed.apply(21), "42");
2177/// ```
2178///
2179/// ## Reverse composition with compose
2180///
2181/// ```rust
2182/// use prism3_function::{Transformer, FnTransformerOps};
2183///
2184/// let double = |x: i32| x * 2;
2185/// let add_one = |x: i32| x + 1;
2186///
2187/// let composed = double.compose(add_one);
2188/// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
2189/// ```
2190///
2191/// ## Conditional transformation with when
2192///
2193/// ```rust
2194/// use prism3_function::{Transformer, FnTransformerOps};
2195///
2196/// let double = |x: i32| x * 2;
2197/// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
2198///
2199/// assert_eq!(conditional.apply(5), 10);
2200/// assert_eq!(conditional.apply(-5), 5);
2201/// ```
2202///
2203/// # Author
2204///
2205/// Hu Haixing
2206pub trait FnTransformerOps<T, R>: Fn(T) -> R + Sized + 'static {
2207    /// Chain composition - applies self first, then after
2208    ///
2209    /// Creates a new transformer that applies this transformer first, then
2210    /// applies the after transformer to the result. Consumes self and returns
2211    /// a `BoxTransformer`.
2212    ///
2213    /// # Type Parameters
2214    ///
2215    /// * `S` - The output type of the after transformer
2216    /// * `F` - The type of the after transformer (must implement Transformer<R, S>)
2217    ///
2218    /// # Parameters
2219    ///
2220    /// * `after` - The transformer to apply after self. **Note: This parameter
2221    ///   is passed by value and will transfer ownership.** If you need to
2222    ///   preserve the original transformer, clone it first (if it implements
2223    ///   `Clone`). Can be:
2224    ///   - A closure: `|x: R| -> S`
2225    ///   - A function pointer: `fn(R) -> S`
2226    ///   - A `BoxTransformer<R, S>`
2227    ///   - An `RcTransformer<R, S>`
2228    ///   - An `ArcTransformer<R, S>`
2229    ///   - Any type implementing `Transformer<R, S>`
2230    ///
2231    /// # Returns
2232    ///
2233    /// A new `BoxTransformer<T, S>` representing the composition
2234    ///
2235    /// # Examples
2236    ///
2237    /// ## Direct value passing (ownership transfer)
2238    ///
2239    /// ```rust
2240    /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
2241    ///
2242    /// let double = |x: i32| x * 2;
2243    /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
2244    ///
2245    /// // to_string is moved here
2246    /// let composed = double.and_then(to_string);
2247    /// assert_eq!(composed.apply(21), "42");
2248    /// // to_string.apply(5); // Would not compile - moved
2249    /// ```
2250    ///
2251    /// ## Preserving original with clone
2252    ///
2253    /// ```rust
2254    /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
2255    ///
2256    /// let double = |x: i32| x * 2;
2257    /// let to_string = BoxTransformer::new(|x: i32| x.to_string());
2258    ///
2259    /// // Clone to preserve original
2260    /// let composed = double.and_then(to_string.clone());
2261    /// assert_eq!(composed.apply(21), "42");
2262    ///
2263    /// // Original still usable
2264    /// assert_eq!(to_string.apply(5), "5");
2265    /// ```
2266    fn and_then<S, F>(self, after: F) -> BoxTransformer<T, S>
2267    where
2268        S: 'static,
2269        F: Transformer<R, S> + 'static,
2270        T: 'static,
2271        R: 'static,
2272    {
2273        BoxTransformer::new(move |x: T| after.apply(self(x)))
2274    }
2275
2276    /// Reverse composition - applies before first, then self
2277    ///
2278    /// Creates a new transformer that applies the before transformer first,
2279    /// then applies this transformer to the result. Consumes self and returns
2280    /// a `BoxTransformer`.
2281    ///
2282    /// # Type Parameters
2283    ///
2284    /// * `S` - The input type of the before transformer
2285    /// * `F` - The type of the before transformer (must implement Transformer<S, T>)
2286    ///
2287    /// # Parameters
2288    ///
2289    /// * `before` - The transformer to apply before self. **Note: This parameter
2290    ///   is passed by value and will transfer ownership.** If you need to
2291    ///   preserve the original transformer, clone it first (if it implements
2292    ///   `Clone`). Can be:
2293    ///   - A closure: `|x: S| -> T`
2294    ///   - A function pointer: `fn(S) -> T`
2295    ///   - A `BoxTransformer<S, T>`
2296    ///   - An `RcTransformer<S, T>`
2297    ///   - An `ArcTransformer<S, T>`
2298    ///   - Any type implementing `Transformer<S, T>`
2299    ///
2300    /// # Returns
2301    ///
2302    /// A new `BoxTransformer<S, R>` representing the composition
2303    ///
2304    /// # Examples
2305    ///
2306    /// ## Direct value passing (ownership transfer)
2307    ///
2308    /// ```rust
2309    /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
2310    ///
2311    /// let double = |x: i32| x * 2;
2312    /// let add_one = BoxTransformer::new(|x: i32| x + 1);
2313    ///
2314    /// // add_one is moved here
2315    /// let composed = double.compose(add_one);
2316    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
2317    /// // add_one.apply(3); // Would not compile - moved
2318    /// ```
2319    ///
2320    /// ## Preserving original with clone
2321    ///
2322    /// ```rust
2323    /// use prism3_function::{Transformer, FnTransformerOps, BoxTransformer};
2324    ///
2325    /// let double = |x: i32| x * 2;
2326    /// let add_one = BoxTransformer::new(|x: i32| x + 1);
2327    ///
2328    /// // Clone to preserve original
2329    /// let composed = double.compose(add_one.clone());
2330    /// assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
2331    ///
2332    /// // Original still usable
2333    /// assert_eq!(add_one.apply(3), 4);
2334    /// ```
2335    fn compose<S, F>(self, before: F) -> BoxTransformer<S, R>
2336    where
2337        S: 'static,
2338        F: Transformer<S, T> + 'static,
2339        T: 'static,
2340        R: 'static,
2341    {
2342        BoxTransformer::new(move |x: S| self(before.apply(x)))
2343    }
2344
2345    /// Creates a conditional transformer
2346    ///
2347    /// Returns a transformer that only executes when a predicate is satisfied.
2348    /// You must call `or_else()` to provide an alternative transformer for when
2349    /// the condition is not satisfied.
2350    ///
2351    /// # Parameters
2352    ///
2353    /// * `predicate` - The condition to check. **Note: This parameter is passed
2354    ///   by value and will transfer ownership.** If you need to preserve the
2355    ///   original predicate, clone it first (if it implements `Clone`). Can be:
2356    ///   - A closure: `|x: &T| -> bool`
2357    ///   - A function pointer: `fn(&T) -> bool`
2358    ///   - A `BoxPredicate<T>`
2359    ///   - An `RcPredicate<T>`
2360    ///   - An `ArcPredicate<T>`
2361    ///   - Any type implementing `Predicate<T>`
2362    ///
2363    /// # Returns
2364    ///
2365    /// Returns `BoxConditionalTransformer<T, R>`
2366    ///
2367    /// # Examples
2368    ///
2369    /// ## Basic usage with or_else
2370    ///
2371    /// ```rust
2372    /// use prism3_function::{Transformer, FnTransformerOps};
2373    ///
2374    /// let double = |x: i32| x * 2;
2375    /// let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
2376    ///
2377    /// assert_eq!(conditional.apply(5), 10);
2378    /// assert_eq!(conditional.apply(-5), 5);
2379    /// ```
2380    ///
2381    /// ## Preserving predicate with clone
2382    ///
2383    /// ```rust
2384    /// use prism3_function::{Transformer, FnTransformerOps, BoxPredicate};
2385    ///
2386    /// let double = |x: i32| x * 2;
2387    /// let is_positive = BoxPredicate::new(|x: &i32| *x > 0);
2388    ///
2389    /// // Clone to preserve original predicate
2390    /// let conditional = double.when(is_positive.clone())
2391    ///     .or_else(|x: i32| -x);
2392    ///
2393    /// assert_eq!(conditional.apply(5), 10);
2394    ///
2395    /// // Original predicate still usable
2396    /// assert!(is_positive.test(&3));
2397    /// ```
2398    fn when<P>(self, predicate: P) -> BoxConditionalTransformer<T, R>
2399    where
2400        P: Predicate<T> + 'static,
2401        T: 'static,
2402        R: 'static,
2403    {
2404        BoxTransformer::new(self).when(predicate)
2405    }
2406}
2407
2408/// Blanket implementation of FnTransformerOps for all closures
2409///
2410/// Automatically implements `FnTransformerOps<T, R>` for any type that
2411/// implements `Fn(T) -> R`.
2412///
2413/// # Author
2414///
2415/// Hu Haixing
2416impl<T, R, F> FnTransformerOps<T, R> for F where F: Fn(T) -> R + 'static {}
2417
2418// ============================================================================
2419// UnaryOperator Trait - Marker trait for Transformer<T, T>
2420// ============================================================================
2421
2422/// UnaryOperator trait - marker trait for unary operators
2423///
2424/// A unary operator transforms a value of type `T` to another value of the
2425/// same type `T`. This trait extends `Transformer<T, T>` to provide semantic
2426/// clarity for same-type transformations. Equivalent to Java's `UnaryOperator<T>`
2427/// which extends `Function<T, T>`.
2428///
2429/// # Automatic Implementation
2430///
2431/// This trait is automatically implemented for all types that implement
2432/// `Transformer<T, T>`, so you don't need to implement it manually.
2433///
2434/// # Type Parameters
2435///
2436/// * `T` - The type of both input and output values
2437///
2438/// # Examples
2439///
2440/// ## Using in generic constraints
2441///
2442/// ```rust
2443/// use prism3_function::{UnaryOperator, Transformer};
2444///
2445/// fn apply_twice<T, O>(value: T, op: O) -> T
2446/// where
2447///     O: UnaryOperator<T>,
2448///     T: Clone,
2449/// {
2450///     let result = op.apply(value.clone());
2451///     op.apply(result)
2452/// }
2453///
2454/// let increment = |x: i32| x + 1;
2455/// assert_eq!(apply_twice(5, increment), 7); // (5 + 1) + 1
2456/// ```
2457///
2458/// ## With concrete types
2459///
2460/// ```rust
2461/// use prism3_function::{BoxUnaryOperator, UnaryOperator, Transformer};
2462///
2463/// fn create_incrementer() -> BoxUnaryOperator<i32> {
2464///     BoxUnaryOperator::new(|x| x + 1)
2465/// }
2466///
2467/// let op = create_incrementer();
2468/// assert_eq!(op.apply(41), 42);
2469/// ```
2470///
2471/// # Author
2472///
2473/// Hu Haixing
2474pub trait UnaryOperator<T>: Transformer<T, T> {}
2475
2476/// Blanket implementation of UnaryOperator for all Transformer<T, T>
2477///
2478/// This automatically implements `UnaryOperator<T>` for any type that
2479/// implements `Transformer<T, T>`.
2480///
2481/// # Author
2482///
2483/// Hu Haixing
2484impl<F, T> UnaryOperator<T> for F
2485where
2486    F: Transformer<T, T>,
2487    T: 'static,
2488{
2489    // empty
2490}
2491
2492// ============================================================================
2493// Type Aliases for UnaryOperator (Transformer<T, T>)
2494// ============================================================================
2495
2496/// Type alias for `BoxTransformer<T, T>`
2497///
2498/// Represents a unary operator that transforms a value of type `T` to another
2499/// value of the same type `T`, with single ownership semantics. Equivalent to
2500/// Java's `UnaryOperator<T>`.
2501///
2502/// # Examples
2503///
2504/// ```rust
2505/// use prism3_function::{BoxUnaryOperator, Transformer};
2506///
2507/// let increment: BoxUnaryOperator<i32> = BoxUnaryOperator::new(|x| x + 1);
2508/// assert_eq!(increment.apply(41), 42);
2509/// ```
2510///
2511/// # Author
2512///
2513/// Hu Haixing
2514pub type BoxUnaryOperator<T> = BoxTransformer<T, T>;
2515
2516/// Type alias for `ArcTransformer<T, T>`
2517///
2518/// Represents a thread-safe unary operator that transforms a value of type `T`
2519/// to another value of the same type `T`. Equivalent to Java's `UnaryOperator<T>`
2520/// with shared, thread-safe ownership.
2521///
2522/// # Examples
2523///
2524/// ```rust
2525/// use prism3_function::{ArcUnaryOperator, Transformer};
2526///
2527/// let double: ArcUnaryOperator<i32> = ArcUnaryOperator::new(|x| x * 2);
2528/// let double_clone = double.clone();
2529/// assert_eq!(double.apply(21), 42);
2530/// assert_eq!(double_clone.apply(21), 42);
2531/// ```
2532///
2533/// # Author
2534///
2535/// Hu Haixing
2536pub type ArcUnaryOperator<T> = ArcTransformer<T, T>;
2537
2538/// Type alias for `RcTransformer<T, T>`
2539///
2540/// Represents a single-threaded unary operator that transforms a value of type
2541/// `T` to another value of the same type `T`. Equivalent to Java's
2542/// `UnaryOperator<T>` with shared, single-threaded ownership.
2543///
2544/// # Examples
2545///
2546/// ```rust
2547/// use prism3_function::{RcUnaryOperator, Transformer};
2548///
2549/// let negate: RcUnaryOperator<i32> = RcUnaryOperator::new(|x: i32| -x);
2550/// let negate_clone = negate.clone();
2551/// assert_eq!(negate.apply(42), -42);
2552/// assert_eq!(negate_clone.apply(42), -42);
2553/// ```
2554///
2555/// # Author
2556///
2557/// Hu Haixing
2558pub type RcUnaryOperator<T> = RcTransformer<T, T>;