Skip to main content

qubit_function/functions/function_once/
box_function_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 `BoxFunctionOnce` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// BoxFunctionOnce - Box<dyn FnOnce(&T) -> R>
17// ============================================================================
18
19/// BoxFunctionOnce - consuming transformer wrapper based on
20/// `Box<dyn FnOnce>`
21///
22/// A transformer wrapper that provides single ownership with one-time use
23/// semantics. Consumes both self and the input value.
24///
25/// # Features
26///
27/// - **Based on**: `Box<dyn FnOnce(&T) -> R>`
28/// - **Ownership**: Single ownership, cannot be cloned
29/// - **Reusability**: Can only be called once (consumes self and input)
30/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
31///
32/// # Author
33///
34/// Haixing Hu
35pub struct BoxFunctionOnce<T, R> {
36    pub(super) function: Box<dyn FnOnce(&T) -> R>,
37    pub(super) name: Option<String>,
38}
39
40impl<T, R> BoxFunctionOnce<T, R> {
41    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
42    impl_function_common_methods!(
43        BoxFunctionOnce<T, R>,
44        (FnOnce(&T) -> R + 'static),
45        |f| Box::new(f)
46    );
47
48    // Generates: when(), and_then(), compose()
49    impl_box_function_methods!(
50        BoxFunctionOnce<T, R>,
51        BoxConditionalFunctionOnce,
52        FunctionOnce
53    );
54}
55
56impl<T, R> FunctionOnce<T, R> for BoxFunctionOnce<T, R> {
57    fn apply(self, input: &T) -> R {
58        (self.function)(input)
59    }
60
61    impl_box_once_conversions!(
62        BoxFunctionOnce<T, R>,
63        FunctionOnce,
64        FnOnce(&T) -> R
65    );
66}
67
68// Generates: constant() method for BoxFunctionOnce<T, R>
69impl_function_constant_method!(BoxFunctionOnce<T, R>, 'static);
70
71// Generates: identity() method for BoxFunctionOnce<T, T>
72impl_function_identity_method!(BoxFunctionOnce<T, T>);
73
74// Generates: Debug and Display implementations for BoxFunctionOnce<T, R>
75impl_function_debug_display!(BoxFunctionOnce<T, R>);
76
77// ============================================================================
78// Blanket implementation for standard FnOnce trait
79// ============================================================================
80
81// Implement FunctionOnce for all FnOnce(&T) -> R using macro
82impl_closure_once_trait!(
83    FunctionOnce<T, R>,
84    apply,
85    BoxFunctionOnce,
86    FnOnce(input: &T) -> R
87);