Skip to main content

qubit_function/predicates/
predicate.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Predicate Abstraction
10//!
11//! Provides a Rust implementation similar to Java's `Predicate` interface
12//! for condition testing and logical composition.
13//!
14//! ## Core Semantics
15//!
16//! A **Predicate** is fundamentally a pure judgment operation that tests
17//! whether a value satisfies a specific condition. It should be:
18//!
19//! - **Read-only**: Does not modify the tested value
20//! - **Side-effect free**: Does not change external state (from the user's
21//!   perspective)
22//! - **Repeatable**: Same input should produce the same result
23//! - **Deterministic**: Judgment logic should be predictable
24//!
25//! It is similar to the `Fn(&T) -> bool` trait in the standard library.
26//!
27//! ## Design Philosophy
28//!
29//! This module follows these principles:
30//!
31//! 1. **Single Trait**: Only one `Predicate<T>` trait with `&self`, keeping
32//!    the API simple and semantically clear
33//! 2. **No PredicateMut**: All stateful scenarios use interior mutability
34//!    (`RefCell`, `Cell`, `Mutex`) instead of `&mut self`
35//! 3. **No PredicateOnce**: Violates predicate semantics - judgments should
36//!    be repeatable
37//! 4. **Three Implementations**: `BoxPredicate`, `RcPredicate`, and
38//!    `ArcPredicate` cover all ownership scenarios
39//!
40//! ## Type Selection Guide
41//!
42//! | Scenario | Recommended Type | Reason |
43//! |----------|------------------|--------|
44//! | One-time use | `BoxPredicate` | Single ownership, no overhead |
45//! | Multi-threaded | `ArcPredicate` | Thread-safe, clonable |
46//! | Single-threaded reuse | `RcPredicate` | Better performance |
47//! | Stateful predicate | Any type + `RefCell`/`Cell`/`Mutex` | Interior mutability |
48//!
49//! ## Examples
50//!
51//! ### Basic Usage with Closures
52//!
53//! ```rust
54//! use qubit_function::predicate::Predicate;
55//!
56//! let is_positive = |x: &i32| *x > 0;
57//! assert!(is_positive.test(&5));
58//! assert!(!is_positive.test(&-3));
59//! ```
60//!
61//! ### BoxPredicate - Single Ownership
62//!
63//! ```rust
64//! use qubit_function::predicate::{Predicate, BoxPredicate};
65//!
66//! let pred = BoxPredicate::new(|x: &i32| *x > 0)
67//!     .and(BoxPredicate::new(|x| x % 2 == 0));
68//! assert!(pred.test(&4));
69//! ```
70//!
71//! ### Closure Composition with Extension Methods
72//!
73//! Closures automatically gain `and`, `or`, `not` methods through the
74//! `FnPredicateOps` extension trait, returning `BoxPredicate`:
75//!
76//! ```rust
77//! use qubit_function::predicate::{Predicate, FnPredicateOps, BoxPredicate};
78//!
79//! // Compose closures directly - result is BoxPredicate
80//! let is_positive = |x: &i32| *x > 0;
81//! let is_even = |x: &i32| x % 2 == 0;
82//!
83//! let positive_and_even = is_positive.and(is_even);
84//! assert!(positive_and_even.test(&4));
85//! assert!(!positive_and_even.test(&3));
86//!
87//! // Can chain multiple operations
88//! let pred = (|x: &i32| *x > 0)
89//!     .and(|x: &i32| x % 2 == 0)
90//!     .and(BoxPredicate::new(|x: &i32| *x < 100));
91//! assert!(pred.test(&42));
92//!
93//! // Use `or` for disjunction
94//! let negative_or_large = (|x: &i32| *x < 0)
95//!     .or(|x: &i32| *x > 100);
96//! assert!(negative_or_large.test(&-5));
97//! assert!(negative_or_large.test(&200));
98//!
99//! // Use `not` for negation
100//! let not_zero = (|x: &i32| *x == 0).not();
101//! assert!(not_zero.test(&5));
102//! assert!(!not_zero.test(&0));
103//! ```
104//!
105//! ### Complex Predicate Composition
106//!
107//! Build complex predicates by mixing closures and predicate types:
108//!
109//! ```rust
110//! use qubit_function::predicate::{Predicate, BoxPredicate, FnPredicateOps};
111//!
112//! // Start with a closure, compose with BoxPredicate
113//! let in_range = (|x: &i32| *x >= 0)
114//!     .and(BoxPredicate::new(|x| *x <= 100));
115//!
116//! // Use in filtering
117//! let numbers = vec![-10, 5, 50, 150, 75];
118//! let filtered: Vec<_> = numbers.iter()
119//!     .copied()
120//!     .filter(in_range.into_fn())
121//!     .collect();
122//! assert_eq!(filtered, vec![5, 50, 75]);
123//! ```
124//!
125//! ### RcPredicate - Single-threaded Reuse
126//!
127//! ```rust
128//! use qubit_function::predicate::{Predicate, RcPredicate};
129//!
130//! let pred = RcPredicate::new(|x: &i32| *x > 0);
131//! let combined1 = pred.and(RcPredicate::new(|x| x % 2 == 0));
132//! let combined2 = pred.or(RcPredicate::new(|x| *x > 100));
133//!
134//! // Original predicate is still usable
135//! assert!(pred.test(&5));
136//! ```
137//!
138//! ### ArcPredicate - Thread-safe Sharing
139//!
140//! ```rust
141//! use qubit_function::predicate::{Predicate, ArcPredicate};
142//! use std::thread;
143//!
144//! let pred = ArcPredicate::new(|x: &i32| *x > 0);
145//! let pred_clone = pred.clone();
146//!
147//! let handle = thread::spawn(move || {
148//!     pred_clone.test(&10)
149//! });
150//!
151//! assert!(handle.join().unwrap());
152//! assert!(pred.test(&5));  // Original still usable
153//! ```
154//!
155//! ### Stateful Predicates with Interior Mutability
156//!
157//! ```rust
158//! use qubit_function::predicate::{Predicate, BoxPredicate};
159//! use std::cell::Cell;
160//!
161//! let count = Cell::new(0);
162//! let pred = BoxPredicate::new(move |x: &i32| {
163//!     count.set(count.get() + 1);
164//!     *x > 0
165//! });
166//!
167//! // No need for `mut` - interior mutability handles state
168//! assert!(pred.test(&5));
169//! assert!(!pred.test(&-3));
170//! ```
171//!
172//! ## Author
173//!
174//! Haixing Hu
175use std::rc::Rc;
176use std::sync::Arc;
177
178use crate::macros::{
179    impl_arc_conversions,
180    impl_box_conversions,
181    impl_closure_trait,
182    impl_rc_conversions,
183};
184use crate::predicates::macros::{
185    constants::{
186        ALWAYS_FALSE_NAME,
187        ALWAYS_TRUE_NAME,
188    },
189    impl_box_predicate_methods,
190    impl_predicate_clone,
191    impl_predicate_common_methods,
192    impl_predicate_debug_display,
193    impl_shared_predicate_methods,
194};
195
196/// A predicate trait for testing whether a value satisfies a condition.
197///
198/// This trait represents a **pure judgment operation** - it tests whether
199/// a given value meets certain criteria without modifying either the value
200/// or the predicate itself (from the user's perspective). This semantic
201/// clarity distinguishes predicates from consumers or transformers.
202///
203/// ## Design Rationale
204///
205/// This is a **minimal trait** that only defines:
206/// - The core `test` method using `&self` (immutable borrow)
207/// - Type conversion methods (`into_box`, `into_rc`, `into_arc`)
208/// - Closure conversion method (`into_fn`)
209///
210/// Logical composition methods (`and`, `or`, `not`) are intentionally
211/// **not** part of the trait. Instead, they are implemented on concrete
212/// types (`BoxPredicate`, `RcPredicate`, `ArcPredicate`), allowing each
213/// implementation to maintain its specific ownership characteristics:
214///
215/// - `BoxPredicate`: Methods consume `self` (single ownership)
216/// - `RcPredicate`: Methods borrow `&self` (shared ownership)
217/// - `ArcPredicate`: Methods borrow `&self` (thread-safe shared ownership)
218///
219/// ## Why `&self` Instead of `&mut self`?
220///
221/// Predicates use `&self` because:
222///
223/// 1. **Semantic Clarity**: A predicate is a judgment, not a mutation
224/// 2. **Flexibility**: Can be used in immutable contexts
225/// 3. **Simplicity**: No need for `mut` in user code
226/// 4. **Interior Mutability**: State (if needed) can be managed with
227///    `RefCell`, `Cell`, or `Mutex`
228///
229/// ## Automatic Implementation for Closures
230///
231/// Any closure matching `Fn(&T) -> bool` automatically implements this
232/// trait, providing seamless integration with Rust's closure system.
233///
234/// ## Examples
235///
236/// ### Basic Usage
237///
238/// ```rust
239/// use qubit_function::predicate::Predicate;
240///
241/// let is_positive = |x: &i32| *x > 0;
242/// assert!(is_positive.test(&5));
243/// assert!(!is_positive.test(&-3));
244/// ```
245///
246/// ### Type Conversion
247///
248/// ```rust
249/// use qubit_function::predicate::{Predicate, BoxPredicate};
250///
251/// let closure = |x: &i32| *x > 0;
252/// let boxed: BoxPredicate<i32> = closure.into_box();
253/// assert!(boxed.test(&5));
254/// ```
255///
256/// ### Stateful Predicate with Interior Mutability
257///
258/// ```rust
259/// use qubit_function::predicate::{Predicate, BoxPredicate};
260/// use std::cell::Cell;
261///
262/// let count = Cell::new(0);
263/// let counting_pred = BoxPredicate::new(move |x: &i32| {
264///     count.set(count.get() + 1);
265///     *x > 0
266/// });
267///
268/// // Note: No `mut` needed - interior mutability handles state
269/// assert!(counting_pred.test(&5));
270/// assert!(!counting_pred.test(&-3));
271/// ```
272///
273/// ## Author
274///
275/// Haixing Hu
276pub trait Predicate<T> {
277    /// Tests whether the given value satisfies this predicate.
278    ///
279    /// # Parameters
280    ///
281    /// * `value` - The value to test.
282    ///
283    /// # Returns
284    ///
285    /// `true` if the value satisfies this predicate, `false` otherwise.
286    fn test(&self, value: &T) -> bool;
287
288    /// Converts this predicate into a `BoxPredicate`.
289    ///
290    /// The default implementation wraps the predicate in a closure that
291    /// calls the `test` method. Concrete types may override this with
292    /// more efficient implementations.
293    ///
294    /// # Returns
295    ///
296    /// A `BoxPredicate` wrapping this predicate.
297    fn into_box(self) -> BoxPredicate<T>
298    where
299        Self: Sized + 'static,
300    {
301        BoxPredicate::new(move |value: &T| self.test(value))
302    }
303
304    /// Converts this predicate into an `RcPredicate`.
305    ///
306    /// The default implementation wraps the predicate in a closure that
307    /// calls the `test` method. Concrete types may override this with
308    /// more efficient implementations.
309    ///
310    /// # Returns
311    ///
312    /// An `RcPredicate` wrapping this predicate.
313    fn into_rc(self) -> RcPredicate<T>
314    where
315        Self: Sized + 'static,
316    {
317        RcPredicate::new(move |value: &T| self.test(value))
318    }
319
320    /// Converts this predicate into an `ArcPredicate`.
321    ///
322    /// The default implementation wraps the predicate in a closure that
323    /// calls the `test` method. Concrete types may override this with
324    /// more efficient implementations.
325    ///
326    /// # Returns
327    ///
328    /// An `ArcPredicate` wrapping this predicate.
329    fn into_arc(self) -> ArcPredicate<T>
330    where
331        Self: Sized + Send + Sync + 'static,
332    {
333        ArcPredicate::new(move |value: &T| self.test(value))
334    }
335
336    /// Converts this predicate into a closure that can be used directly
337    /// with standard library methods.
338    ///
339    /// This method consumes the predicate and returns a closure with
340    /// signature `Fn(&T) -> bool`. Since `Fn` is a subtrait of `FnMut`,
341    /// the returned closure can be used in any context that requires
342    /// either `Fn(&T) -> bool` or `FnMut(&T) -> bool`, making it
343    /// compatible with methods like `Iterator::filter`,
344    /// `Iterator::filter_map`, `Vec::retain`, and similar standard
345    /// library APIs.
346    ///
347    /// The default implementation returns a closure that calls the
348    /// `test` method. Concrete types may override this with more
349    /// efficient implementations.
350    ///
351    /// # Returns
352    ///
353    /// A closure implementing `Fn(&T) -> bool` (also usable as
354    /// `FnMut(&T) -> bool`).
355    ///
356    /// # Examples
357    ///
358    /// ## Using with `Iterator::filter` (requires `FnMut`)
359    ///
360    /// ```rust
361    /// use qubit_function::predicate::{Predicate, BoxPredicate};
362    ///
363    /// let pred = BoxPredicate::new(|x: &i32| *x > 0);
364    ///
365    /// let numbers = vec![-2, -1, 0, 1, 2, 3];
366    /// let positives: Vec<_> = numbers.iter()
367    ///     .copied()
368    ///     .filter(pred.into_fn())
369    ///     .collect();
370    /// assert_eq!(positives, vec![1, 2, 3]);
371    /// ```
372    ///
373    /// ## Using with `Vec::retain` (requires `FnMut`)
374    ///
375    /// ```rust
376    /// use qubit_function::predicate::{Predicate, BoxPredicate};
377    ///
378    /// let pred = BoxPredicate::new(|x: &i32| *x % 2 == 0);
379    /// let mut numbers = vec![1, 2, 3, 4, 5, 6];
380    /// numbers.retain(pred.into_fn());
381    /// assert_eq!(numbers, vec![2, 4, 6]);
382    /// ```
383    fn into_fn(self) -> impl Fn(&T) -> bool
384    where
385        Self: Sized + 'static,
386    {
387        move |value: &T| self.test(value)
388    }
389
390    /// Converts a reference to this predicate into a `BoxPredicate`.
391    ///
392    /// This method clones the predicate and then converts it to a
393    /// `BoxPredicate`. The original predicate remains usable after this call.
394    ///
395    /// # Returns
396    ///
397    /// A `BoxPredicate` wrapping a clone of this predicate.
398    fn to_box(&self) -> BoxPredicate<T>
399    where
400        Self: Clone + Sized + 'static,
401    {
402        self.clone().into_box()
403    }
404
405    /// Converts a reference to this predicate into an `RcPredicate`.
406    ///
407    /// This method clones the predicate and then converts it to an
408    /// `RcPredicate`. The original predicate remains usable after this call.
409    ///
410    /// # Returns
411    ///
412    /// An `RcPredicate` wrapping a clone of this predicate.
413    fn to_rc(&self) -> RcPredicate<T>
414    where
415        Self: Clone + Sized + 'static,
416    {
417        self.clone().into_rc()
418    }
419
420    /// Converts a reference to this predicate into an `ArcPredicate`.
421    ///
422    /// This method clones the predicate and then converts it to an
423    /// `ArcPredicate`. The original predicate remains usable after this call.
424    ///
425    /// # Returns
426    ///
427    /// An `ArcPredicate` wrapping a clone of this predicate.
428    fn to_arc(&self) -> ArcPredicate<T>
429    where
430        Self: Clone + Sized + Send + Sync + 'static,
431    {
432        self.clone().into_arc()
433    }
434
435    /// Converts a reference to this predicate into a closure that can be
436    /// used directly with standard library methods.
437    ///
438    /// This method clones the predicate and then converts it to a closure.
439    /// The original predicate remains usable after this call.
440    ///
441    /// The returned closure has signature `Fn(&T) -> bool`. Since `Fn` is a
442    /// subtrait of `FnMut`, it can be used in any context that requires
443    /// either `Fn(&T) -> bool` or `FnMut(&T) -> bool`, making it compatible
444    /// with methods like `Iterator::filter`, `Iterator::filter_map`,
445    /// `Vec::retain`, and similar standard library APIs.
446    ///
447    /// # Returns
448    ///
449    /// A closure implementing `Fn(&T) -> bool` (also usable as
450    /// `FnMut(&T) -> bool`).
451    fn to_fn(&self) -> impl Fn(&T) -> bool
452    where
453        Self: Clone + Sized + 'static,
454    {
455        self.clone().into_fn()
456    }
457}
458
459/// A Box-based predicate with single ownership.
460///
461/// This type is suitable for one-time use scenarios where the predicate does
462/// not need to be cloned or shared. Composition methods consume `self`,
463/// reflecting the single-ownership model.
464///
465/// # Examples
466///
467/// ```rust
468/// use qubit_function::predicate::{Predicate, BoxPredicate};
469///
470/// let pred = BoxPredicate::new(|x: &i32| *x > 0);
471/// assert!(pred.test(&5));
472///
473/// // Chaining consumes the predicate
474/// let combined = pred.and(BoxPredicate::new(|x| x % 2 == 0));
475/// assert!(combined.test(&4));
476/// ```
477///
478/// # Author
479///
480/// Haixing Hu
481pub struct BoxPredicate<T> {
482    function: Box<dyn Fn(&T) -> bool>,
483    name: Option<String>,
484}
485
486impl<T> BoxPredicate<T> {
487    // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
488    impl_predicate_common_methods!(BoxPredicate<T>, (Fn(&T) -> bool + 'static), |f| Box::new(f));
489
490    // Generates: and(), or(), not(), nand(), xor(), nor()
491    impl_box_predicate_methods!(BoxPredicate<T>);
492}
493
494// Generates: impl Debug for BoxPredicate<T> and impl Display for BoxPredicate<T>
495impl_predicate_debug_display!(BoxPredicate<T>);
496
497// Implements Predicate trait for BoxPredicate<T>
498impl<T> Predicate<T> for BoxPredicate<T> {
499    fn test(&self, value: &T) -> bool {
500        (self.function)(value)
501    }
502
503    // Generates: into_box(), into_rc(), into_fn()
504    impl_box_conversions!(
505        BoxPredicate<T>,
506        RcPredicate,
507        Fn(&T) -> bool
508    );
509}
510
511/// An Rc-based predicate with single-threaded shared ownership.
512///
513/// This type is suitable for scenarios where the predicate needs to be
514/// reused in a single-threaded context. Composition methods borrow `&self`,
515/// allowing the original predicate to remain usable after composition.
516///
517/// # Examples
518///
519/// ```rust
520/// use qubit_function::predicate::{Predicate, RcPredicate};
521///
522/// let pred = RcPredicate::new(|x: &i32| *x > 0);
523/// assert!(pred.test(&5));
524///
525/// // Original predicate remains usable after composition
526/// let combined = pred.and(RcPredicate::new(|x| x % 2 == 0));
527/// assert!(pred.test(&5));  // Still works
528/// ```
529///
530/// # Author
531///
532/// Haixing Hu
533pub struct RcPredicate<T> {
534    function: Rc<dyn Fn(&T) -> bool>,
535    name: Option<String>,
536}
537
538impl<T> RcPredicate<T> {
539    // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
540    impl_predicate_common_methods!(RcPredicate<T>, (Fn(&T) -> bool + 'static), |f| Rc::new(f));
541
542    // Generates: and(), or(), not(), nand(), xor(), nor()
543    impl_shared_predicate_methods!(RcPredicate<T>, 'static);
544}
545
546// Generates: impl Clone for RcPredicate<T>
547impl_predicate_clone!(RcPredicate<T>);
548
549// Generates: impl Debug for RcPredicate<T> and impl Display for RcPredicate<T>
550impl_predicate_debug_display!(RcPredicate<T>);
551
552// Implements Predicate trait for RcPredicate<T>
553impl<T> Predicate<T> for RcPredicate<T> {
554    fn test(&self, value: &T) -> bool {
555        (self.function)(value)
556    }
557
558    // Generates: into_box(), into_rc(), into_fn(), to_box(), to_rc(), to_fn()
559    impl_rc_conversions!(
560        RcPredicate<T>,
561        BoxPredicate,
562        Fn(t: &T) -> bool
563    );
564}
565
566/// An Arc-based predicate with thread-safe shared ownership.
567///
568/// This type is suitable for scenarios where the predicate needs to be
569/// shared across threads. Composition methods borrow `&self`, allowing the
570/// original predicate to remain usable after composition.
571///
572/// # Examples
573///
574/// ```rust
575/// use qubit_function::predicate::{Predicate, ArcPredicate};
576///
577/// let pred = ArcPredicate::new(|x: &i32| *x > 0);
578/// assert!(pred.test(&5));
579///
580/// // Original predicate remains usable after composition
581/// let combined = pred.and(ArcPredicate::new(|x| x % 2 == 0));
582/// assert!(pred.test(&5));  // Still works
583///
584/// // Can be cloned and sent across threads
585/// let pred_clone = pred.clone();
586/// std::thread::spawn(move || {
587///     assert!(pred_clone.test(&10));
588/// }).join().unwrap();
589/// ```
590///
591/// # Author
592///
593/// Haixing Hu
594pub struct ArcPredicate<T> {
595    function: Arc<dyn Fn(&T) -> bool + Send + Sync>,
596    name: Option<String>,
597}
598
599impl<T> ArcPredicate<T> {
600    // Generates: new(), new_with_name(), name(), set_name(), always_true(), always_false()
601    impl_predicate_common_methods!(
602        ArcPredicate<T>,
603        (Fn(&T) -> bool + Send + Sync + 'static),
604        |f| Arc::new(f)
605    );
606
607    // Generates: and(), or(), not(), nand(), xor(), nor()
608    impl_shared_predicate_methods!(ArcPredicate<T>, Send + Sync + 'static);
609}
610
611// Generates: impl Clone for ArcPredicate<T>
612impl_predicate_clone!(ArcPredicate<T>);
613
614// Generates: impl Debug for ArcPredicate<T> and impl Display for ArcPredicate<T>
615impl_predicate_debug_display!(ArcPredicate<T>);
616
617// Implements Predicate trait for ArcPredicate<T>
618impl<T> Predicate<T> for ArcPredicate<T> {
619    fn test(&self, value: &T) -> bool {
620        (self.function)(value)
621    }
622
623    // Generates: into_box, into_rc, into_arc, into_fn, to_box, to_rc, to_arc, to_fn
624    impl_arc_conversions!(
625        ArcPredicate<T>,
626        BoxPredicate,
627        RcPredicate,
628        Fn(t: &T) -> bool
629    );
630}
631
632// Blanket implementation for all closures that match Fn(&T) -> bool
633impl_closure_trait!(
634    Predicate<T>,
635    test,
636    Fn(value: &T) -> bool
637);
638
639/// Extension trait providing logical composition methods for closures.
640///
641/// This trait is automatically implemented for all closures and function
642/// pointers that match `Fn(&T) -> bool`, enabling method chaining starting
643/// from a closure.
644///
645/// # Examples
646///
647/// ```rust
648/// use qubit_function::predicate::{Predicate, FnPredicateOps};
649///
650/// let is_positive = |x: &i32| *x > 0;
651/// let is_even = |x: &i32| x % 2 == 0;
652///
653/// // Combine predicates using extension methods
654/// let pred = is_positive.and(is_even);
655/// assert!(pred.test(&4));
656/// assert!(!pred.test(&3));
657/// ```
658///
659/// # Author
660///
661/// Haixing Hu
662pub trait FnPredicateOps<T>: Fn(&T) -> bool + Sized {
663    /// Returns a predicate that represents the logical AND of this predicate
664    /// and another.
665    ///
666    /// # Parameters
667    ///
668    /// * `other` - The other predicate to combine with. **Note: This parameter
669    ///   is passed by value and will transfer ownership.** If you need to
670    ///   preserve the original predicate, clone it first (if it implements
671    ///   `Clone`). Can be:
672    ///   - Another closure
673    ///   - A function pointer
674    ///   - A `BoxPredicate<T>`, `RcPredicate<T>`, or `ArcPredicate<T>`
675    ///
676    /// # Returns
677    ///
678    /// A `BoxPredicate` representing the logical AND.
679    ///
680    /// # Examples
681    ///
682    /// ```rust
683    /// use qubit_function::predicate::{Predicate, FnPredicateOps};
684    ///
685    /// let is_positive = |x: &i32| *x > 0;
686    /// let is_even = |x: &i32| x % 2 == 0;
687    ///
688    /// let combined = is_positive.and(is_even);
689    /// assert!(combined.test(&4));
690    /// assert!(!combined.test(&3));
691    /// ```
692    fn and<P>(self, other: P) -> BoxPredicate<T>
693    where
694        Self: 'static,
695        P: Predicate<T> + 'static,
696        T: 'static,
697    {
698        BoxPredicate::new(move |value: &T| self.test(value) && other.test(value))
699    }
700
701    /// Returns a predicate that represents the logical OR of this predicate
702    /// and another.
703    ///
704    /// # Parameters
705    ///
706    /// * `other` - The other predicate to combine with. **Note: This parameter
707    ///   is passed by value and will transfer ownership.** If you need to
708    ///   preserve the original predicate, clone it first (if it implements
709    ///   `Clone`). Can be:
710    ///   - Another closure
711    ///   - A function pointer
712    ///   - A `BoxPredicate<T>`, `RcPredicate<T>`, or `ArcPredicate<T>`
713    ///   - Any type implementing `Predicate<T>`
714    ///
715    /// # Returns
716    ///
717    /// A `BoxPredicate` representing the logical OR.
718    ///
719    /// # Examples
720    ///
721    /// ```rust
722    /// use qubit_function::predicate::{Predicate, FnPredicateOps};
723    ///
724    /// let is_negative = |x: &i32| *x < 0;
725    /// let is_large = |x: &i32| *x > 100;
726    ///
727    /// let combined = is_negative.or(is_large);
728    /// assert!(combined.test(&-5));
729    /// assert!(combined.test(&150));
730    /// assert!(!combined.test(&50));
731    /// ```
732    fn or<P>(self, other: P) -> BoxPredicate<T>
733    where
734        Self: 'static,
735        P: Predicate<T> + 'static,
736        T: 'static,
737    {
738        BoxPredicate::new(move |value: &T| self.test(value) || other.test(value))
739    }
740
741    /// Returns a predicate that represents the logical negation of this
742    /// predicate.
743    ///
744    /// # Returns
745    ///
746    /// A `BoxPredicate` representing the logical negation.
747    fn not(self) -> BoxPredicate<T>
748    where
749        Self: 'static,
750        T: 'static,
751    {
752        BoxPredicate::new(move |value: &T| !self.test(value))
753    }
754
755    /// Returns a predicate that represents the logical NAND (NOT AND) of this
756    /// predicate and another.
757    ///
758    /// NAND returns `true` unless both predicates are `true`.
759    /// Equivalent to `!(self AND other)`.
760    ///
761    /// # Parameters
762    ///
763    /// * `other` - The other predicate to combine with. **Note: This parameter
764    ///   is passed by value and will transfer ownership.** If you need to
765    ///   preserve the original predicate, clone it first (if it implements
766    ///   `Clone`). Accepts closures, function pointers, or any
767    ///   `Predicate<T>` implementation.
768    ///
769    /// # Returns
770    ///
771    /// A `BoxPredicate` representing the logical NAND.
772    ///
773    /// # Examples
774    ///
775    /// ```rust
776    /// use qubit_function::predicate::{Predicate, FnPredicateOps};
777    ///
778    /// let is_positive = |x: &i32| *x > 0;
779    /// let is_even = |x: &i32| x % 2 == 0;
780    ///
781    /// let nand = is_positive.nand(is_even);
782    /// assert!(nand.test(&3));   // !(true && false) = true
783    /// assert!(!nand.test(&4));  // !(true && true) = false
784    /// ```
785    fn nand<P>(self, other: P) -> BoxPredicate<T>
786    where
787        Self: 'static,
788        P: Predicate<T> + 'static,
789        T: 'static,
790    {
791        BoxPredicate::new(move |value: &T| !(self.test(value) && other.test(value)))
792    }
793
794    /// Returns a predicate that represents the logical XOR (exclusive OR) of
795    /// this predicate and another.
796    ///
797    /// XOR returns `true` if exactly one of the predicates is `true`.
798    ///
799    /// # Parameters
800    ///
801    /// * `other` - The other predicate to combine with. **Note: This parameter
802    ///   is passed by value and will transfer ownership.** If you need to
803    ///   preserve the original predicate, clone it first (if it implements
804    ///   `Clone`). Accepts closures, function pointers, or any
805    ///   `Predicate<T>` implementation.
806    ///
807    /// # Returns
808    ///
809    /// A `BoxPredicate` representing the logical XOR.
810    ///
811    /// # Examples
812    ///
813    /// ```rust
814    /// use qubit_function::predicate::{Predicate, FnPredicateOps};
815    ///
816    /// let is_positive = |x: &i32| *x > 0;
817    /// let is_even = |x: &i32| x % 2 == 0;
818    ///
819    /// let xor = is_positive.xor(is_even);
820    /// assert!(xor.test(&3));    // true ^ false = true
821    /// assert!(!xor.test(&4));   // true ^ true = false
822    /// assert!(!xor.test(&-1));  // false ^ false = false
823    /// ```
824    fn xor<P>(self, other: P) -> BoxPredicate<T>
825    where
826        Self: 'static,
827        P: Predicate<T> + 'static,
828        T: 'static,
829    {
830        BoxPredicate::new(move |value: &T| self.test(value) ^ other.test(value))
831    }
832
833    /// Returns a predicate that represents the logical NOR (NOT OR) of this
834    /// predicate and another.
835    ///
836    /// NOR returns `true` only when both predicates are `false`. Equivalent
837    /// to `!(self OR other)`.
838    ///
839    /// # Parameters
840    ///
841    /// * `other` - The other predicate to combine with. **Note: This parameter
842    ///   is passed by value and will transfer ownership.** If you need to
843    ///   preserve the original predicate, clone it first (if it implements
844    ///   `Clone`). Accepts closures, function pointers, or any
845    ///   `Predicate<T>` implementation.
846    ///
847    /// # Returns
848    ///
849    /// A `BoxPredicate` representing the logical NOR.
850    ///
851    /// # Examples
852    ///
853    /// ```rust
854    /// use qubit_function::predicate::{Predicate, FnPredicateOps};
855    ///
856    /// let is_positive = |x: &i32| *x > 0;
857    /// let is_even = |x: &i32| x % 2 == 0;
858    ///
859    /// let nor = is_positive.nor(is_even);
860    /// assert!(nor.test(&-3));   // !(false || false) = true
861    /// assert!(!nor.test(&4));   // !(true || true) = false
862    /// assert!(!nor.test(&3));   // !(true || false) = false
863    /// ```
864    fn nor<P>(self, other: P) -> BoxPredicate<T>
865    where
866        Self: 'static,
867        P: Predicate<T> + 'static,
868        T: 'static,
869    {
870        BoxPredicate::new(move |value: &T| !(self.test(value) || other.test(value)))
871    }
872}
873
874// Blanket implementation for all closures
875impl<T, F> FnPredicateOps<T> for F where F: Fn(&T) -> bool {}