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