Skip to main content

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