Skip to main content

qubit_function/functions/
stateful_function.rs

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