Skip to main content

qubit_function/suppliers/
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//! # Supplier Types
11//!
12//! Provides stateless supplier implementations that generate and
13//! return values without taking input.
14//!
15//! # Overview
16//!
17//! A **Supplier** is a functional abstraction equivalent to
18//! `Fn() -> T`: it generates values without accepting input or
19//! requiring mutable access to itself. The `get` method uses `&self`,
20//! enabling use in read-only contexts and lock-free concurrent access
21//! for the `Arc` implementation.
22//!
23//! For generators that need mutable internal state, such as counters
24//! or sequences, use [`StatefulSupplier`](crate::StatefulSupplier).
25//!
26//! # Key Differences from StatefulSupplier
27//!
28//! | Aspect | `Supplier<T>` | `StatefulSupplier<T>` |
29//! |--------|---------------|----------------------|
30//! | self signature | `&self` | `&mut self` |
31//! | Closure type | `Fn() -> T` | `FnMut() -> T` |
32//! | Can modify internal state | No | Yes |
33//! | Arc implementation | `Arc<dyn Fn() -> T + Send + Sync>` | `Arc<Mutex<dyn FnMut() -> T + Send>>` |
34//! | Use cases | Factory, constant, high concurrency | Counter, sequence, generator |
35//!
36//! # Three Implementations
37//!
38//! - **`BoxSupplier<T>`**: Single ownership using `Box<dyn
39//!   Fn() -> T>`. Zero overhead, cannot be cloned. Best for
40//!   one-time use in read-only contexts.
41//!
42//! - **`ArcSupplier<T>`**: Thread-safe shared ownership
43//!   using `Arc<dyn Fn() -> T + Send + Sync>`. **Lock-free** - no
44//!   Mutex needed! Can be cloned and sent across threads with
45//!   excellent performance.
46//!
47//! - **`RcSupplier<T>`**: Single-threaded shared ownership
48//!   using `Rc<dyn Fn() -> T>`. Can be cloned but not sent across
49//!   threads. Lightweight alternative to `ArcSupplier`.
50//!
51//! # Use Cases
52//!
53//! ## 1. Calling in `&self` Methods
54//!
55//! ```rust
56//! use qubit_function::{ArcSupplier, Supplier};
57//!
58//! struct Executor<E> {
59//!     error_supplier: ArcSupplier<E>,
60//! }
61//!
62//! impl<E> Executor<E> {
63//!     fn execute(&self) -> Result<(), E> {
64//!         // Can call directly in &self method!
65//!         Err(self.error_supplier.get())
66//!     }
67//! }
68//! ```
69//!
70//! ## 2. High-Concurrency Lock-Free Access
71//!
72//! ```rust
73//! use qubit_function::{ArcSupplier, Supplier};
74//! use std::thread;
75//!
76//! let factory = ArcSupplier::new(|| {
77//!     String::from("Hello, World!")
78//! });
79//!
80//! let handles: Vec<_> = (0..10)
81//!     .map(|_| {
82//!         let f = factory.clone();
83//!         thread::spawn(move || f.get()) // Lock-free!
84//!     })
85//!     .collect();
86//!
87//! for h in handles {
88//!     assert_eq!(h.join().unwrap(), "Hello, World!");
89//! }
90//! ```
91//!
92//! ## 3. Fixed Factories
93//!
94//! ```rust
95//! use qubit_function::{BoxSupplier, Supplier};
96//!
97//! #[derive(Clone)]
98//! struct Config {
99//!     timeout: u64,
100//! }
101//!
102//! let config_factory = BoxSupplier::new(|| Config {
103//!     timeout: 30,
104//! });
105//!
106//! assert_eq!(config_factory.get().timeout, 30);
107//! assert_eq!(config_factory.get().timeout, 30);
108//! ```
109//!
110//! # Performance Comparison
111//!
112//! For stateless scenarios in multi-threaded environments:
113//!
114//! - `ArcStatefulSupplier<T>`: Requires `Mutex`, lock contention on
115//!   every `get()` call.
116//! - `ArcSupplier<T>`: Lock-free, can call `get()`
117//!   concurrently without contention.
118//!
119//! Benchmark results show `ArcSupplier` can be **10x
120//! faster** than `ArcStatefulSupplier` in high-concurrency stateless
121//! scenarios.
122//!
123
124use std::rc::Rc;
125use std::sync::Arc;
126
127use crate::BoxSupplierOnce;
128use crate::macros::{
129    impl_arc_conversions,
130    impl_box_conversions,
131    impl_closure_trait,
132    impl_rc_conversions,
133};
134use crate::predicates::predicate::Predicate;
135use crate::suppliers::macros::{
136    impl_box_supplier_methods,
137    impl_shared_supplier_methods,
138    impl_supplier_clone,
139    impl_supplier_common_methods,
140    impl_supplier_debug_display,
141};
142use crate::transformers::transformer::Transformer;
143
144mod box_supplier;
145pub use box_supplier::BoxSupplier;
146mod arc_supplier;
147pub use arc_supplier::ArcSupplier;
148mod rc_supplier;
149pub use rc_supplier::RcSupplier;
150
151// ======================================================================
152// Supplier Trait
153// ======================================================================
154
155/// Stateless supplier trait: generates values without modifying
156/// state.
157///
158/// The core abstraction for stateless value generation. Unlike
159/// `Supplier<T>`, it uses `&self` instead of `&mut self`, enabling
160/// usage in read-only contexts and lock-free concurrent access.
161///
162/// # Key Characteristics
163///
164/// - **No input parameters**: Pure value generation
165/// - **Read-only access**: Uses `&self`, doesn't modify state
166/// - **Returns ownership**: Returns `T` (not `&T`) to avoid
167///   lifetime issues
168/// - **Lock-free concurrency**: `Arc` implementation doesn't need
169///   `Mutex`
170///
171/// # Automatically Implemented for Closures
172///
173/// All `Fn() -> T` closures automatically implement this trait,
174/// enabling seamless integration with both raw closures and
175/// wrapped supplier types.
176///
177/// # Examples
178///
179/// ## Using with Generic Functions
180///
181/// ```rust
182/// use qubit_function::{Supplier, BoxSupplier};
183///
184/// fn call_twice<S: Supplier<i32>>(supplier: &S)
185///     -> (i32, i32)
186/// {
187///     (supplier.get(), supplier.get())
188/// }
189///
190/// let s = BoxSupplier::new(|| 42);
191/// assert_eq!(call_twice(&s), (42, 42));
192///
193/// let closure = || 100;
194/// assert_eq!(call_twice(&closure), (100, 100));
195/// ```
196///
197/// ## Stateless Factory
198///
199/// ```rust
200/// use qubit_function::{Supplier, SupplierOnce};
201///
202/// struct User {
203///     name: String,
204/// }
205///
206/// impl User {
207///     fn new() -> Self {
208///         User {
209///             name: String::from("Default"),
210///         }
211///     }
212/// }
213///
214/// let factory = || User::new();
215/// let user1 = factory.get();
216/// let user2 = factory.get();
217/// // Each call creates a new User instance
218/// ```
219///
220pub trait Supplier<T> {
221    /// Generates and returns a value.
222    ///
223    /// Executes the underlying function and returns the generated
224    /// value. Uses `&self` because the supplier doesn't modify its
225    /// own state.
226    ///
227    /// # Returns
228    ///
229    /// The generated value of type `T`
230    ///
231    /// # Examples
232    ///
233    /// ```rust
234    /// use qubit_function::{Supplier, BoxSupplier};
235    ///
236    /// let supplier = BoxSupplier::new(|| 42);
237    /// assert_eq!(supplier.get(), 42);
238    /// assert_eq!(supplier.get(), 42);
239    /// ```
240    fn get(&self) -> T;
241
242    /// Converts to `BoxSupplier`.
243    ///
244    /// This method has a default implementation that wraps the
245    /// supplier in a `BoxSupplier`. Custom implementations
246    /// can override this method for optimization purposes.
247    ///
248    /// # Returns
249    ///
250    /// A new `BoxSupplier<T>` instance
251    ///
252    /// # Examples
253    ///
254    /// ```rust
255    /// use qubit_function::{Supplier, SupplierOnce};
256    ///
257    /// let closure = || 42;
258    /// let boxed = Supplier::into_box(closure);
259    /// assert_eq!(boxed.get(), 42);
260    /// ```
261    fn into_box(self) -> BoxSupplier<T>
262    where
263        Self: Sized + 'static,
264    {
265        BoxSupplier::new(move || self.get())
266    }
267
268    /// Converts to `RcSupplier`.
269    ///
270    /// This method has a default implementation that wraps the
271    /// supplier in an `RcSupplier`. Custom implementations
272    /// can override this method for optimization purposes.
273    ///
274    /// # Returns
275    ///
276    /// A new `RcSupplier<T>` instance
277    ///
278    /// # Examples
279    ///
280    /// ```rust
281    /// use qubit_function::{Supplier, SupplierOnce};
282    ///
283    /// let closure = || 42;
284    /// let rc = closure.into_rc();
285    /// assert_eq!(rc.get(), 42);
286    /// ```
287    fn into_rc(self) -> RcSupplier<T>
288    where
289        Self: Sized + 'static,
290    {
291        RcSupplier::new(move || self.get())
292    }
293
294    /// Converts to `ArcSupplier`.
295    ///
296    /// This method has a default implementation that wraps the
297    /// supplier in an `ArcSupplier`. Custom implementations
298    /// can override this method for optimization purposes.
299    ///
300    /// # Returns
301    ///
302    /// A new `ArcSupplier<T>` instance
303    ///
304    /// # Examples
305    ///
306    /// ```rust
307    /// use qubit_function::{Supplier, SupplierOnce};
308    ///
309    /// let closure = || 42;
310    /// let arc = closure.into_arc();
311    /// assert_eq!(arc.get(), 42);
312    /// ```
313    fn into_arc(self) -> ArcSupplier<T>
314    where
315        Self: Sized + Send + Sync + 'static,
316    {
317        ArcSupplier::new(move || self.get())
318    }
319
320    /// Converts to a closure implementing `Fn() -> T`.
321    ///
322    /// This method has a default implementation that wraps the
323    /// supplier in a closure. Custom implementations can override
324    /// this method for optimization purposes.
325    ///
326    /// # Returns
327    ///
328    /// A closure implementing `Fn() -> T`
329    ///
330    /// # Examples
331    ///
332    /// ```rust
333    /// use qubit_function::{Supplier, SupplierOnce};
334    ///
335    /// let closure = || 42;
336    /// let fn_closure = Supplier::into_fn(closure);
337    /// assert_eq!(fn_closure(), 42);
338    /// assert_eq!(fn_closure(), 42);
339    /// ```
340    fn into_fn(self) -> impl Fn() -> T
341    where
342        Self: Sized + 'static,
343    {
344        move || self.get()
345    }
346
347    /// Converts to `BoxSupplierOnce`.
348    ///
349    /// This method has a default implementation that wraps the
350    /// supplier in a `BoxSupplierOnce`. Custom implementations
351    /// can override this method for optimization purposes.
352    ///
353    /// # Returns
354    ///
355    /// A new `BoxSupplierOnce<T>` instance
356    ///
357    /// # Examples
358    ///
359    /// ```rust
360    /// use qubit_function::{Supplier, SupplierOnce};
361    ///
362    /// let closure = || 42;
363    /// let once = closure.into_once();
364    /// assert_eq!(once.get(), 42);
365    /// ```
366    fn into_once(self) -> BoxSupplierOnce<T>
367    where
368        Self: Sized + 'static,
369    {
370        BoxSupplierOnce::new(move || self.get())
371    }
372
373    /// Converts to `BoxSupplier` by cloning.
374    ///
375    /// This method clones the supplier and wraps it in a
376    /// `BoxSupplier`. Requires `Self: Clone`. Custom
377    /// implementations can override this method for optimization.
378    ///
379    /// # Returns
380    ///
381    /// A new `BoxSupplier<T>` instance
382    ///
383    /// # Examples
384    ///
385    /// ```rust
386    /// use qubit_function::Supplier;
387    ///
388    /// let closure = || 42;
389    /// let boxed = closure.to_box();
390    /// assert_eq!(boxed.get(), 42);
391    /// ```
392    fn to_box(&self) -> BoxSupplier<T>
393    where
394        Self: Clone + 'static,
395    {
396        self.clone().into_box()
397    }
398
399    /// Converts to `RcSupplier` by cloning.
400    ///
401    /// This method clones the supplier and wraps it in an
402    /// `RcSupplier`. Requires `Self: Clone`. Custom
403    /// implementations can override this method for optimization.
404    ///
405    /// # Returns
406    ///
407    /// A new `RcSupplier<T>` instance
408    ///
409    /// # Examples
410    ///
411    /// ```rust
412    /// use qubit_function::Supplier;
413    ///
414    /// let closure = || 42;
415    /// let rc = closure.to_rc();
416    /// assert_eq!(rc.get(), 42);
417    /// ```
418    fn to_rc(&self) -> RcSupplier<T>
419    where
420        Self: Clone + 'static,
421    {
422        self.clone().into_rc()
423    }
424
425    /// Converts to `ArcSupplier` by cloning.
426    ///
427    /// This method clones the supplier and wraps it in an
428    /// `ArcSupplier`. Requires `Self: Clone + Send + Sync`.
429    /// Custom implementations can override this method for
430    /// optimization.
431    ///
432    /// # Returns
433    ///
434    /// A new `ArcSupplier<T>` instance
435    ///
436    /// # Examples
437    ///
438    /// ```rust
439    /// use qubit_function::Supplier;
440    ///
441    /// let closure = || 42;
442    /// let arc = closure.to_arc();
443    /// assert_eq!(arc.get(), 42);
444    /// ```
445    fn to_arc(&self) -> ArcSupplier<T>
446    where
447        Self: Clone + Send + Sync + 'static,
448    {
449        self.clone().into_arc()
450    }
451
452    /// Converts to a closure by cloning.
453    ///
454    /// This method clones the supplier and wraps it in a closure
455    /// implementing `Fn() -> T`. Requires `Self: Clone`. Custom
456    /// implementations can override this method for optimization.
457    ///
458    /// # Returns
459    ///
460    /// A closure implementing `Fn() -> T`
461    ///
462    /// # Examples
463    ///
464    /// ```rust
465    /// use qubit_function::Supplier;
466    ///
467    /// let closure = || 42;
468    /// let fn_closure = closure.to_fn();
469    /// assert_eq!(fn_closure(), 42);
470    /// assert_eq!(fn_closure(), 42);
471    /// ```
472    fn to_fn(&self) -> impl Fn() -> T
473    where
474        Self: Clone + 'static,
475    {
476        self.clone().into_fn()
477    }
478
479    /// Converts to `BoxSupplierOnce` without consuming self
480    ///
481    /// **⚠️ Requires Clone**: This method requires `Self` to implement `Clone`.
482    /// Clones the current supplier and converts the clone to a one-time supplier.
483    ///
484    /// # Returns
485    ///
486    /// Returns a `BoxSupplierOnce<T>`
487    fn to_once(&self) -> BoxSupplierOnce<T>
488    where
489        Self: Clone + 'static,
490    {
491        self.clone().into_once()
492    }
493}