Skip to main content

qubit_function/consumers/bi_consumer/
box_bi_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 `BoxBiConsumer` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// =======================================================================
18// 2. BoxBiConsumer - Single Ownership Implementation
19// =======================================================================
20
21/// BoxBiConsumer struct
22///
23/// A non-mutating bi-consumer implementation based on `Box<dyn Fn(&T, &U)>`
24/// for single ownership scenarios.
25///
26/// # Features
27///
28/// - **Single Ownership**: Not cloneable, ownership moves on use
29/// - **Zero Overhead**: No reference counting or locking
30/// - **Shared-reference API**: Invoked through `&self` and shared input
31///   references
32/// - **No Wrapper Interior Mutability**: No need for Mutex or RefCell in the
33///   wrapper
34///
35/// # Use Cases
36///
37/// Choose `BoxBiConsumer` when:
38/// - The non-mutating bi-consumer is used only once or in a linear flow
39/// - No need to share the consumer across contexts
40/// - Pure observation operations like logging
41///
42/// # Examples
43///
44/// ```rust
45/// use qubit_function::{BiConsumer, BoxBiConsumer};
46///
47/// let consumer = BoxBiConsumer::new(|x: &i32, y: &i32| {
48///     println!("Sum: {}", x + y);
49/// });
50/// consumer.accept(&5, &3);
51/// ```
52///
53pub struct BoxBiConsumer<T, U> {
54    pub(super) function: Box<BiConsumerFn<T, U>>,
55    pub(super) name: Option<String>,
56}
57
58impl<T, U> BoxBiConsumer<T, U> {
59    // Generates: new(), new_with_name(), name(), set_name(), noop()
60    impl_consumer_common_methods!(
61        BoxBiConsumer<T, U>,
62        (Fn(&T, &U) + 'static),
63        |f| Box::new(f)
64    );
65
66    // Generates: when() and and_then() methods that consume self
67    impl_box_consumer_methods!(
68        BoxBiConsumer<T, U>,
69        BoxConditionalBiConsumer,
70        BiConsumer
71    );
72}
73
74impl<T, U> BiConsumer<T, U> for BoxBiConsumer<T, U> {
75    fn accept(&self, first: &T, second: &U) {
76        (self.function)(first, second)
77    }
78
79    // Generates: into_box(), into_rc(), into_fn(), into_once()
80    impl_box_conversions!(
81        BoxBiConsumer<T, U>,
82        RcBiConsumer,
83        Fn(&T, &U),
84        BoxBiConsumerOnce
85    );
86}
87
88// Use macro to generate Debug and Display implementations
89impl_consumer_debug_display!(BoxBiConsumer<T, U>);