Skip to main content

qubit_function/predicates/predicate/
arc_predicate.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `ArcPredicate` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15/// An Arc-based predicate with thread-safe shared ownership.
16///
17/// This type is suitable for scenarios where the predicate needs to be
18/// shared across threads. Composition methods borrow `&self`, allowing the
19/// original predicate to remain usable after composition.
20///
21/// # Examples
22///
23/// ```rust
24/// use qubit_function::{Predicate, ArcPredicate};
25///
26/// let pred = ArcPredicate::new(|x: &i32| *x > 0);
27/// assert!(pred.test(&5));
28///
29/// // Original predicate remains usable after composition
30/// let combined = pred.and(ArcPredicate::new(|x| x % 2 == 0));
31/// assert!(pred.test(&5));  // Still works
32///
33/// // Can be cloned and sent across threads
34/// let pred_clone = pred.clone();
35/// std::thread::spawn(move || {
36///     assert!(pred_clone.test(&10));
37/// }).join().unwrap();
38/// ```
39///
40/// # Author
41///
42/// Haixing Hu
43pub struct ArcPredicate<T> {
44    pub(super) function: Arc<dyn Fn(&T) -> bool + Send + Sync>,
45    pub(super) name: Option<String>,
46}
47
48impl<T> ArcPredicate<T> {
49    // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
50    impl_predicate_common_methods!(
51        ArcPredicate<T>,
52        (Fn(&T) -> bool + Send + Sync + 'static),
53        |f| Arc::new(f)
54    );
55
56    // Generates: and(), or(), not(), nand(), xor(), nor()
57    impl_shared_predicate_methods!(ArcPredicate<T>, Send + Sync + 'static);
58}
59
60// Generates: impl Clone for ArcPredicate<T>
61impl_predicate_clone!(ArcPredicate<T>);
62
63// Generates: impl Debug for ArcPredicate<T> and impl Display for ArcPredicate<T>
64impl_predicate_debug_display!(ArcPredicate<T>);
65
66// Implements Predicate trait for ArcPredicate<T>
67impl<T> Predicate<T> for ArcPredicate<T> {
68    fn test(&self, value: &T) -> bool {
69        (self.function)(value)
70    }
71
72    // Generates: into_box, into_rc, into_arc, into_fn, to_box, to_rc, to_arc, to_fn
73    impl_arc_conversions!(
74        ArcPredicate<T>,
75        BoxPredicate,
76        RcPredicate,
77        Fn(t: &T) -> bool
78    );
79}
80
81// Blanket implementation for all closures that match Fn(&T) -> bool
82impl_closure_trait!(
83    Predicate<T>,
84    test,
85    Fn(value: &T) -> bool
86);