1pub trait Scorer {
2 type Context;
3
4 fn predicate_score(&self, ctx: &Self::Context, input: &str) -> u32;
5}
6
7impl<T> ScorerExt for T where T: Scorer + Sized + Send {}
8
9pub trait ScorerExt: Scorer + Sized + Send {
10 fn into_sorter(self) -> impl Sorter<Context = Self::Context>
11where {
12 ScorerSorter(self)
13 }
14
15 fn into_filter<F>(self, predicate: F) -> impl Filter<Context = Self::Context>
16 where
17 F: Fn(u32) -> bool + Send,
18 {
19 ScorerFilter(self, predicate)
20 }
21}
22
23use ltrait::Filter;
24use ltrait::Sorter;
25
26pub struct ScorerSorter<C, T>(pub T)
27where
28 T: Scorer<Context = C> + Send;
29
30impl<C, T> ScorerSorter<C, T>
31where
32 T: Scorer<Context = C> + Send,
33{
34 pub fn new(t: T) -> Self {
35 ScorerSorter(t)
36 }
37}
38
39impl<C, T> Sorter for ScorerSorter<C, T>
40where
41 T: Scorer<Context = C> + Send,
42{
43 type Context = C;
44
45 fn compare(&self, lhs: &Self::Context, rhs: &Self::Context, input: &str) -> std::cmp::Ordering {
46 self.0
47 .predicate_score(lhs, input)
48 .cmp(&self.0.predicate_score(rhs, input))
49 }
50}
51
52pub struct ScorerFilter<C, T, F>(pub T, pub F)
53where
54 T: Scorer<Context = C> + Send,
55 F: Fn(u32) -> bool;
56
57impl<C, T, F> ScorerFilter<C, T, F>
58where
59 T: Scorer<Context = C> + Send,
60 F: Fn(u32) -> bool + Send,
61{
62 pub fn new(t: T, f: F) -> Self {
63 Self(t, f)
64 }
65}
66
67impl<C, T, F> Filter for ScorerFilter<C, T, F>
68where
69 T: Scorer<Context = C> + Send,
70 F: Fn(u32) -> bool + Send,
71{
72 type Context = C;
73
74 fn predicate(&self, ctx: &Self::Context, input: &str) -> bool {
75 (self.1)(self.0.predicate_score(ctx, input))
76 }
77}