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