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