Skip to main content

qubit_function/suppliers/stateful_supplier/
box_stateful_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 `BoxStatefulSupplier` public type.
12
13use super::{
14    BoxSupplierOnce,
15    Predicate,
16    RcStatefulSupplier,
17    StatefulSupplier,
18    Transformer,
19    impl_box_conversions,
20    impl_box_supplier_methods,
21    impl_supplier_common_methods,
22    impl_supplier_debug_display,
23};
24
25// ==========================================================================
26// BoxStatefulSupplier - Single Ownership Implementation
27// ==========================================================================
28
29/// Box-based single ownership supplier.
30///
31/// Uses `Box<dyn FnMut() -> T>` for single ownership scenarios.
32/// This is the most lightweight supplier with zero reference
33/// counting overhead.
34///
35/// # Ownership Model
36///
37/// Methods consume `self` (move semantics). When you call a method
38/// like `map()`, the original supplier is consumed and you get a new
39/// one:
40///
41/// ```rust
42/// use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
43///
44/// let supplier = BoxStatefulSupplier::new(|| 10);
45/// let mapped = supplier.map(|x| x * 2);
46/// // supplier is no longer usable here
47/// ```
48///
49/// # Examples
50///
51/// ## Counter
52///
53/// ```rust
54/// use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
55///
56/// let mut counter = 0;
57/// let mut supplier = BoxStatefulSupplier::new(move || {
58///     counter += 1;
59///     counter
60/// });
61///
62/// assert_eq!(supplier.get(), 1);
63/// assert_eq!(supplier.get(), 2);
64/// ```
65///
66/// ## Method Chaining
67///
68/// ```rust
69/// use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
70///
71/// let mut pipeline = BoxStatefulSupplier::new(|| 10)
72///     .map(|x| x * 2)
73///     .map(|x| x + 5);
74///
75/// assert_eq!(pipeline.get(), 25);
76/// ```
77///
78pub struct BoxStatefulSupplier<T> {
79    pub(super) function: Box<dyn FnMut() -> T>,
80    pub(super) name: Option<String>,
81}
82
83impl<T> BoxStatefulSupplier<T> {
84    // Generates: new(), new_with_name(), name(), set_name(), constant()
85    impl_supplier_common_methods!(BoxStatefulSupplier<T>, (FnMut() -> T + 'static), |f| { Box::new(f) });
86
87    // Generates: map(), filter(), zip()
88    impl_box_supplier_methods!(BoxStatefulSupplier<T>, StatefulSupplier);
89
90    /// Creates a memoizing supplier.
91    ///
92    /// Returns a new supplier that caches the first value it
93    /// produces. All subsequent calls return the cached value.
94    ///
95    /// # Returns
96    ///
97    /// A new memoized `BoxStatefulSupplier<T>`
98    ///
99    /// # Examples
100    ///
101    /// ```rust
102    /// use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
103    ///
104    /// let mut call_count = 0;
105    /// let mut memoized = BoxStatefulSupplier::new(move || {
106    ///     call_count += 1;
107    ///     42
108    /// }).memoize();
109    ///
110    /// assert_eq!(memoized.get(), 42); // Calls underlying function
111    /// assert_eq!(memoized.get(), 42); // Returns cached value
112    /// ```
113    pub fn memoize(mut self) -> BoxStatefulSupplier<T>
114    where
115        T: Clone + 'static,
116    {
117        let mut cache: Option<T> = None;
118        BoxStatefulSupplier::new(move || {
119            if let Some(ref cached) = cache {
120                cached.clone()
121            } else {
122                let value = StatefulSupplier::get(&mut self);
123                cache = Some(value.clone());
124                value
125            }
126        })
127    }
128}
129
130// Generates: Debug and Display implementations for BoxStatefulSupplier<T>
131impl_supplier_debug_display!(BoxStatefulSupplier<T>);
132
133impl<T> StatefulSupplier<T> for BoxStatefulSupplier<T> {
134    fn get(&mut self) -> T {
135        (self.function)()
136    }
137
138    // Generates: into_box(), into_rc(), into_fn(), into_once()
139    impl_box_conversions!(
140        BoxStatefulSupplier<T>,
141        RcStatefulSupplier,
142        FnMut() -> T,
143        BoxSupplierOnce
144    );
145}