Skip to main content

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