1 | package com.hammurapi.eventbus; |
2 | |
3 | import java.io.Serializable; |
4 | import java.util.Arrays; |
5 | |
6 | /** |
7 | * Mapper maps events from one array to another. |
8 | * @author Pavel Vlasov |
9 | * |
10 | */ |
11 | public class Mapper<E> implements Serializable { |
12 | |
13 | private int[] indexMap; |
14 | |
15 | /** |
16 | * @param indexMap Array elements contain target indices. |
17 | */ |
18 | public Mapper(int[] indexMap) { |
19 | this.indexMap = indexMap; |
20 | } |
21 | |
22 | boolean mapsTo(int idx) { |
23 | for (int i=0; i<indexMap.length; ++i) { |
24 | if (idx==indexMap[i]) { |
25 | return true; |
26 | } |
27 | } |
28 | return false; |
29 | } |
30 | |
31 | public int[] getIndexMap() { |
32 | return indexMap; |
33 | } |
34 | |
35 | /** |
36 | * Maps events from input to output. |
37 | * @param input |
38 | * @param output |
39 | */ |
40 | void map(E[] input, E[] output) { |
41 | if (input!=null) { |
42 | for (int i=0; i<input.length; ++i) { |
43 | if (output.length>indexMap[i]) { |
44 | output[indexMap[i]] = input[i]; |
45 | } |
46 | } |
47 | } |
48 | } |
49 | |
50 | @Override |
51 | public int hashCode() { |
52 | final int prime = 31; |
53 | int result = 1; |
54 | result = prime * result + Arrays.hashCode(indexMap); |
55 | return result; |
56 | } |
57 | |
58 | @Override |
59 | public boolean equals(Object obj) { |
60 | if (this == obj) |
61 | return true; |
62 | if (obj == null) |
63 | return false; |
64 | if (getClass() != obj.getClass()) |
65 | return false; |
66 | Mapper other = (Mapper) obj; |
67 | if (!Arrays.equals(indexMap, other.indexMap)) |
68 | return false; |
69 | return true; |
70 | } |
71 | |
72 | @Override |
73 | public String toString() { |
74 | return "Mapper [indexMap=" + Arrays.toString(indexMap) + "]"; |
75 | } |
76 | |
77 | } |