qubit_function/consumers/consumer/box_consumer.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `BoxConsumer` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// 2. BoxConsumer - Single Ownership Implementation
17// ============================================================================
18
19/// BoxConsumer struct
20///
21/// Non-mutating consumer implementation based on `Box<dyn Fn(&T)>` for single
22/// ownership scenarios.
23///
24/// # Features
25///
26/// - **Single Ownership**: Not cloneable, transfers ownership when used
27/// - **Zero Overhead**: No reference counting or lock overhead
28/// - **Shared-reference API**: Invoked through `&self` and shared input
29/// references
30/// - **No Wrapper Interior Mutability**: No need for Mutex or RefCell in the
31/// wrapper
32///
33/// # Use Cases
34///
35/// Choose `BoxConsumer` when:
36/// - Non-mutating consumer is used once or in a linear flow
37/// - No need to share consumer across contexts
38/// - Pure observation operations, such as logging
39///
40/// # Examples
41///
42/// ```rust
43/// use qubit_function::{Consumer, BoxConsumer};
44///
45/// let consumer = BoxConsumer::new(|x: &i32| {
46/// println!("Observed value: {}", x);
47/// });
48/// consumer.accept(&5);
49/// ```
50///
51/// # Author
52///
53/// Haixing Hu
54pub struct BoxConsumer<T> {
55 pub(super) function: Box<dyn Fn(&T)>,
56 pub(super) name: Option<String>,
57}
58
59impl<T> BoxConsumer<T> {
60 // Generates: new(), new_with_name(), name(), set_name(), noop()
61 impl_consumer_common_methods!(BoxConsumer<T>, (Fn(&T) + 'static), |f| Box::new(f));
62
63 // Generates: when() and and_then() methods that consume self
64 impl_box_consumer_methods!(BoxConsumer<T>, BoxConditionalConsumer, Consumer);
65}
66
67impl<T> Consumer<T> for BoxConsumer<T> {
68 fn accept(&self, value: &T) {
69 (self.function)(value)
70 }
71
72 // Generates: into_box(), into_rc(), into_fn(), into_once()
73 impl_box_conversions!(BoxConsumer<T>, RcConsumer, Fn(&T), BoxConsumerOnce);
74}
75
76// Use macro to generate Debug and Display implementations
77impl_consumer_debug_display!(BoxConsumer<T>);