Skip to main content

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