prism3_function/
comparator.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Comparator Abstraction
10//!
11//! Provides a Rust implementation similar to Java's `Comparator` interface
12//! for comparison operations and chaining.
13//!
14//! ## Design Overview
15//!
16//! This module adopts the **Trait + Multiple Implementations** design
17//! pattern, which is the most flexible and elegant approach for
18//! implementing comparators in Rust. It achieves a perfect balance
19//! between semantic clarity, type safety, and API flexibility.
20//!
21//! ### Core Components
22//!
23//! 1. **`Comparator<T>` trait**: A minimalist unified interface that only
24//!    defines the core `compare` method and type conversion methods
25//!    (`into_*`). It does NOT include chaining methods like
26//!    `then_comparing`, etc.
27//!
28//! 2. **Three Concrete Struct Implementations**:
29//!    - [`BoxComparator<T>`]: Box-based single ownership implementation
30//!      for one-time use scenarios
31//!    - [`ArcComparator<T>`]: Arc-based thread-safe shared ownership
32//!      implementation for multi-threaded scenarios
33//!    - [`RcComparator<T>`]: Rc-based single-threaded shared ownership
34//!      implementation for single-threaded reuse
35//!
36//! 3. **Specialized Composition Methods**: Each struct implements its own
37//!    inherent methods (`reversed`, `then_comparing`, etc.) that return
38//!    the same concrete type, preserving their specific characteristics
39//!    (e.g., `ArcComparator` compositions remain `ArcComparator` and stay
40//!    cloneable and thread-safe).
41//!
42//! 4. **Extension Trait for Closures**: The `FnComparatorOps<T>`
43//!    extension trait provides composition methods for all closures and
44//!    function pointers, returning `BoxComparator<T>` to initiate method
45//!    chaining.
46//!
47//! 5. **Unified Trait Implementation**: All closures and the three
48//!    structs implement the `Comparator<T>` trait, enabling them to be
49//!    handled uniformly by generic functions.
50//!
51//! ## Ownership Model Coverage
52//!
53//! The three implementations correspond to three typical ownership
54//! scenarios:
55//!
56//! | Type | Ownership | Clonable | Thread-Safe | API | Use Case |
57//! |:-----|:----------|:---------|:------------|:----|:---------|
58//! | [`BoxComparator`] | Single | ❌ | ❌ | consumes `self` | One-time |
59//! | [`ArcComparator`] | Shared | ✅ | ✅ | borrows `&self` | Multi-thread |
60//! | [`RcComparator`] | Shared | ✅ | ❌ | borrows `&self` | Single-thread |
61//!
62//! ## Key Design Advantages
63//!
64//! ### 1. Type Preservation through Specialization
65//!
66//! By implementing composition methods on concrete structs rather than in
67//! the trait, each type maintains its specific characteristics through
68//! composition:
69//!
70//! ```rust
71//! use prism3_function::comparator::{Comparator, ArcComparator};
72//! use std::cmp::Ordering;
73//!
74//! let arc_cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
75//! let another = ArcComparator::new(|a: &i32, b: &i32| b.cmp(a));
76//!
77//! // Composition returns ArcComparator, preserving clonability and
78//! // thread-safety
79//! let combined = arc_cmp.then_comparing(&another);
80//! let cloned = combined.clone();  // ✅ Still cloneable
81//!
82//! // Original comparators remain usable
83//! assert_eq!(arc_cmp.compare(&5, &3), Ordering::Greater);
84//! ```
85//!
86//! ### 2. Elegant API without Explicit Cloning
87//!
88//! `ArcComparator` and `RcComparator` use `&self` in their composition
89//! methods, providing a natural experience without requiring explicit
90//! `.clone()` calls:
91//!
92//! ```rust
93//! use prism3_function::comparator::{Comparator, ArcComparator};
94//!
95//! let cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
96//!
97//! // No need for explicit clone()
98//! let reversed = cmp.reversed();
99//! let chained = cmp.then_comparing(&ArcComparator::new(|a, b| b.cmp(a)));
100//!
101//! // cmp is still available
102//! cmp.compare(&1, &2);
103//! ```
104//!
105//! ### 3. Efficient Closure Composition
106//!
107//! The `FnComparatorOps` extension trait allows direct composition on
108//! closures:
109//!
110//! ```rust
111//! use prism3_function::comparator::{Comparator, FnComparatorOps};
112//! use std::cmp::Ordering;
113//!
114//! let cmp = (|a: &i32, b: &i32| a.cmp(b))
115//!     .reversed()
116//!     .then_comparing(|a: &i32, b: &i32| b.cmp(a));
117//!
118//! assert_eq!(cmp.compare(&5, &3), Ordering::Less);
119//! ```
120//!
121//! ## Usage Examples
122//!
123//! ### Basic Comparison
124//!
125//! ```rust
126//! use prism3_function::comparator::{Comparator, BoxComparator};
127//! use std::cmp::Ordering;
128//!
129//! let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
130//! assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
131//! ```
132//!
133//! ### Reversed Comparison
134//!
135//! ```rust
136//! use prism3_function::comparator::{Comparator, BoxComparator};
137//! use std::cmp::Ordering;
138//!
139//! let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
140//! let rev = cmp.reversed();
141//! assert_eq!(rev.compare(&5, &3), Ordering::Less);
142//! ```
143//!
144//! ### Chained Comparison
145//!
146//! ```rust
147//! use prism3_function::comparator::{Comparator, BoxComparator};
148//! use std::cmp::Ordering;
149//!
150//! #[derive(Debug)]
151//! struct Person {
152//!     name: String,
153//!     age: i32,
154//! }
155//!
156//! let by_name = BoxComparator::new(|a: &Person, b: &Person| {
157//!     a.name.cmp(&b.name)
158//! });
159//! let by_age = BoxComparator::new(|a: &Person, b: &Person| {
160//!     a.age.cmp(&b.age)
161//! });
162//! let cmp = by_name.then_comparing(by_age);
163//!
164//! let p1 = Person { name: "Alice".to_string(), age: 30 };
165//! let p2 = Person { name: "Alice".to_string(), age: 25 };
166//! assert_eq!(cmp.compare(&p1, &p2), Ordering::Greater);
167//! ```
168//!
169//! ## Author
170//!
171//! Haixing Hu
172
173use std::cmp::Ordering;
174use std::rc::Rc;
175use std::sync::Arc;
176
177// ==========================================================================
178// Type Aliases
179// ==========================================================================
180
181/// Type alias for comparator function signature.
182type ComparatorFn<T> = dyn Fn(&T, &T) -> Ordering;
183
184/// Type alias for thread-safe comparator function signature.
185type ThreadSafeComparatorFn<T> = dyn Fn(&T, &T) -> Ordering + Send + Sync;
186
187/// A trait for comparison operations.
188///
189/// This trait defines the core comparison operation and conversion methods.
190/// It does NOT include composition methods like `reversed` or
191/// `then_comparing` to maintain a clean separation between the trait
192/// interface and specialized implementations.
193///
194/// # Type Parameters
195///
196/// * `T` - The type of values being compared
197///
198/// # Examples
199///
200/// ```rust
201/// use prism3_function::comparator::{Comparator, BoxComparator};
202/// use std::cmp::Ordering;
203///
204/// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
205/// assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
206/// ```
207///
208/// # Author
209///
210/// Haixing Hu
211pub trait Comparator<T> {
212    /// Compares two values and returns an ordering.
213    ///
214    /// # Parameters
215    ///
216    /// * `a` - The first value to compare
217    /// * `b` - The second value to compare
218    ///
219    /// # Returns
220    ///
221    /// An `Ordering` indicating whether `a` is less than, equal to, or
222    /// greater than `b`.
223    ///
224    /// # Examples
225    ///
226    /// ```rust
227    /// use prism3_function::comparator::{Comparator, BoxComparator};
228    /// use std::cmp::Ordering;
229    ///
230    /// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
231    /// assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
232    /// assert_eq!(cmp.compare(&3, &5), Ordering::Less);
233    /// assert_eq!(cmp.compare(&5, &5), Ordering::Equal);
234    /// ```
235    fn compare(&self, a: &T, b: &T) -> Ordering;
236
237    /// Converts this comparator into a `BoxComparator`.
238    ///
239    /// # Returns
240    ///
241    /// A new `BoxComparator` wrapping this comparator.
242    ///
243    /// # Examples
244    ///
245    /// ```rust
246    /// use prism3_function::comparator::{Comparator, BoxComparator};
247    ///
248    /// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
249    /// let boxed = cmp.into_box();
250    /// ```
251    fn into_box(self) -> BoxComparator<T>
252    where
253        Self: Sized + 'static,
254        T: 'static,
255    {
256        BoxComparator::new(move |a, b| self.compare(a, b))
257    }
258
259    /// Converts this comparator into an `ArcComparator`.
260    ///
261    /// # Returns
262    ///
263    /// A new `ArcComparator` wrapping this comparator.
264    ///
265    /// # Examples
266    ///
267    /// ```rust
268    /// use prism3_function::comparator::{Comparator, ArcComparator};
269    ///
270    /// let cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
271    /// let arc = cmp.into_arc();
272    /// ```
273    fn into_arc(self) -> ArcComparator<T>
274    where
275        Self: Sized + Send + Sync + 'static,
276        T: 'static,
277    {
278        ArcComparator::new(move |a, b| self.compare(a, b))
279    }
280
281    /// Converts this comparator into an `RcComparator`.
282    ///
283    /// # Returns
284    ///
285    /// A new `RcComparator` wrapping this comparator.
286    ///
287    /// # Examples
288    ///
289    /// ```rust
290    /// use prism3_function::comparator::{Comparator, RcComparator};
291    ///
292    /// let cmp = RcComparator::new(|a: &i32, b: &i32| a.cmp(b));
293    /// let rc = cmp.into_rc();
294    /// ```
295    fn into_rc(self) -> RcComparator<T>
296    where
297        Self: Sized + 'static,
298        T: 'static,
299    {
300        RcComparator::new(move |a, b| self.compare(a, b))
301    }
302
303    /// Converts this comparator into a closure that implements
304    /// `Fn(&T, &T) -> Ordering`.
305    ///
306    /// This method consumes the comparator and returns a closure that
307    /// can be used anywhere a function or closure is expected.
308    ///
309    /// # Returns
310    ///
311    /// An implementation that can be called as `Fn(&T, &T) -> Ordering`.
312    ///
313    /// # Examples
314    ///
315    /// ```rust
316    /// use prism3_function::comparator::{Comparator, BoxComparator};
317    /// use std::cmp::Ordering;
318    ///
319    /// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
320    /// let func = cmp.into_fn();
321    /// assert_eq!(func(&5, &3), Ordering::Greater);
322    /// ```
323    fn into_fn(self) -> impl Fn(&T, &T) -> Ordering
324    where
325        Self: Sized + 'static,
326        T: 'static,
327    {
328        move |a: &T, b: &T| self.compare(a, b)
329    }
330}
331
332/// Blanket implementation of `Comparator` for all closures and function
333/// pointers.
334///
335/// This allows any closure or function with the signature
336/// `Fn(&T, &T) -> Ordering` to be used as a comparator.
337///
338/// # Examples
339///
340/// ```rust
341/// use prism3_function::comparator::Comparator;
342/// use std::cmp::Ordering;
343///
344/// let cmp = |a: &i32, b: &i32| a.cmp(b);
345/// assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
346/// ```
347impl<T, F> Comparator<T> for F
348where
349    F: Fn(&T, &T) -> Ordering,
350{
351    fn compare(&self, a: &T, b: &T) -> Ordering {
352        self(a, b)
353    }
354}
355
356/// A boxed comparator with single ownership.
357///
358/// `BoxComparator` wraps a comparator function in a `Box`, providing single
359/// ownership semantics. It is not cloneable and consumes `self` in
360/// composition operations.
361///
362/// # Type Parameters
363///
364/// * `T` - The type of values being compared
365///
366/// # Examples
367///
368/// ```rust
369/// use prism3_function::comparator::{Comparator, BoxComparator};
370/// use std::cmp::Ordering;
371///
372/// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
373/// assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
374/// ```
375///
376/// # Author
377///
378/// Haixing Hu
379pub struct BoxComparator<T> {
380    function: Box<ComparatorFn<T>>,
381}
382
383impl<T: 'static> BoxComparator<T> {
384    /// Creates a new `BoxComparator` from a closure.
385    ///
386    /// # Parameters
387    ///
388    /// * `f` - The closure to wrap
389    ///
390    /// # Returns
391    ///
392    /// A new `BoxComparator` instance.
393    ///
394    /// # Examples
395    ///
396    /// ```rust
397    /// use prism3_function::comparator::BoxComparator;
398    ///
399    /// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
400    /// ```
401    pub fn new<F>(f: F) -> Self
402    where
403        F: Fn(&T, &T) -> Ordering + 'static,
404    {
405        Self {
406            function: Box::new(f),
407        }
408    }
409
410    /// Returns a comparator that imposes the reverse ordering.
411    ///
412    /// # Returns
413    ///
414    /// A new `BoxComparator` that reverses the comparison order.
415    ///
416    /// # Examples
417    ///
418    /// ```rust
419    /// use prism3_function::comparator::{Comparator, BoxComparator};
420    /// use std::cmp::Ordering;
421    ///
422    /// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
423    /// let rev = cmp.reversed();
424    /// assert_eq!(rev.compare(&5, &3), Ordering::Less);
425    /// ```
426    pub fn reversed(self) -> Self {
427        BoxComparator::new(move |a, b| (self.function)(b, a))
428    }
429
430    /// Returns a comparator that uses this comparator first, then another
431    /// comparator if this one considers the values equal.
432    ///
433    /// # Parameters
434    ///
435    /// * `other` - The comparator to use for tie-breaking. **Note: This
436    ///   parameter is passed by value and will transfer ownership.** If you
437    ///   need to preserve the original comparator, clone it first (if it
438    ///   implements `Clone`). Can be:
439    ///   - A `BoxComparator<T>`
440    ///   - An `RcComparator<T>`
441    ///   - An `ArcComparator<T>`
442    ///   - Any type implementing `Comparator<T>`
443    ///
444    /// # Returns
445    ///
446    /// A new `BoxComparator` that chains this comparator with another.
447    ///
448    /// # Examples
449    ///
450    /// ```rust
451    /// use prism3_function::comparator::{Comparator, BoxComparator};
452    /// use std::cmp::Ordering;
453    ///
454    /// #[derive(Debug)]
455    /// struct Person {
456    ///     name: String,
457    ///     age: i32,
458    /// }
459    ///
460    /// let by_name = BoxComparator::new(|a: &Person, b: &Person| {
461    ///     a.name.cmp(&b.name)
462    /// });
463    /// let by_age = BoxComparator::new(|a: &Person, b: &Person| {
464    ///     a.age.cmp(&b.age)
465    /// });
466    ///
467    /// // by_age is moved here
468    /// let cmp = by_name.then_comparing(by_age);
469    ///
470    /// let p1 = Person { name: "Alice".to_string(), age: 30 };
471    /// let p2 = Person { name: "Alice".to_string(), age: 25 };
472    /// assert_eq!(cmp.compare(&p1, &p2), Ordering::Greater);
473    /// // by_age.compare(&p1, &p2); // Would not compile - moved
474    /// ```
475    pub fn then_comparing(self, other: Self) -> Self {
476        BoxComparator::new(move |a, b| match (self.function)(a, b) {
477            Ordering::Equal => (other.function)(a, b),
478            ord => ord,
479        })
480    }
481
482    /// Returns a comparator that compares values by a key extracted by the
483    /// given function.
484    ///
485    /// # Parameters
486    ///
487    /// * `key_fn` - A function that extracts a comparable key from values
488    ///
489    /// # Returns
490    ///
491    /// A new `BoxComparator` that compares by the extracted key.
492    ///
493    /// # Examples
494    ///
495    /// ```rust
496    /// use prism3_function::comparator::{Comparator, BoxComparator};
497    /// use std::cmp::Ordering;
498    ///
499    /// #[derive(Debug)]
500    /// struct Person {
501    ///     name: String,
502    ///     age: i32,
503    /// }
504    ///
505    /// let by_age = BoxComparator::comparing(|p: &Person| &p.age);
506    /// let p1 = Person { name: "Alice".to_string(), age: 30 };
507    /// let p2 = Person { name: "Bob".to_string(), age: 25 };
508    /// assert_eq!(by_age.compare(&p1, &p2), Ordering::Greater);
509    /// ```
510    pub fn comparing<K, F>(key_fn: F) -> Self
511    where
512        K: Ord,
513        F: Fn(&T) -> &K + 'static,
514    {
515        BoxComparator::new(move |a: &T, b: &T| key_fn(a).cmp(key_fn(b)))
516    }
517
518    /// Converts this comparator into a closure.
519    ///
520    /// # Returns
521    ///
522    /// A closure that implements `Fn(&T, &T) -> Ordering`.
523    ///
524    /// # Examples
525    ///
526    /// ```rust
527    /// use prism3_function::comparator::{Comparator, BoxComparator};
528    /// use std::cmp::Ordering;
529    ///
530    /// let cmp = BoxComparator::new(|a: &i32, b: &i32| a.cmp(b));
531    /// let func = cmp.into_fn();
532    /// assert_eq!(func(&5, &3), Ordering::Greater);
533    /// ```
534    pub fn into_fn(self) -> impl Fn(&T, &T) -> Ordering {
535        move |a: &T, b: &T| (self.function)(a, b)
536    }
537}
538
539impl<T> Comparator<T> for BoxComparator<T> {
540    fn compare(&self, a: &T, b: &T) -> Ordering {
541        (self.function)(a, b)
542    }
543}
544
545/// An Arc-based thread-safe comparator with shared ownership.
546///
547/// `ArcComparator` wraps a comparator function in an `Arc`, providing
548/// thread-safe shared ownership semantics. It is cloneable and uses `&self`
549/// in composition operations.
550///
551/// # Type Parameters
552///
553/// * `T` - The type of values being compared
554///
555/// # Examples
556///
557/// ```rust
558/// use prism3_function::comparator::{Comparator, ArcComparator};
559/// use std::cmp::Ordering;
560///
561/// let cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
562/// let cloned = cmp.clone();
563/// assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
564/// assert_eq!(cloned.compare(&5, &3), Ordering::Greater);
565/// ```
566///
567/// # Author
568///
569/// Haixing Hu
570#[derive(Clone)]
571pub struct ArcComparator<T> {
572    function: Arc<ThreadSafeComparatorFn<T>>,
573}
574
575impl<T: 'static> ArcComparator<T> {
576    /// Creates a new `ArcComparator` from a closure.
577    ///
578    /// # Parameters
579    ///
580    /// * `f` - The closure to wrap
581    ///
582    /// # Returns
583    ///
584    /// A new `ArcComparator` instance.
585    ///
586    /// # Examples
587    ///
588    /// ```rust
589    /// use prism3_function::comparator::ArcComparator;
590    ///
591    /// let cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
592    /// ```
593    pub fn new<F>(f: F) -> Self
594    where
595        F: Fn(&T, &T) -> Ordering + Send + Sync + 'static,
596    {
597        Self {
598            function: Arc::new(f),
599        }
600    }
601
602    /// Returns a comparator that imposes the reverse ordering.
603    ///
604    /// # Returns
605    ///
606    /// A new `ArcComparator` that reverses the comparison order.
607    ///
608    /// # Examples
609    ///
610    /// ```rust
611    /// use prism3_function::comparator::{Comparator, ArcComparator};
612    /// use std::cmp::Ordering;
613    ///
614    /// let cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
615    /// let rev = cmp.reversed();
616    /// assert_eq!(rev.compare(&5, &3), Ordering::Less);
617    /// assert_eq!(cmp.compare(&5, &3), Ordering::Greater); // cmp still works
618    /// ```
619    pub fn reversed(&self) -> Self {
620        let self_fn = self.function.clone();
621        ArcComparator::new(move |a, b| self_fn(b, a))
622    }
623
624    /// Returns a comparator that uses this comparator first, then another
625    /// comparator if this one considers the values equal.
626    ///
627    /// # Parameters
628    ///
629    /// * `other` - The comparator to use for tie-breaking
630    ///
631    /// # Returns
632    ///
633    /// A new `ArcComparator` that chains this comparator with another.
634    ///
635    /// # Examples
636    ///
637    /// ```rust
638    /// use prism3_function::comparator::{Comparator, ArcComparator};
639    /// use std::cmp::Ordering;
640    ///
641    /// let cmp1 = ArcComparator::new(|a: &i32, b: &i32| {
642    ///     (a % 2).cmp(&(b % 2))
643    /// });
644    /// let cmp2 = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
645    /// let chained = cmp1.then_comparing(&cmp2);
646    /// assert_eq!(chained.compare(&4, &2), Ordering::Greater);
647    /// ```
648    pub fn then_comparing(&self, other: &Self) -> Self {
649        let first = self.function.clone();
650        let second = other.function.clone();
651        ArcComparator::new(move |a, b| match first(a, b) {
652            Ordering::Equal => second(a, b),
653            ord => ord,
654        })
655    }
656
657    /// Returns a comparator that compares values by a key extracted by the
658    /// given function.
659    ///
660    /// # Parameters
661    ///
662    /// * `key_fn` - A function that extracts a comparable key from values
663    ///
664    /// # Returns
665    ///
666    /// A new `ArcComparator` that compares by the extracted key.
667    ///
668    /// # Examples
669    ///
670    /// ```rust
671    /// use prism3_function::comparator::{Comparator, ArcComparator};
672    /// use std::cmp::Ordering;
673    ///
674    /// #[derive(Debug)]
675    /// struct Person {
676    ///     name: String,
677    ///     age: i32,
678    /// }
679    ///
680    /// let by_age = ArcComparator::comparing(|p: &Person| &p.age);
681    /// let p1 = Person { name: "Alice".to_string(), age: 30 };
682    /// let p2 = Person { name: "Bob".to_string(), age: 25 };
683    /// assert_eq!(by_age.compare(&p1, &p2), Ordering::Greater);
684    /// ```
685    pub fn comparing<K, F>(key_fn: F) -> Self
686    where
687        K: Ord,
688        F: Fn(&T) -> &K + Send + Sync + 'static,
689    {
690        ArcComparator::new(move |a, b| key_fn(a).cmp(key_fn(b)))
691    }
692
693    /// Converts this comparator into a closure.
694    ///
695    /// # Returns
696    ///
697    /// A closure that implements `Fn(&T, &T) -> Ordering`.
698    ///
699    /// # Examples
700    ///
701    /// ```rust
702    /// use prism3_function::comparator::{Comparator, ArcComparator};
703    /// use std::cmp::Ordering;
704    ///
705    /// let cmp = ArcComparator::new(|a: &i32, b: &i32| a.cmp(b));
706    /// let func = cmp.into_fn();
707    /// assert_eq!(func(&5, &3), Ordering::Greater);
708    /// ```
709    pub fn into_fn(self) -> impl Fn(&T, &T) -> Ordering {
710        move |a: &T, b: &T| (self.function)(a, b)
711    }
712}
713
714impl<T> Comparator<T> for ArcComparator<T> {
715    fn compare(&self, a: &T, b: &T) -> Ordering {
716        (self.function)(a, b)
717    }
718}
719
720/// An Rc-based single-threaded comparator with shared ownership.
721///
722/// `RcComparator` wraps a comparator function in an `Rc`, providing
723/// single-threaded shared ownership semantics. It is cloneable and uses
724/// `&self` in composition operations.
725///
726/// # Type Parameters
727///
728/// * `T` - The type of values being compared
729///
730/// # Examples
731///
732/// ```rust
733/// use prism3_function::comparator::{Comparator, RcComparator};
734/// use std::cmp::Ordering;
735///
736/// let cmp = RcComparator::new(|a: &i32, b: &i32| a.cmp(b));
737/// let cloned = cmp.clone();
738/// assert_eq!(cmp.compare(&5, &3), Ordering::Greater);
739/// assert_eq!(cloned.compare(&5, &3), Ordering::Greater);
740/// ```
741///
742/// # Author
743///
744/// Haixing Hu
745#[derive(Clone)]
746pub struct RcComparator<T> {
747    function: Rc<ComparatorFn<T>>,
748}
749
750impl<T: 'static> RcComparator<T> {
751    /// Creates a new `RcComparator` from a closure.
752    ///
753    /// # Parameters
754    ///
755    /// * `f` - The closure to wrap
756    ///
757    /// # Returns
758    ///
759    /// A new `RcComparator` instance.
760    ///
761    /// # Examples
762    ///
763    /// ```rust
764    /// use prism3_function::comparator::RcComparator;
765    ///
766    /// let cmp = RcComparator::new(|a: &i32, b: &i32| a.cmp(b));
767    /// ```
768    pub fn new<F>(f: F) -> Self
769    where
770        F: Fn(&T, &T) -> Ordering + 'static,
771    {
772        Self {
773            function: Rc::new(f),
774        }
775    }
776
777    /// Returns a comparator that imposes the reverse ordering.
778    ///
779    /// # Returns
780    ///
781    /// A new `RcComparator` that reverses the comparison order.
782    ///
783    /// # Examples
784    ///
785    /// ```rust
786    /// use prism3_function::comparator::{Comparator, RcComparator};
787    /// use std::cmp::Ordering;
788    ///
789    /// let cmp = RcComparator::new(|a: &i32, b: &i32| a.cmp(b));
790    /// let rev = cmp.reversed();
791    /// assert_eq!(rev.compare(&5, &3), Ordering::Less);
792    /// assert_eq!(cmp.compare(&5, &3), Ordering::Greater); // cmp still works
793    /// ```
794    pub fn reversed(&self) -> Self {
795        let self_fn = self.function.clone();
796        RcComparator::new(move |a, b| self_fn(b, a))
797    }
798
799    /// Returns a comparator that uses this comparator first, then another
800    /// comparator if this one considers the values equal.
801    ///
802    /// # Parameters
803    ///
804    /// * `other` - The comparator to use for tie-breaking
805    ///
806    /// # Returns
807    ///
808    /// A new `RcComparator` that chains this comparator with another.
809    ///
810    /// # Examples
811    ///
812    /// ```rust
813    /// use prism3_function::comparator::{Comparator, RcComparator};
814    /// use std::cmp::Ordering;
815    ///
816    /// let cmp1 = RcComparator::new(|a: &i32, b: &i32| {
817    ///     (a % 2).cmp(&(b % 2))
818    /// });
819    /// let cmp2 = RcComparator::new(|a: &i32, b: &i32| a.cmp(b));
820    /// let chained = cmp1.then_comparing(&cmp2);
821    /// assert_eq!(chained.compare(&4, &2), Ordering::Greater);
822    /// ```
823    pub fn then_comparing(&self, other: &Self) -> Self {
824        let first = self.function.clone();
825        let second = other.function.clone();
826        RcComparator::new(move |a, b| match first(a, b) {
827            Ordering::Equal => second(a, b),
828            ord => ord,
829        })
830    }
831
832    /// Returns a comparator that compares values by a key extracted by the
833    /// given function.
834    ///
835    /// # Parameters
836    ///
837    /// * `key_fn` - A function that extracts a comparable key from values
838    ///
839    /// # Returns
840    ///
841    /// A new `RcComparator` that compares by the extracted key.
842    ///
843    /// # Examples
844    ///
845    /// ```rust
846    /// use prism3_function::comparator::{Comparator, RcComparator};
847    /// use std::cmp::Ordering;
848    ///
849    /// #[derive(Debug)]
850    /// struct Person {
851    ///     name: String,
852    ///     age: i32,
853    /// }
854    ///
855    /// let by_age = RcComparator::comparing(|p: &Person| &p.age);
856    /// let p1 = Person { name: "Alice".to_string(), age: 30 };
857    /// let p2 = Person { name: "Bob".to_string(), age: 25 };
858    /// assert_eq!(by_age.compare(&p1, &p2), Ordering::Greater);
859    /// ```
860    pub fn comparing<K, F>(key_fn: F) -> Self
861    where
862        K: Ord,
863        F: Fn(&T) -> &K + 'static,
864    {
865        RcComparator::new(move |a, b| key_fn(a).cmp(key_fn(b)))
866    }
867
868    /// Converts this comparator into a closure.
869    ///
870    /// # Returns
871    ///
872    /// A closure that implements `Fn(&T, &T) -> Ordering`.
873    ///
874    /// # Examples
875    ///
876    /// ```rust
877    /// use prism3_function::comparator::{Comparator, RcComparator};
878    /// use std::cmp::Ordering;
879    ///
880    /// let cmp = RcComparator::new(|a: &i32, b: &i32| a.cmp(b));
881    /// let func = cmp.into_fn();
882    /// assert_eq!(func(&5, &3), Ordering::Greater);
883    /// ```
884    pub fn into_fn(self) -> impl Fn(&T, &T) -> Ordering {
885        move |a: &T, b: &T| (self.function)(a, b)
886    }
887}
888
889impl<T> Comparator<T> for RcComparator<T> {
890    fn compare(&self, a: &T, b: &T) -> Ordering {
891        (self.function)(a, b)
892    }
893}
894
895/// Extension trait providing composition methods for closures and function
896/// pointers.
897///
898/// This trait is automatically implemented for all closures and function
899/// pointers with the signature `Fn(&T, &T) -> Ordering`, allowing them to
900/// be composed directly without explicit wrapping.
901///
902/// # Examples
903///
904/// ```rust
905/// use prism3_function::comparator::{Comparator, FnComparatorOps};
906/// use std::cmp::Ordering;
907///
908/// let cmp = (|a: &i32, b: &i32| a.cmp(b))
909///     .reversed()
910///     .then_comparing(BoxComparator::new(|a, b| b.cmp(a)));
911///
912/// assert_eq!(cmp.compare(&5, &3), Ordering::Less);
913/// ```
914///
915/// # Author
916///
917/// Haixing Hu
918pub trait FnComparatorOps<T>: Fn(&T, &T) -> Ordering + Sized {
919    /// Returns a comparator that imposes the reverse ordering.
920    ///
921    /// # Returns
922    ///
923    /// A new `BoxComparator` that reverses the comparison order.
924    ///
925    /// # Examples
926    ///
927    /// ```rust
928    /// use prism3_function::comparator::{Comparator, FnComparatorOps};
929    /// use std::cmp::Ordering;
930    ///
931    /// let rev = (|a: &i32, b: &i32| a.cmp(b)).reversed();
932    /// assert_eq!(rev.compare(&5, &3), Ordering::Less);
933    /// ```
934    fn reversed(self) -> BoxComparator<T>
935    where
936        Self: 'static,
937        T: 'static,
938    {
939        BoxComparator::new(self).reversed()
940    }
941
942    /// Returns a comparator that uses this comparator first, then another
943    /// comparator if this one considers the values equal.
944    ///
945    /// # Parameters
946    ///
947    /// * `other` - The comparator to use for tie-breaking
948    ///
949    /// # Returns
950    ///
951    /// A new `BoxComparator` that chains this comparator with another.
952    ///
953    /// # Examples
954    ///
955    /// ```rust
956    /// use prism3_function::comparator::{Comparator, FnComparatorOps,
957    ///                                   BoxComparator};
958    /// use std::cmp::Ordering;
959    ///
960    /// let cmp = (|a: &i32, b: &i32| (a % 2).cmp(&(b % 2)))
961    ///     .then_comparing(BoxComparator::new(|a, b| a.cmp(b)));
962    /// assert_eq!(cmp.compare(&4, &2), Ordering::Greater);
963    /// ```
964    fn then_comparing(self, other: BoxComparator<T>) -> BoxComparator<T>
965    where
966        Self: 'static,
967        T: 'static,
968    {
969        BoxComparator::new(self).then_comparing(other)
970    }
971}
972
973impl<T, F> FnComparatorOps<T> for F where F: Fn(&T, &T) -> Ordering {}