Skip to main content

qubit_function/functions/function/
box_function.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `BoxFunction` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// BoxFunction - Box<dyn Fn(&T) -> R>
17// ============================================================================
18
19/// BoxFunction - function wrapper based on `Box<dyn Fn>`
20///
21/// A function wrapper that provides single ownership with reusable
22/// transformation. The function consumes the input and can be called
23/// multiple times.
24///
25/// # Features
26///
27/// - **Based on**: `Box<dyn Fn(&T) -> R>`
28/// - **Ownership**: Single ownership, cannot be cloned
29/// - **Reusability**: Can be called multiple times (each call consumes its
30///   input)
31/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
32///
33/// # Author
34///
35/// Haixing Hu
36pub struct BoxFunction<T, R> {
37    pub(super) function: Box<dyn Fn(&T) -> R>,
38    pub(super) name: Option<String>,
39}
40
41impl<T, R> BoxFunction<T, R> {
42    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
43    impl_function_common_methods!(
44        BoxFunction<T, R>,
45        (Fn(&T) -> R + 'static),
46        |f| Box::new(f)
47    );
48
49    // Generates: when(), and_then(), compose()
50    impl_box_function_methods!(
51        BoxFunction<T, R>,
52        BoxConditionalFunction,
53        Function
54    );
55}
56
57// Generates: constant() method for BoxFunction<T, R>
58impl_function_constant_method!(BoxFunction<T, R>, 'static);
59
60// Generates: identity() method for BoxFunction<T, T>
61impl_function_identity_method!(BoxFunction<T, T>);
62
63// Generates: Debug and Display implementations for BoxFunction<T, R>
64impl_function_debug_display!(BoxFunction<T, R>);
65
66// Implement Function trait for BoxFunction<T, R>
67impl<T, R> Function<T, R> for BoxFunction<T, R> {
68    fn apply(&self, t: &T) -> R {
69        (self.function)(t)
70    }
71
72    // Generates: into_box(), into_rc(), into_fn(), into_once()
73    impl_box_conversions!(
74        BoxFunction<T, R>,
75        RcFunction,
76        Fn(&T) -> R,
77        BoxFunctionOnce
78    );
79}