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