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