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