Skip to main content

qubit_function/predicates/predicate/
rc_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 `RcPredicate` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15/// An Rc-based predicate with single-threaded shared ownership.
16///
17/// This type is suitable for scenarios where the predicate needs to be
18/// reused in a single-threaded context. Composition methods borrow `&self`,
19/// allowing the original predicate to remain usable after composition.
20///
21/// # Examples
22///
23/// ```rust
24/// use qubit_function::{Predicate, RcPredicate};
25///
26/// let pred = RcPredicate::new(|x: &i32| *x > 0);
27/// assert!(pred.test(&5));
28///
29/// // Original predicate remains usable after composition
30/// let combined = pred.and(RcPredicate::new(|x| x % 2 == 0));
31/// assert!(pred.test(&5));  // Still works
32/// ```
33///
34/// # Author
35///
36/// Haixing Hu
37pub struct RcPredicate<T> {
38    pub(super) function: Rc<dyn Fn(&T) -> bool>,
39    pub(super) name: Option<String>,
40}
41
42impl<T> RcPredicate<T> {
43    // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
44    impl_predicate_common_methods!(RcPredicate<T>, (Fn(&T) -> bool + 'static), |f| Rc::new(f));
45
46    // Generates: and(), or(), not(), nand(), xor(), nor()
47    impl_shared_predicate_methods!(RcPredicate<T>, 'static);
48}
49
50// Generates: impl Clone for RcPredicate<T>
51impl_predicate_clone!(RcPredicate<T>);
52
53// Generates: impl Debug for RcPredicate<T> and impl Display for RcPredicate<T>
54impl_predicate_debug_display!(RcPredicate<T>);
55
56// Implements Predicate trait for RcPredicate<T>
57impl<T> Predicate<T> for RcPredicate<T> {
58    fn test(&self, value: &T) -> bool {
59        (self.function)(value)
60    }
61
62    // Generates: into_box(), into_rc(), into_fn(), to_box(), to_rc(), to_fn()
63    impl_rc_conversions!(
64        RcPredicate<T>,
65        BoxPredicate,
66        Fn(t: &T) -> bool
67    );
68}