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