Skip to main content

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