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