qubit_function/predicates/bi_predicate/arc_bi_predicate.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 `ArcBiPredicate` public type.
12
13#![allow(unused_imports)]
14
15use super::*;
16
17/// An Arc-based bi-predicate with thread-safe shared ownership.
18///
19/// This type is suitable for scenarios where the bi-predicate needs
20/// to be shared across threads. Composition methods borrow `&self`,
21/// allowing the original bi-predicate to remain usable after
22/// composition.
23///
24/// # Examples
25///
26/// ```rust
27/// use qubit_function::{BiPredicate, ArcBiPredicate};
28///
29/// let pred = ArcBiPredicate::new(|x: &i32, y: &i32| x + y > 0);
30/// assert!(pred.test(&5, &3));
31///
32/// // Original bi-predicate remains usable after composition
33/// let combined = pred.and(ArcBiPredicate::new(|x, y| x > y));
34/// assert!(pred.test(&5, &3)); // Still works
35///
36/// // Can be cloned and sent across threads
37/// let pred_clone = pred.clone();
38/// std::thread::spawn(move || {
39/// assert!(pred_clone.test(&10, &5));
40/// }).join().unwrap();
41/// ```
42///
43pub struct ArcBiPredicate<T, U> {
44 pub(super) function: Arc<SendSyncBiPredicateFn<T, U>>,
45 pub(super) name: Option<String>,
46}
47
48impl<T, U> ArcBiPredicate<T, U> {
49 // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
50 impl_predicate_common_methods!(
51 ArcBiPredicate<T, U>,
52 (Fn(&T, &U) -> bool + Send + Sync + 'static),
53 |f| Arc::new(f)
54 );
55
56 // Generates: and(), or(), not(), nand(), xor(), nor()
57 impl_shared_predicate_methods!(
58 ArcBiPredicate<T, U>,
59 Send + Sync + 'static
60 );
61}
62
63// Generates: impl Clone for ArcBiPredicate<T, U>
64impl_predicate_clone!(ArcBiPredicate<T, U>);
65
66// Generates: impl Debug for ArcBiPredicate<T, U> and impl Display for ArcBiPredicate<T, U>
67impl_predicate_debug_display!(ArcBiPredicate<T, U>);
68
69// Implements BiPredicate trait for ArcBiPredicate<T, U>
70impl<T, U> BiPredicate<T, U> for ArcBiPredicate<T, U> {
71 fn test(&self, first: &T, second: &U) -> bool {
72 (self.function)(first, second)
73 }
74
75 // Generates: into_box, into_rc, into_arc, into_fn, to_box, to_rc, to_arc, to_fn
76 impl_arc_conversions!(
77 ArcBiPredicate<T, U>,
78 BoxBiPredicate,
79 RcBiPredicate,
80 Fn(first: &T, second: &U) -> bool
81 );
82}
83
84// Blanket implementation for all closures that match
85// Fn(&T, &U) -> bool. This provides optimal implementations for
86// closures by wrapping them directly into the target type.
87impl_closure_trait!(
88 BiPredicate<T, U>,
89 test,
90 Fn(first: &T, second: &U) -> bool
91);