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