Skip to main content

qubit_function/suppliers/supplier/
box_supplier.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `BoxSupplier` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ======================================================================
16// BoxSupplier - Single Ownership Implementation
17// ======================================================================
18
19/// Box-based single ownership stateless supplier.
20///
21/// Uses `Box<dyn Fn() -> T>` for single ownership scenarios. This
22/// is the most lightweight stateless supplier with zero reference
23/// counting overhead.
24///
25/// # Ownership Model
26///
27/// Methods consume `self` (move semantics) or borrow `&self` for
28/// read-only operations. When you call methods like `map()`, the
29/// original supplier is consumed and you get a new one:
30///
31/// ```rust
32/// use qubit_function::{BoxSupplier, Supplier};
33///
34/// let supplier = BoxSupplier::new(|| 10);
35/// let mapped = supplier.map(|x| x * 2);
36/// // supplier is no longer usable here
37/// ```
38///
39/// # Examples
40///
41/// ## Constant Factory
42///
43/// ```rust
44/// use qubit_function::{BoxSupplier, Supplier};
45///
46/// let factory = BoxSupplier::new(|| 42);
47/// assert_eq!(factory.get(), 42);
48/// assert_eq!(factory.get(), 42);
49/// ```
50///
51/// ## Method Chaining
52///
53/// ```rust
54/// use qubit_function::{BoxSupplier, Supplier};
55///
56/// let pipeline = BoxSupplier::new(|| 10)
57///     .map(|x| x * 2)
58///     .map(|x| x + 5);
59///
60/// assert_eq!(pipeline.get(), 25);
61/// ```
62///
63/// # Author
64///
65/// Haixing Hu
66pub struct BoxSupplier<T> {
67    pub(super) function: Box<dyn Fn() -> T>,
68    pub(super) name: Option<String>,
69}
70
71impl<T> BoxSupplier<T> {
72    // Generates: new(), new_with_name(), name(), set_name(), constant()
73    impl_supplier_common_methods!(BoxSupplier<T>, (Fn() -> T + 'static), |f| Box::new(f));
74
75    // Generates: map(), filter(), zip()
76    impl_box_supplier_methods!(BoxSupplier<T>, Supplier);
77}
78
79// Generates: Debug and Display implementations for BoxSupplier<T>
80impl_supplier_debug_display!(BoxSupplier<T>);
81
82impl<T> Supplier<T> for BoxSupplier<T> {
83    fn get(&self) -> T {
84        (self.function)()
85    }
86
87    // Generates: into_box(), into_rc(), into_fn(), into_once()
88    impl_box_conversions!(
89        BoxSupplier<T>,
90        RcSupplier,
91        Fn() -> T,
92        BoxSupplierOnce
93    );
94}