Skip to main content

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