Skip to main content

qubit_function/transformers/transformer/
box_transformer.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 `BoxTransformer` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// ============================================================================
18// BoxTransformer - Box<dyn Fn(T) -> R>
19// ============================================================================
20
21/// BoxTransformer - transformer wrapper based on `Box<dyn Fn>`
22///
23/// A transformer wrapper that provides single ownership with reusable
24/// transformation. The transformer 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 BoxTransformer<T, R> {
36    pub(super) function: Box<dyn Fn(T) -> R>,
37    pub(super) name: Option<String>,
38}
39
40// Implement BoxTransformer
41impl<T, R> BoxTransformer<T, R> {
42    impl_transformer_common_methods!(
43        BoxTransformer<T, R>,
44        (Fn(T) -> R + 'static),
45        |f| Box::new(f)
46    );
47
48    impl_box_transformer_methods!(
49        BoxTransformer<T, R>,
50        BoxConditionalTransformer,
51        Transformer
52    );
53}
54
55// Implement constant method for BoxTransformer
56impl_transformer_constant_method!(BoxTransformer<T, R>);
57
58// Implement Debug and Display for BoxTransformer
59impl_transformer_debug_display!(BoxTransformer<T, R>);
60
61// Implement Transformer for BoxTransformer
62impl<T, R> Transformer<T, R> for BoxTransformer<T, R> {
63    fn apply(&self, input: T) -> R {
64        (self.function)(input)
65    }
66
67    // Generates: into_box(), into_rc(), into_fn(), into_once()
68    impl_box_conversions!(
69        BoxTransformer<T, R>,
70        RcTransformer,
71        Fn(T) -> R,
72        BoxTransformerOnce
73    );
74}