qubit_function/transformers/stateful_transformer.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # StatefulTransformer Types
10//!
11//! Provides Rust implementations of stateful transformer traits for stateful value
12//! transformation. StatefulTransformers consume input values (taking ownership) and
13//! produce output values while allowing internal state modification. This is
14//! analogous to `FnMut(T) -> R` in Rust's standard library.
15//!
16//! This module provides the `StatefulTransformer<T, R>` trait and three implementations:
17//!
18//! - [`BoxStatefulTransformer`]: Single ownership, not cloneable
19//! - [`ArcStatefulTransformer`]: Thread-safe shared ownership, cloneable
20//! - [`RcStatefulTransformer`]: Single-threaded shared ownership, cloneable
21//!
22//! # Author
23//!
24//! Haixing Hu
25use std::cell::RefCell;
26use std::rc::Rc;
27use std::sync::Arc;
28
29use parking_lot::Mutex;
30
31use crate::macros::{
32 impl_arc_conversions,
33 impl_box_conversions,
34 impl_closure_trait,
35 impl_rc_conversions,
36};
37use crate::predicates::predicate::{
38 ArcPredicate,
39 BoxPredicate,
40 Predicate,
41 RcPredicate,
42};
43use crate::transformers::{
44 macros::{
45 impl_box_conditional_transformer,
46 impl_box_transformer_methods,
47 impl_conditional_transformer_clone,
48 impl_conditional_transformer_debug_display,
49 impl_shared_conditional_transformer,
50 impl_shared_transformer_methods,
51 impl_transformer_clone,
52 impl_transformer_common_methods,
53 impl_transformer_constant_method,
54 impl_transformer_debug_display,
55 },
56 transformer_once::BoxTransformerOnce,
57};
58
59mod box_stateful_transformer;
60pub use box_stateful_transformer::BoxStatefulTransformer;
61mod rc_stateful_transformer;
62pub use rc_stateful_transformer::RcStatefulTransformer;
63mod arc_stateful_transformer;
64pub use arc_stateful_transformer::ArcStatefulTransformer;
65mod fn_stateful_transformer_ops;
66pub use fn_stateful_transformer_ops::FnStatefulTransformerOps;
67mod box_conditional_stateful_transformer;
68pub use box_conditional_stateful_transformer::BoxConditionalStatefulTransformer;
69mod rc_conditional_stateful_transformer;
70pub use rc_conditional_stateful_transformer::RcConditionalStatefulTransformer;
71mod arc_conditional_stateful_transformer;
72pub use arc_conditional_stateful_transformer::ArcConditionalStatefulTransformer;
73
74// ============================================================================
75// Core Trait
76// ============================================================================
77
78/// StatefulTransformer trait - transforms values from type T to type R with state
79///
80/// Defines the behavior of a stateful transformation: converting a value
81/// of type `T` to a value of type `R` by consuming the input while
82/// allowing modification of internal state. This is analogous to
83/// `FnMut(T) -> R` in Rust's standard library.
84///
85/// # Type Parameters
86///
87/// * `T` - The type of the input value (consumed)
88/// * `R` - The type of the output value
89///
90/// # Author
91///
92/// Haixing Hu
93pub trait StatefulTransformer<T, R> {
94 /// Applies the transformation to the input value to produce an output value
95 ///
96 /// # Parameters
97 ///
98 /// * `input` - The input value to transform (consumed)
99 ///
100 /// # Returns
101 ///
102 /// The transformed output value
103 fn apply(&mut self, input: T) -> R;
104
105 /// Converts to BoxStatefulTransformer
106 ///
107 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
108 /// after calling this method.
109 ///
110 /// # Returns
111 ///
112 /// Returns `BoxStatefulTransformer<T, R>`
113 ///
114 /// # Default Implementation
115 ///
116 /// The default implementation wraps `self` in a `BoxStatefulTransformer` by
117 /// creating a new closure that calls `self.apply()`. This is a lightweight
118 /// adapter, but it is not strictly zero-cost.
119 ///
120 /// # Examples
121 ///
122 /// ```rust
123 /// use qubit_function::{StatefulTransformer, BoxStatefulTransformer};
124 ///
125 /// struct CustomTransformer {
126 /// multiplier: i32,
127 /// }
128 ///
129 /// impl StatefulTransformer<i32, i32> for CustomTransformer {
130 /// fn apply(&mut self, input: i32) -> i32 {
131 /// self.multiplier += 1;
132 /// input * self.multiplier
133 /// }
134 /// }
135 ///
136 /// let transformer = CustomTransformer { multiplier: 0 };
137 /// let mut boxed = transformer.into_box();
138 /// assert_eq!(boxed.apply(10), 10); // 10 * 1
139 /// assert_eq!(boxed.apply(10), 20); // 10 * 2
140 /// ```
141 fn into_box(self) -> BoxStatefulTransformer<T, R>
142 where
143 Self: Sized + 'static,
144 {
145 let mut transformer = self;
146 BoxStatefulTransformer::new(move |t| transformer.apply(t))
147 }
148
149 /// Converts to RcStatefulTransformer
150 ///
151 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
152 /// after calling this method.
153 ///
154 /// # Returns
155 ///
156 /// Returns `RcStatefulTransformer<T, R>`
157 ///
158 /// # Default Implementation
159 ///
160 /// The default implementation first converts to `BoxStatefulTransformer` using
161 /// `into_box()`, then wraps it in `RcStatefulTransformer`. Specific implementations
162 /// may override this for better efficiency.
163 ///
164 /// # Examples
165 ///
166 /// ```rust
167 /// use qubit_function::{StatefulTransformer, RcStatefulTransformer};
168 ///
169 /// struct CustomTransformer {
170 /// multiplier: i32,
171 /// }
172 ///
173 /// impl StatefulTransformer<i32, i32> for CustomTransformer {
174 /// fn apply(&mut self, input: i32) -> i32 {
175 /// self.multiplier += 1;
176 /// input * self.multiplier
177 /// }
178 /// }
179 ///
180 /// let transformer = CustomTransformer { multiplier: 0 };
181 /// let mut rc_transformer = transformer.into_rc();
182 /// assert_eq!(rc_transformer.apply(10), 10); // 10 * 1
183 /// assert_eq!(rc_transformer.apply(10), 20); // 10 * 2
184 /// ```
185 fn into_rc(self) -> RcStatefulTransformer<T, R>
186 where
187 Self: Sized + 'static,
188 {
189 let mut transformer = self;
190 RcStatefulTransformer::new(move |t| transformer.apply(t))
191 }
192
193 /// Converts to ArcStatefulTransformer
194 ///
195 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
196 /// after calling this method.
197 ///
198 /// # Returns
199 ///
200 /// Returns `ArcStatefulTransformer<T, R>`
201 ///
202 /// # Default Implementation
203 ///
204 /// The default implementation wraps `self` in an `ArcStatefulTransformer` by creating
205 /// a new closure that calls `self.apply()`. Note that this requires `self`
206 /// to implement `Send` due to Arc's thread-safety requirements.
207 ///
208 /// # Examples
209 ///
210 /// ```rust
211 /// use qubit_function::{StatefulTransformer, ArcStatefulTransformer};
212 ///
213 /// struct CustomTransformer {
214 /// multiplier: i32,
215 /// }
216 ///
217 /// impl StatefulTransformer<i32, i32> for CustomTransformer {
218 /// fn apply(&mut self, input: i32) -> i32 {
219 /// self.multiplier += 1;
220 /// input * self.multiplier
221 /// }
222 /// }
223 ///
224 /// let transformer = CustomTransformer { multiplier: 0 };
225 /// let mut arc_transformer = transformer.into_arc();
226 /// assert_eq!(arc_transformer.apply(10), 10); // 10 * 1
227 /// assert_eq!(arc_transformer.apply(10), 20); // 10 * 2
228 /// ```
229 fn into_arc(self) -> ArcStatefulTransformer<T, R>
230 where
231 Self: Sized + Send + 'static,
232 {
233 let mut transformer = self;
234 ArcStatefulTransformer::new(move |t| transformer.apply(t))
235 }
236
237 /// Converts to a closure implementing `FnMut(T) -> R`
238 ///
239 /// **⚠️ Consumes `self`**: The original transformer becomes unavailable
240 /// after calling this method.
241 ///
242 /// # Returns
243 ///
244 /// Returns an implementation of `FnMut(T) -> R`
245 ///
246 /// # Default Implementation
247 ///
248 /// The default implementation creates a new closure that calls `self.apply()`.
249 /// Specific implementations may override this for better efficiency.
250 ///
251 /// # Examples
252 ///
253 /// ```rust
254 /// use qubit_function::{StatefulTransformer, BoxStatefulTransformer};
255 ///
256 /// let transformer = BoxStatefulTransformer::new(|x: i32| x * 2);
257 /// let mut closure = transformer.into_fn();
258 /// assert_eq!(closure(10), 20);
259 /// assert_eq!(closure(15), 30);
260 /// ```
261 fn into_fn(self) -> impl FnMut(T) -> R
262 where
263 Self: Sized + 'static,
264 {
265 let mut transformer = self;
266 move |t| transformer.apply(t)
267 }
268
269 /// Converts transformer to a mutable closure (`FnMut`) with an explicit
270 /// method name.
271 ///
272 /// This is a naming alias of [`StatefulTransformer::into_fn`] to make the
273 /// mutability of the returned closure explicit.
274 fn into_mut_fn(self) -> impl FnMut(T) -> R
275 where
276 Self: Sized + 'static,
277 {
278 self.into_fn()
279 }
280
281 /// Converts to `BoxTransformerOnce`.
282 ///
283 /// This method has a default implementation that wraps the
284 /// transformer in a `BoxTransformerOnce`. Custom implementations
285 /// can override this method for optimization purposes.
286 ///
287 /// # Returns
288 ///
289 /// A new `BoxTransformerOnce<T, R>` instance
290 ///
291 /// # Examples
292 ///
293 /// ```rust
294 /// use qubit_function::{StatefulTransformer, TransformerOnce};
295 ///
296 /// let closure = |x: i32| x * 2;
297 /// let once = closure.into_once();
298 /// assert_eq!(once.apply(5), 10);
299 /// ```
300 fn into_once(self) -> BoxTransformerOnce<T, R>
301 where
302 Self: Sized + 'static,
303 {
304 let mut transformer = self;
305 BoxTransformerOnce::new(move |t| transformer.apply(t))
306 }
307
308 /// Non-consuming conversion to `BoxStatefulTransformer`.
309 ///
310 /// Default implementation requires `Self: Clone` and wraps a cloned
311 /// instance in a `RefCell` so the returned transformer can mutate state
312 /// across calls.
313 fn to_box(&self) -> BoxStatefulTransformer<T, R>
314 where
315 Self: Sized + Clone + 'static,
316 {
317 self.clone().into_box()
318 }
319
320 /// Non-consuming conversion to `RcStatefulTransformer`.
321 ///
322 /// Default implementation clones `self` into an `Rc<RefCell<_>>` so the
323 /// resulting transformer can be shared within a single thread.
324 fn to_rc(&self) -> RcStatefulTransformer<T, R>
325 where
326 Self: Sized + Clone + 'static,
327 {
328 self.clone().into_rc()
329 }
330
331 /// Non-consuming conversion to `ArcStatefulTransformer` (thread-safe).
332 ///
333 /// Default implementation requires `Self: Clone + Send + Sync` and wraps
334 /// the cloned instance in `Arc<Mutex<_>>` so it can be used across
335 /// threads.
336 fn to_arc(&self) -> ArcStatefulTransformer<T, R>
337 where
338 Self: Sized + Clone + Send + 'static,
339 {
340 self.clone().into_arc()
341 }
342
343 /// Non-consuming conversion to a closure (`FnMut(T) -> R`).
344 ///
345 /// Default implementation clones `self` into a `RefCell` and returns a
346 /// closure that calls `apply` on the interior mutable value.
347 fn to_fn(&self) -> impl FnMut(T) -> R
348 where
349 Self: Sized + Clone + 'static,
350 {
351 self.clone().into_fn()
352 }
353
354 /// Non-consuming conversion to a mutable closure (`FnMut`) with an explicit
355 /// method name.
356 ///
357 /// This is a naming alias of [`StatefulTransformer::to_fn`] and preserves
358 /// the same clone-based behavior.
359 fn to_mut_fn(&self) -> impl FnMut(T) -> R
360 where
361 Self: Sized + Clone + 'static,
362 {
363 self.to_fn()
364 }
365
366 /// Creates a `BoxTransformerOnce` from a cloned transformer
367 ///
368 /// Uses `Clone` to obtain an owned copy and converts it into a
369 /// `BoxTransformerOnce`. Requires `Self: Clone`. Custom implementations
370 /// can override this for better performance.
371 fn to_once(&self) -> BoxTransformerOnce<T, R>
372 where
373 Self: Sized + Clone + 'static,
374 {
375 self.clone().into_once()
376 }
377}