qubit_function/consumers/consumer/box_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 `BoxConsumer` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17// ============================================================================
18// 2. BoxConsumer - Single Ownership Implementation
19// ============================================================================
20
21/// BoxConsumer struct
22///
23/// Non-mutating consumer implementation based on `Box<dyn Fn(&T)>` for single
24/// ownership scenarios.
25///
26/// # Features
27///
28/// - **Single Ownership**: Not cloneable, transfers ownership when used
29/// - **Zero Overhead**: No reference counting or lock overhead
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 `BoxConsumer` when:
38/// - Non-mutating consumer is used once or in a linear flow
39/// - No need to share consumer across contexts
40/// - Pure observation operations, such as logging
41///
42/// # Examples
43///
44/// ```rust
45/// use qubit_function::{Consumer, BoxConsumer};
46///
47/// let consumer = BoxConsumer::new(|x: &i32| {
48/// println!("Observed value: {}", x);
49/// });
50/// consumer.accept(&5);
51/// ```
52///
53pub struct BoxConsumer<T> {
54 pub(super) function: Box<dyn Fn(&T)>,
55 pub(super) name: Option<String>,
56}
57
58impl<T> BoxConsumer<T> {
59 // Generates: new(), new_with_name(), name(), set_name(), noop()
60 impl_consumer_common_methods!(BoxConsumer<T>, (Fn(&T) + 'static), |f| Box::new(f));
61
62 // Generates: when() and and_then() methods that consume self
63 impl_box_consumer_methods!(BoxConsumer<T>, BoxConditionalConsumer, Consumer);
64}
65
66impl<T> Consumer<T> for BoxConsumer<T> {
67 fn accept(&self, value: &T) {
68 (self.function)(value)
69 }
70
71 // Generates: into_box(), into_rc(), into_fn(), into_once()
72 impl_box_conversions!(BoxConsumer<T>, RcConsumer, Fn(&T), BoxConsumerOnce);
73}
74
75// Use macro to generate Debug and Display implementations
76impl_consumer_debug_display!(BoxConsumer<T>);