qubit_function/functions/bi_function/rc_bi_function.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 `RcBiFunction` public type.
12
13use super::{
14 BiFunction,
15 BiPredicate,
16 BoxBiFunction,
17 BoxBiFunctionOnce,
18 Function,
19 Rc,
20 RcConditionalBiFunction,
21 impl_function_clone,
22 impl_function_common_methods,
23 impl_function_constant_method,
24 impl_function_debug_display,
25 impl_rc_conversions,
26 impl_shared_function_methods,
27};
28
29type RcBiFunctionFn<T, U, R> = Rc<dyn Fn(&T, &U) -> R>;
30
31// ============================================================================
32// RcBiFunction - Rc<dyn Fn(&T, &U) -> R>
33// ============================================================================
34
35/// RcBiFunction - single-threaded bi-function wrapper
36///
37/// A single-threaded, clonable bi-function wrapper optimized for scenarios
38/// that require sharing without thread-safety overhead.
39///
40/// # Features
41///
42/// - **Based on**: `Rc<dyn Fn(&T, &U) -> R>`
43/// - **Ownership**: Shared ownership via reference counting (non-atomic)
44/// - **Reusability**: Can be called multiple times (borrows inputs each time)
45/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
46/// - **Clonable**: Cheap cloning via `Rc::clone`
47///
48pub struct RcBiFunction<T, U, R> {
49 pub(super) function: RcBiFunctionFn<T, U, R>,
50 pub(super) name: Option<String>,
51}
52
53impl<T, U, R> RcBiFunction<T, U, R> {
54 impl_function_common_methods!(
55 RcBiFunction<T, U, R>,
56 (Fn(&T, &U) -> R + 'static),
57 |f| Rc::new(f)
58 );
59 impl_shared_function_methods!(
60 RcBiFunction<T, U, R>,
61 RcConditionalBiFunction,
62 into_rc,
63 Function,
64 'static
65 );
66}
67
68// Implement BiFunction trait for RcBiFunction
69impl<T, U, R> BiFunction<T, U, R> for RcBiFunction<T, U, R> {
70 fn apply(&self, first: &T, second: &U) -> R {
71 (self.function)(first, second)
72 }
73
74 // Generate into_box(), into_rc(), into_fn(), into_once(), to_box(), to_rc(), to_fn(), to_once()
75 impl_rc_conversions!(
76 RcBiFunction<T, U, R>,
77 BoxBiFunction,
78 BoxBiFunctionOnce,
79 Fn(first: &T, second: &U) -> R
80 );
81}
82
83// Implement constant method for RcBiFunction
84impl_function_constant_method!(RcBiFunction<T, U, R>);
85
86// Implement Debug and Display for RcBiFunction
87impl_function_debug_display!(RcBiFunction<T, U, R>);
88
89// Implement Clone for RcBiFunction
90impl_function_clone!(RcBiFunction<T, U, R>);