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