1 | package com.hammurapi.eventbus; |
2 | |
3 | import java.util.Comparator; |
4 | |
5 | import com.hammurapi.extract.Predicate; |
6 | |
7 | /** |
8 | * Comparator to sort join predicates. |
9 | * @author Pavel Vlasov |
10 | * |
11 | * @param <E> |
12 | * @param <C> |
13 | */ |
14 | public class PredicateCostCardinalityComparator<E,C> implements Comparator<Predicate<E,C>> { |
15 | |
16 | @Override |
17 | public int compare(Predicate<E, C> p1, Predicate<E, C> p2) { |
18 | // Predicates ordered by cost first - cheaper come before more expensive |
19 | double delta = p1.getCost() - p2.getCost(); |
20 | if (delta < -Double.MIN_VALUE) { |
21 | return -1; |
22 | } |
23 | |
24 | if (delta > Double.MIN_VALUE) { |
25 | return 1; |
26 | } |
27 | |
28 | // Then by cardinality (smaller comes before greater) |
29 | // And then by first index. |
30 | int c1 = p1.parameterIndices().size(); |
31 | int c2 = p2.parameterIndices().size(); |
32 | if (c1!=c2) { |
33 | return c1 - c2; |
34 | } |
35 | |
36 | for (int i: p1.parameterIndices()) { |
37 | for (int j: p2.parameterIndices()) { |
38 | if (i!=j) { |
39 | return i-j; |
40 | } |
41 | } |
42 | } |
43 | |
44 | return p1.hashCode() - p2.hashCode(); |
45 | } |
46 | |
47 | } |