Skip to main content

qubit_function/predicates/
bi_predicate.rs

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