Skip to main content

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
57mod box_transformer;
58pub use box_transformer::BoxTransformer;
59mod rc_transformer;
60pub use rc_transformer::RcTransformer;
61mod arc_transformer;
62pub use arc_transformer::ArcTransformer;
63mod fn_transformer_ops;
64pub use fn_transformer_ops::FnTransformerOps;
65mod unary_operator;
66pub use unary_operator::UnaryOperator;
67mod box_unary_operator;
68pub use box_unary_operator::BoxUnaryOperator;
69mod arc_unary_operator;
70pub use arc_unary_operator::ArcUnaryOperator;
71mod rc_unary_operator;
72pub use rc_unary_operator::RcUnaryOperator;
73mod box_conditional_transformer;
74pub use box_conditional_transformer::BoxConditionalTransformer;
75mod rc_conditional_transformer;
76pub use rc_conditional_transformer::RcConditionalTransformer;
77mod arc_conditional_transformer;
78pub use arc_conditional_transformer::ArcConditionalTransformer;
79
80// ============================================================================
81// Core Trait
82// ============================================================================
83
84/// Transformer trait - transforms values from type T to type R
85///
86/// Defines the behavior of a transformation: converting a value of type `T`
87/// to a value of type `R` by consuming the input. This is analogous to
88/// `Fn(T) -> R` in Rust's standard library.
89///
90/// # Type Parameters
91///
92/// * `T` - The type of the input value (consumed)
93/// * `R` - The type of the output value
94///
95/// # Author
96///
97/// Haixing Hu
98pub trait Transformer<T, R> {
99    /// Applies the transformation to the input value to produce an output value
100    ///
101    /// # Parameters
102    ///
103    /// * `input` - The input value to transform (consumed)
104    ///
105    /// # Returns
106    ///
107    /// The transformed output value
108    fn apply(&self, input: T) -> R;
109
110    /// Converts to BoxTransformer
111    ///
112    /// **⚠️ Consumes `self`**: The original transformer becomes
113    /// unavailable after calling this method.
114    ///
115    /// # Default Implementation
116    ///
117    /// The default implementation wraps `self` in a `Box` and creates a
118    /// `BoxTransformer`. Types can override this method to provide more
119    /// efficient conversions.
120    ///
121    /// # Returns
122    ///
123    /// Returns `BoxTransformer<T, R>`
124    fn into_box(self) -> BoxTransformer<T, R>
125    where
126        Self: Sized + 'static,
127    {
128        BoxTransformer::new(move |x| self.apply(x))
129    }
130
131    /// Converts to RcTransformer
132    ///
133    /// **⚠️ Consumes `self`**: The original transformer becomes
134    /// unavailable after calling this method.
135    ///
136    /// # Default Implementation
137    ///
138    /// The default implementation wraps `self` in an `Rc` and creates an
139    /// `RcTransformer`. Types can override this method to provide more
140    /// efficient conversions.
141    ///
142    /// # Returns
143    ///
144    /// Returns `RcTransformer<T, R>`
145    fn into_rc(self) -> RcTransformer<T, R>
146    where
147        Self: Sized + 'static,
148    {
149        RcTransformer::new(move |x| self.apply(x))
150    }
151
152    /// Converts to ArcTransformer
153    ///
154    /// **⚠️ Consumes `self`**: The original transformer becomes
155    /// unavailable after calling this method.
156    ///
157    /// # Default Implementation
158    ///
159    /// The default implementation wraps `self` in an `Arc` and creates
160    /// an `ArcTransformer`. Types can override this method to provide
161    /// more efficient conversions.
162    ///
163    /// # Returns
164    ///
165    /// Returns `ArcTransformer<T, R>`
166    fn into_arc(self) -> ArcTransformer<T, R>
167    where
168        Self: Sized + Send + Sync + 'static,
169    {
170        ArcTransformer::new(move |x| self.apply(x))
171    }
172
173    /// Converts transformer to a closure
174    ///
175    /// **⚠️ Consumes `self`**: The original transformer becomes
176    /// unavailable after calling this method.
177    ///
178    /// # Default Implementation
179    ///
180    /// The default implementation creates a closure that captures `self`
181    /// and calls its `transform` method. Types can override this method
182    /// to provide more efficient conversions.
183    ///
184    /// # Returns
185    ///
186    /// Returns a closure that implements `Fn(T) -> R`
187    fn into_fn(self) -> impl Fn(T) -> R
188    where
189        Self: Sized + 'static,
190    {
191        move |t: T| self.apply(t)
192    }
193
194    /// Converts to `BoxTransformerOnce`.
195    ///
196    /// This method has a default implementation that wraps the
197    /// transformer in a `BoxTransformerOnce`. Custom implementations
198    /// can override this method for optimization purposes.
199    ///
200    /// # Returns
201    ///
202    /// A new `BoxTransformerOnce<T, R>` instance
203    ///
204    /// # Examples
205    ///
206    /// ```rust
207    /// use qubit_function::{Transformer, TransformerOnce};
208    ///
209    /// let closure = |x: i32| x * 2;
210    /// let once = closure.into_once();
211    /// assert_eq!(once.apply(5), 10);
212    /// ```
213    fn into_once(self) -> BoxTransformerOnce<T, R>
214    where
215        Self: Sized + 'static,
216    {
217        BoxTransformerOnce::new(move |t| self.apply(t))
218    }
219
220    /// Converts to BoxTransformer without consuming self
221    ///
222    /// **📌 Borrows `&self`**: The original transformer remains usable
223    /// after calling this method.
224    ///
225    /// # Default Implementation
226    ///
227    /// The default implementation creates a new `BoxTransformer` that
228    /// captures a reference-counted clone. Types implementing `Clone`
229    /// can override this method to provide more efficient conversions.
230    ///
231    /// # Returns
232    ///
233    /// Returns `BoxTransformer<T, R>`
234    ///
235    /// # Examples
236    ///
237    /// ```rust
238    /// use qubit_function::{ArcTransformer, Transformer};
239    ///
240    /// let double = ArcTransformer::new(|x: i32| x * 2);
241    /// let boxed = double.to_box();
242    ///
243    /// // Original transformer still usable
244    /// assert_eq!(double.apply(21), 42);
245    /// assert_eq!(boxed.apply(21), 42);
246    /// ```
247    fn to_box(&self) -> BoxTransformer<T, R>
248    where
249        Self: Clone + 'static,
250    {
251        self.clone().into_box()
252    }
253
254    /// Converts to RcTransformer without consuming self
255    ///
256    /// **📌 Borrows `&self`**: The original transformer remains usable
257    /// after calling this method.
258    ///
259    /// # Default Implementation
260    ///
261    /// The default implementation creates a new `RcTransformer` that
262    /// captures a reference-counted clone. Types implementing `Clone`
263    /// can override this method to provide more efficient conversions.
264    ///
265    /// # Returns
266    ///
267    /// Returns `RcTransformer<T, R>`
268    ///
269    /// # Examples
270    ///
271    /// ```rust
272    /// use qubit_function::{ArcTransformer, Transformer};
273    ///
274    /// let double = ArcTransformer::new(|x: i32| x * 2);
275    /// let rc = double.to_rc();
276    ///
277    /// // Original transformer still usable
278    /// assert_eq!(double.apply(21), 42);
279    /// assert_eq!(rc.apply(21), 42);
280    /// ```
281    fn to_rc(&self) -> RcTransformer<T, R>
282    where
283        Self: Clone + 'static,
284    {
285        self.clone().into_rc()
286    }
287
288    /// Converts to ArcTransformer without consuming self
289    ///
290    /// **📌 Borrows `&self`**: The original transformer remains usable
291    /// after calling this method.
292    ///
293    /// # Default Implementation
294    ///
295    /// The default implementation creates a new `ArcTransformer` that
296    /// captures a reference-counted clone. Types implementing `Clone`
297    /// can override this method to provide more efficient conversions.
298    ///
299    /// # Returns
300    ///
301    /// Returns `ArcTransformer<T, R>`
302    ///
303    /// # Examples
304    ///
305    /// ```rust
306    /// use qubit_function::{ArcTransformer, Transformer};
307    ///
308    /// let double = ArcTransformer::new(|x: i32| x * 2);
309    /// let arc = double.to_arc();
310    ///
311    /// // Original transformer still usable
312    /// assert_eq!(double.apply(21), 42);
313    /// assert_eq!(arc.apply(21), 42);
314    /// ```
315    fn to_arc(&self) -> ArcTransformer<T, R>
316    where
317        Self: Clone + Send + Sync + 'static,
318    {
319        self.clone().into_arc()
320    }
321
322    /// Converts transformer to a closure without consuming self
323    ///
324    /// **📌 Borrows `&self`**: The original transformer remains usable
325    /// after calling this method.
326    ///
327    /// # Default Implementation
328    ///
329    /// The default implementation creates a closure that captures a
330    /// clone of `self` and calls its `transform` method. Types can
331    /// override this method to provide more efficient conversions.
332    ///
333    /// # Returns
334    ///
335    /// Returns a closure that implements `Fn(T) -> R`
336    ///
337    /// # Examples
338    ///
339    /// ```rust
340    /// use qubit_function::{ArcTransformer, Transformer};
341    ///
342    /// let double = ArcTransformer::new(|x: i32| x * 2);
343    /// let closure = double.to_fn();
344    ///
345    /// // Original transformer still usable
346    /// assert_eq!(double.apply(21), 42);
347    /// assert_eq!(closure(21), 42);
348    /// ```
349    fn to_fn(&self) -> impl Fn(T) -> R
350    where
351        Self: Clone + 'static,
352    {
353        self.clone().into_fn()
354    }
355
356    /// Converts to `BoxTransformerOnce` without consuming self
357    ///
358    /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
359    /// Clones the current transformer and converts the clone to a one-time transformer.
360    ///
361    /// # Returns
362    ///
363    /// Returns a `BoxTransformerOnce<T, R>`
364    fn to_once(&self) -> BoxTransformerOnce<T, R>
365    where
366        Self: Clone + 'static,
367    {
368        self.clone().into_once()
369    }
370}