qubit_function/predicates/predicate/box_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 `BoxPredicate` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15/// A Box-based predicate with single ownership.
16///
17/// This type is suitable for one-time use scenarios where the predicate does
18/// not need to be cloned or shared. Composition methods consume `self`,
19/// reflecting the single-ownership model.
20///
21/// # Examples
22///
23/// ```rust
24/// use qubit_function::{Predicate, BoxPredicate};
25///
26/// let pred = BoxPredicate::new(|x: &i32| *x > 0);
27/// assert!(pred.test(&5));
28///
29/// // Chaining consumes the predicate
30/// let combined = pred.and(BoxPredicate::new(|x| x % 2 == 0));
31/// assert!(combined.test(&4));
32/// ```
33///
34/// # Author
35///
36/// Haixing Hu
37pub struct BoxPredicate<T> {
38 pub(super) function: Box<dyn Fn(&T) -> bool>,
39 pub(super) name: Option<String>,
40}
41
42impl<T> BoxPredicate<T> {
43 // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
44 impl_predicate_common_methods!(BoxPredicate<T>, (Fn(&T) -> bool + 'static), |f| Box::new(f));
45
46 // Generates: and(), or(), not(), nand(), xor(), nor()
47 impl_box_predicate_methods!(BoxPredicate<T>);
48}
49
50// Generates: impl Debug for BoxPredicate<T> and impl Display for BoxPredicate<T>
51impl_predicate_debug_display!(BoxPredicate<T>);
52
53// Implements Predicate trait for BoxPredicate<T>
54impl<T> Predicate<T> for BoxPredicate<T> {
55 fn test(&self, value: &T) -> bool {
56 (self.function)(value)
57 }
58
59 // Generates: into_box(), into_rc(), into_fn()
60 impl_box_conversions!(
61 BoxPredicate<T>,
62 RcPredicate,
63 Fn(&T) -> bool
64 );
65}