Skip to main content

qubit_function/consumers/stateful_consumer/
box_conditional_stateful_consumer.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 `BoxConditionalStatefulConsumer` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// ============================================================================
18// 7. BoxConditionalStatefulConsumer - Box-based Conditional Consumer
19// ============================================================================
20
21/// BoxConditionalStatefulConsumer struct
22///
23/// A conditional consumer that only executes when a predicate is satisfied.
24/// Uses `BoxStatefulConsumer` and `BoxPredicate` for single ownership semantics.
25///
26/// This type is typically created by calling `BoxStatefulConsumer::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 consumes when predicate returns `true`
33/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
34/// - **Implements Consumer**: Can be used anywhere a `Consumer` is expected
35///
36/// # Examples
37///
38/// ## Basic Conditional Execution
39///
40/// ```rust
41/// use qubit_function::{Consumer, StatefulConsumer, BoxStatefulConsumer};
42/// use std::sync::{Arc, Mutex};
43///
44/// let log = Arc::new(Mutex::new(Vec::new()));
45/// let l = log.clone();
46/// let consumer = BoxStatefulConsumer::new(move |x: &i32| {
47///     l.lock().unwrap().push(*x);
48/// });
49/// let mut conditional = consumer.when(|x: &i32| *x > 0);
50///
51/// conditional.accept(&5);
52/// assert_eq!(*log.lock().unwrap(), vec![5]); // Executed
53///
54/// conditional.accept(&-5);
55/// assert_eq!(*log.lock().unwrap(), vec![5]); // Not executed
56/// ```
57///
58/// ## With or_else Branch
59///
60/// ```rust
61/// use qubit_function::{Consumer, StatefulConsumer, BoxStatefulConsumer};
62/// use std::sync::{Arc, Mutex};
63///
64/// let log = Arc::new(Mutex::new(Vec::new()));
65/// let l1 = log.clone();
66/// let l2 = log.clone();
67/// let mut consumer = BoxStatefulConsumer::new(move |x: &i32| {
68///     l1.lock().unwrap().push(*x);
69/// })
70/// .when(|x: &i32| *x > 0)
71/// .or_else(move |x: &i32| {
72///     l2.lock().unwrap().push(-*x);
73/// });
74///
75/// consumer.accept(&5);
76/// assert_eq!(*log.lock().unwrap(), vec![5]); // when branch executed
77///
78/// consumer.accept(&-5);
79/// assert_eq!(*log.lock().unwrap(), vec![5, 5]); // or_else branch executed
80/// ```
81///
82pub struct BoxConditionalStatefulConsumer<T> {
83    pub(super) consumer: BoxStatefulConsumer<T>,
84    pub(super) predicate: BoxPredicate<T>,
85}
86
87// Use macro to generate and_then and or_else methods
88impl_box_conditional_consumer!(
89    BoxConditionalStatefulConsumer<T>,
90    BoxStatefulConsumer,
91    StatefulConsumer
92);
93
94impl<T> StatefulConsumer<T> for BoxConditionalStatefulConsumer<T> {
95    fn accept(&mut self, value: &T) {
96        if self.predicate.test(value) {
97            self.consumer.accept(value);
98        }
99    }
100
101    // Generates: into_box(), into_rc(), into_fn()
102    impl_conditional_consumer_conversions!(BoxStatefulConsumer<T>, RcStatefulConsumer, FnMut);
103}
104
105// Use macro to generate Debug and Display implementations
106impl_conditional_consumer_debug_display!(BoxConditionalStatefulConsumer<T>);