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