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