Skip to main content

qubit_function/transformers/transformer/
box_conditional_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 `BoxConditionalTransformer` public type.
12
13use super::{
14    BoxPredicate,
15    BoxTransformer,
16    Predicate,
17    Transformer,
18    impl_box_conditional_transformer,
19    impl_conditional_transformer_debug_display,
20};
21
22// ============================================================================
23// BoxConditionalTransformer - Box-based Conditional Transformer
24// ============================================================================
25
26/// BoxConditionalTransformer struct
27///
28/// A conditional transformer that only executes when a predicate is satisfied.
29/// Uses `BoxTransformer` and `BoxPredicate` for single ownership semantics.
30///
31/// This type is typically created by calling `BoxTransformer::when()` and is
32/// designed to work with the `or_else()` method to create if-then-else logic.
33///
34/// # Features
35///
36/// - **Single Ownership**: Not cloneable, consumes `self` on use
37/// - **Conditional Execution**: Only transforms when predicate returns `true`
38/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
39/// - **Implements Transformer**: Can be used anywhere a `Transformer` is expected
40///
41/// # Examples
42///
43/// ## With or_else Branch
44///
45/// ```rust
46/// use qubit_function::{Transformer, BoxTransformer};
47///
48/// let double = BoxTransformer::new(|x: i32| x * 2);
49/// let negate = BoxTransformer::new(|x: i32| -x);
50/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
51///
52/// assert_eq!(conditional.apply(5), 10); // when branch executed
53/// assert_eq!(conditional.apply(-5), 5); // or_else branch executed
54/// ```
55///
56pub struct BoxConditionalTransformer<T, R> {
57    pub(super) transformer: BoxTransformer<T, R>,
58    pub(super) predicate: BoxPredicate<T>,
59}
60
61// Implement BoxConditionalTransformer
62impl_box_conditional_transformer!(
63    BoxConditionalTransformer<T, R>,
64    BoxTransformer,
65    Transformer
66);
67
68// Use macro to generate Debug and Display implementations
69impl_conditional_transformer_debug_display!(BoxConditionalTransformer<T, R>);