Skip to main content

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