Skip to main content

qubit_function/suppliers/supplier_once/
box_supplier_once.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 `BoxSupplierOnce` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// ==========================================================================
18// BoxSupplierOnce - One-time Supplier Implementation
19// ==========================================================================
20
21/// Box-based one-time supplier.
22///
23/// Uses `Box<dyn FnOnce() -> T>` for one-time value generation.
24/// Can only call `get()` once, consuming the supplier.
25///
26/// # Examples
27///
28/// ## Lazy Initialization
29///
30/// ```rust
31/// use qubit_function::{BoxSupplierOnce, SupplierOnce};
32///
33/// let once = BoxSupplierOnce::new(|| {
34///     println!("Expensive initialization");
35///     42
36/// });
37///
38/// let value = once.get(); // Prints: Expensive initialization
39/// assert_eq!(value, 42);
40/// ```
41///
42/// ## Moving Captured Values
43///
44/// ```rust
45/// use qubit_function::{BoxSupplierOnce, SupplierOnce};
46///
47/// let resource = String::from("data");
48/// let once = BoxSupplierOnce::new(move || resource);
49///
50/// let value = once.get();
51/// assert_eq!(value, "data");
52/// ```
53///
54pub struct BoxSupplierOnce<T> {
55    pub(super) function: Box<dyn FnOnce() -> T>,
56    pub(super) name: Option<String>,
57}
58
59impl<T> BoxSupplierOnce<T> {
60    // Generates: new(), new_with_name(), name(), set_name(), constant()
61    impl_supplier_common_methods!(BoxSupplierOnce<T>, (FnOnce() -> T + 'static), |f| Box::new(
62        f
63    ));
64
65    // Generates: map(), filter(), zip()
66    impl_box_supplier_methods!(BoxSupplierOnce<T>, SupplierOnce);
67}
68
69// Generates: implement SupplierOnce for BoxSupplierOnce<T>
70impl<T> SupplierOnce<T> for BoxSupplierOnce<T> {
71    fn get(self) -> T {
72        (self.function)()
73    }
74
75    impl_box_once_conversions!(
76        BoxSupplierOnce<T>,
77        SupplierOnce,
78        FnOnce() -> T
79    );
80}
81
82// Generates: Debug and Display implementations for BoxSupplierOnce<T>
83impl_supplier_debug_display!(BoxSupplierOnce<T>);
84
85// ==========================================================================
86// Implement SupplierOnce for Closures
87// ==========================================================================
88
89// Implement SupplierOnce for all FnOnce() -> T using macro
90impl_closure_once_trait!(
91    SupplierOnce<T>,
92    get,
93    BoxSupplierOnce,
94    FnOnce() -> T
95);