1 | package com.hammurapi.extract; |
2 | |
3 | import java.util.Collections; |
4 | import java.util.Map; |
5 | import java.util.Set; |
6 | |
7 | import com.hammurapi.extract.ComparisonResult.Type; |
8 | |
9 | /** |
10 | * Extracts value at index. |
11 | * @author Pavel Vlasov. |
12 | * |
13 | * @param <T> |
14 | */ |
15 | public class IndexedExtractor<T, C> implements Extractor<T, T, C>, Mappable<T,T,C> { |
16 | |
17 | private int idx; |
18 | |
19 | public IndexedExtractor(int idx) { |
20 | this.idx = idx; |
21 | } |
22 | |
23 | public Set<Integer> parameterIndices() { |
24 | return Collections.singleton(idx); |
25 | } |
26 | |
27 | @Override |
28 | public int hashCode() { |
29 | final int prime = 31; |
30 | int result = 1; |
31 | result = prime * result + idx; |
32 | return result; |
33 | } |
34 | |
35 | @SuppressWarnings("unchecked") |
36 | @Override |
37 | public boolean equals(Object obj) { |
38 | if (this == obj) |
39 | return true; |
40 | if (obj == null) |
41 | return false; |
42 | if (getClass() != obj.getClass()) |
43 | return false; |
44 | IndexedExtractor other = (IndexedExtractor) obj; |
45 | if (idx != other.idx) |
46 | return false; |
47 | return true; |
48 | } |
49 | |
50 | |
51 | public T extract(C context, Map<C, Map<Extractor<T, ? super T, C>, ? super T>> cache, T... obj) { |
52 | return obj[idx]; |
53 | } |
54 | |
55 | public boolean isContextDependent() { |
56 | return false; |
57 | } |
58 | |
59 | @Override |
60 | public String toString() { |
61 | return "IndexedExtractor [idx=" + idx + "]"; |
62 | } |
63 | |
64 | @Override |
65 | public ComparisonResult compareTo(Extractor<T, T, C> other) { |
66 | if (other instanceof IndexedExtractor) { |
67 | int otherIdx = ((IndexedExtractor<T, C>) other).idx; |
68 | if (otherIdx==idx) { |
69 | return ComparisonResult.EQUAL_NM; |
70 | } |
71 | int[] map = new int[otherIdx+1]; |
72 | map[otherIdx]= idx; |
73 | return new ComparisonResult(Type.EQUAL, map); |
74 | } |
75 | return ComparisonResult.NOT_EQUAL_NM; |
76 | } |
77 | |
78 | @Override |
79 | public double getCost() { |
80 | return 0; |
81 | } |
82 | |
83 | @Override |
84 | public Extractor<T, T, C> map(int[] map) { |
85 | for (int i=0; i<map.length; ++i) { |
86 | if (map[i]==idx) { |
87 | return new IndexedExtractor<T, C>(i); |
88 | } |
89 | } |
90 | return null; |
91 | } |
92 | |
93 | public int getIndex() { |
94 | return idx; |
95 | } |
96 | } |