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