Skip to main content

qubit_function/suppliers/
stateful_supplier.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # StatefulSupplier Types
10//!
11//! Provides stateful supplier implementations that generate and return values
12//! without taking input while allowing mutable internal state.
13//!
14//! # Overview
15//!
16//! A **StatefulSupplier** is a functional abstraction equivalent to
17//! `FnMut() -> T`: it generates values without accepting input and may update
18//! its own internal state between calls. It is useful for counters,
19//! sequences, generators, and memoized computations.
20//!
21//! For stateless factories and constants that only need `Fn() -> T`, use
22//! [`Supplier`](crate::Supplier).
23//!
24//! # Core Design Principles
25//!
26//! 1. **Returns Ownership**: `StatefulSupplier` returns `T` (not `&T`) to
27//!    avoid lifetime issues
28//! 2. **Uses `&mut self`**: Typical scenarios (counters, generators)
29//!    require state modification
30//! 3. **Separate stateless API**: `Supplier` covers lock-free stateless
31//!    factories, while `StatefulSupplier` covers stateful generation
32//!
33//! # Three Implementations
34//!
35//! - **`BoxStatefulSupplier<T>`**: Single ownership using `Box<dyn FnMut()
36//!   -> T>`. Zero overhead, cannot be cloned. Best for one-time use
37//!   and builder patterns.
38//!
39//! - **`ArcStatefulSupplier<T>`**: Thread-safe shared ownership using
40//!   `Arc<Mutex<dyn FnMut() -> T + Send>>`. Can be cloned and sent
41//!   across threads. Higher overhead due to locking.
42//!
43//! - **`RcStatefulSupplier<T>`**: Single-threaded shared ownership using
44//!   `Rc<RefCell<dyn FnMut() -> T>>`. Can be cloned but not sent
45//!   across threads. Lower overhead than `ArcStatefulSupplier`.
46//!
47//! # Comparison with Other Functional Abstractions
48//!
49//! | Type      | Input | Output | self      | Modifies? | Use Case      |
50//! |-----------|-------|--------|-----------|-----------|---------------|
51//! | Supplier  | None  | `T`    | `&mut`    | Yes       | Factory       |
52//! | Consumer  | `&T`  | `()`   | `&mut`    | Yes       | Observer      |
53//! | Predicate | `&T`  | `bool` | `&self`   | No        | Filter        |
54//! | Function  | `&T`  | `R`    | `&self`   | No        | Transform     |
55//!
56//! # Examples
57//!
58//! ## Basic Counter
59//!
60//! ```rust
61//! use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
62//!
63//! let mut counter = 0;
64//! let mut supplier = BoxStatefulSupplier::new(move || {
65//!     counter += 1;
66//!     counter
67//! });
68//!
69//! assert_eq!(supplier.get(), 1);
70//! assert_eq!(supplier.get(), 2);
71//! assert_eq!(supplier.get(), 3);
72//! ```
73//!
74//! ## Method Chaining
75//!
76//! ```rust
77//! use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
78//!
79//! let mut pipeline = BoxStatefulSupplier::new(|| 10)
80//!     .map(|x| x * 2)
81//!     .map(|x| x + 5);
82//!
83//! assert_eq!(pipeline.get(), 25);
84//! ```
85//!
86//! ## Thread-safe Sharing
87//!
88//! ```rust
89//! use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
90//! use std::sync::{Arc, Mutex};
91//! use std::thread;
92//!
93//! let counter = Arc::new(Mutex::new(0));
94//! let counter_clone = Arc::clone(&counter);
95//!
96//! let supplier = ArcStatefulSupplier::new(move || {
97//!     let mut c = counter_clone.lock().unwrap();
98//!     *c += 1;
99//!     *c
100//! });
101//!
102//! let mut s1 = supplier.clone();
103//! let mut s2 = supplier.clone();
104//!
105//! let h1 = thread::spawn(move || s1.get());
106//! let h2 = thread::spawn(move || s2.get());
107//!
108//! let v1 = h1.join().unwrap();
109//! let v2 = h2.join().unwrap();
110//!
111//! assert!(v1 != v2);
112//! assert_eq!(*counter.lock().unwrap(), 2);
113//! ```
114//!
115//! # Author
116//!
117//! Haixing Hu
118use std::cell::RefCell;
119use std::rc::Rc;
120use std::sync::Arc;
121
122use parking_lot::Mutex;
123
124use crate::macros::{
125    impl_arc_conversions,
126    impl_box_conversions,
127    impl_closure_trait,
128    impl_rc_conversions,
129};
130use crate::predicates::predicate::Predicate;
131use crate::suppliers::{
132    macros::{
133        impl_box_supplier_methods,
134        impl_shared_supplier_methods,
135        impl_supplier_clone,
136        impl_supplier_common_methods,
137        impl_supplier_debug_display,
138    },
139    supplier_once::BoxSupplierOnce,
140};
141use crate::transformers::transformer::Transformer;
142
143mod box_stateful_supplier;
144pub use box_stateful_supplier::BoxStatefulSupplier;
145mod rc_stateful_supplier;
146pub use rc_stateful_supplier::RcStatefulSupplier;
147mod arc_stateful_supplier;
148pub use arc_stateful_supplier::ArcStatefulSupplier;
149mod fn_stateful_supplier_ops;
150pub use fn_stateful_supplier_ops::FnStatefulSupplierOps;
151
152// ==========================================================================
153// Supplier Trait
154// ==========================================================================
155
156/// Supplier trait: generates and returns values without input.
157///
158/// The core abstraction for value generation. Similar to Java's
159/// `Supplier<T>` interface, it produces values without taking any
160/// input parameters.
161///
162/// # Key Characteristics
163///
164/// - **No input parameters**: Pure value generation
165/// - **Mutable access**: Uses `&mut self` to allow state changes
166/// - **Returns ownership**: Returns `T` (not `&T`) to avoid lifetime
167///   issues
168/// - **Can modify state**: Commonly used for counters, sequences,
169///   and generators
170///
171/// # Automatically Implemented for Closures
172///
173/// All `FnMut() -> T` closures automatically implement this trait,
174/// enabling seamless integration with both raw closures and wrapped
175/// supplier types.
176///
177/// # Examples
178///
179/// ## Using with Generic Functions
180///
181/// ```rust
182/// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
183///
184/// fn call_twice<S: StatefulSupplier<i32>>(supplier: &mut S) -> (i32, i32) {
185///     (supplier.get(), supplier.get())
186/// }
187///
188/// let mut s = BoxStatefulSupplier::new(|| 42);
189/// assert_eq!(call_twice(&mut s), (42, 42));
190///
191/// let mut closure = || 100;
192/// assert_eq!(call_twice(&mut closure), (100, 100));
193/// ```
194///
195/// ## Stateful Supplier
196///
197/// ```rust
198/// use qubit_function::StatefulSupplier;
199///
200/// let mut counter = 0;
201/// let mut stateful = || {
202///     counter += 1;
203///     counter
204/// };
205///
206/// assert_eq!(stateful.get(), 1);
207/// assert_eq!(stateful.get(), 2);
208/// ```
209///
210/// # Author
211///
212/// Haixing Hu
213pub trait StatefulSupplier<T> {
214    /// Generates and returns the next value.
215    ///
216    /// Executes the underlying function and returns the generated
217    /// value. Uses `&mut self` because suppliers typically involve
218    /// state changes (counters, sequences, etc.).
219    ///
220    /// # Returns
221    ///
222    /// The generated value of type `T`
223    ///
224    /// # Examples
225    ///
226    /// ```rust
227    /// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
228    ///
229    /// let mut supplier = BoxStatefulSupplier::new(|| 42);
230    /// assert_eq!(supplier.get(), 42);
231    /// ```
232    fn get(&mut self) -> T;
233
234    /// Converts to `BoxStatefulSupplier`.
235    ///
236    /// This method has a default implementation that wraps the
237    /// supplier in a `BoxStatefulSupplier`. Custom implementations can
238    /// override this for more efficient conversions.
239    ///
240    /// # Returns
241    ///
242    /// A new `BoxStatefulSupplier<T>` instance
243    ///
244    /// # Examples
245    ///
246    /// ```rust
247    /// use qubit_function::{StatefulSupplier, SupplierOnce};
248    ///
249    /// let closure = || 42;
250    /// let mut boxed = StatefulSupplier::into_box(closure);
251    /// assert_eq!(boxed.get(), 42);
252    /// ```
253    fn into_box(mut self) -> BoxStatefulSupplier<T>
254    where
255        Self: Sized + 'static,
256    {
257        BoxStatefulSupplier::new(move || self.get())
258    }
259
260    /// Converts to `RcStatefulSupplier`.
261    ///
262    /// This method has a default implementation that wraps the
263    /// supplier in an `RcStatefulSupplier`. Custom implementations can
264    /// override this for more efficient conversions.
265    ///
266    /// # Returns
267    ///
268    /// A new `RcStatefulSupplier<T>` instance
269    ///
270    /// # Examples
271    ///
272    /// ```rust
273    /// use qubit_function::{StatefulSupplier, SupplierOnce};
274    ///
275    /// let closure = || 42;
276    /// let mut rc = closure.into_rc();
277    /// assert_eq!(rc.get(), 42);
278    /// ```
279    fn into_rc(mut self) -> RcStatefulSupplier<T>
280    where
281        Self: Sized + 'static,
282    {
283        RcStatefulSupplier::new(move || self.get())
284    }
285
286    /// Converts to `ArcStatefulSupplier`.
287    ///
288    /// This method has a default implementation that wraps the
289    /// supplier in an `ArcStatefulSupplier`. Custom implementations can
290    /// override this for more efficient conversions.
291    ///
292    /// # Returns
293    ///
294    /// A new `ArcStatefulSupplier<T>` instance
295    ///
296    /// # Examples
297    ///
298    /// ```rust
299    /// use qubit_function::{StatefulSupplier, SupplierOnce};
300    ///
301    /// let closure = || 42;
302    /// let mut arc = closure.into_arc();
303    /// assert_eq!(arc.get(), 42);
304    /// ```
305    fn into_arc(mut self) -> ArcStatefulSupplier<T>
306    where
307        Self: Sized + Send + 'static,
308    {
309        ArcStatefulSupplier::new(move || self.get())
310    }
311
312    /// Converts to a closure `FnMut() -> T`.
313    ///
314    /// This method wraps the supplier in a closure that calls the
315    /// `get()` method when invoked. This allows using suppliers
316    /// in contexts that expect `FnMut()` closures.
317    ///
318    /// # Returns
319    ///
320    /// A closure `impl FnMut() -> T`
321    ///
322    /// # Examples
323    ///
324    /// ```rust
325    /// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
326    ///
327    /// let supplier = BoxStatefulSupplier::new(|| 42);
328    /// let mut closure = supplier.into_fn();
329    /// assert_eq!(closure(), 42);
330    /// assert_eq!(closure(), 42);
331    /// ```
332    ///
333    /// ## Using with functions that expect FnMut
334    ///
335    /// ```rust
336    /// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
337    ///
338    /// fn call_fn_twice<F: FnMut() -> i32>(mut f: F) -> (i32, i32) {
339    ///     (f(), f())
340    /// }
341    ///
342    /// let supplier = BoxStatefulSupplier::new(|| 100);
343    /// let closure = supplier.into_fn();
344    /// assert_eq!(call_fn_twice(closure), (100, 100));
345    /// ```
346    fn into_fn(mut self) -> impl FnMut() -> T
347    where
348        Self: Sized + 'static,
349    {
350        move || self.get()
351    }
352
353    /// Converts to `BoxSupplierOnce`.
354    ///
355    /// This method has a default implementation that wraps the
356    /// supplier in a `BoxSupplierOnce`. Custom implementations
357    /// can override this method for optimization purposes.
358    ///
359    /// # Returns
360    ///
361    /// A new `BoxSupplierOnce<T>` instance
362    ///
363    /// # Examples
364    ///
365    /// ```rust
366    /// use qubit_function::{StatefulSupplier, SupplierOnce};
367    ///
368    /// let closure = || 42;
369    /// let once = closure.into_once();
370    /// assert_eq!(once.get(), 42);
371    /// ```
372    fn into_once(mut self) -> BoxSupplierOnce<T>
373    where
374        Self: Sized + 'static,
375    {
376        BoxSupplierOnce::new(move || self.get())
377    }
378
379    /// Creates a `BoxStatefulSupplier` from a cloned supplier.
380    ///
381    /// Uses `Clone` to obtain an owned copy and converts it into a
382    /// `BoxStatefulSupplier`. Implementations can override this for a more
383    /// efficient conversion.
384    fn to_box(&self) -> BoxStatefulSupplier<T>
385    where
386        Self: Clone + Sized + 'static,
387    {
388        self.clone().into_box()
389    }
390
391    /// Creates an `RcStatefulSupplier` from a cloned supplier.
392    ///
393    /// Uses `Clone` to obtain an owned copy and converts it into an
394    /// `RcStatefulSupplier`. Implementations can override it for better
395    /// performance.
396    fn to_rc(&self) -> RcStatefulSupplier<T>
397    where
398        Self: Clone + Sized + 'static,
399    {
400        self.clone().into_rc()
401    }
402
403    /// Creates an `ArcStatefulSupplier` from a cloned supplier.
404    ///
405    /// Requires the supplier and produced values to be `Send` so the
406    /// resulting supplier can be shared across threads.
407    fn to_arc(&self) -> ArcStatefulSupplier<T>
408    where
409        Self: Clone + Sized + Send + 'static,
410    {
411        self.clone().into_arc()
412    }
413
414    /// Creates a closure from a cloned supplier.
415    ///
416    /// The default implementation clones `self` and consumes the clone
417    /// to produce a closure. Concrete suppliers can override it to
418    /// avoid the additional clone.
419    fn to_fn(&self) -> impl FnMut() -> T
420    where
421        Self: Clone + Sized + 'static,
422    {
423        self.clone().into_fn()
424    }
425
426    /// Creates a `BoxSupplierOnce` from a cloned supplier
427    ///
428    /// Uses `Clone` to obtain an owned copy and converts it into a
429    /// `BoxSupplierOnce`. Requires `Self: Clone`. Custom implementations
430    /// can override this for better performance.
431    fn to_once(&self) -> BoxSupplierOnce<T>
432    where
433        Self: Clone + Sized + 'static,
434    {
435        self.clone().into_once()
436    }
437}