001    package com.hammurapi.eventbus;
002    
003    import java.io.Serializable;
004    import java.util.Arrays;
005    
006    /**
007     * Mapper maps events from one array to another. 
008     * @author Pavel Vlasov
009     *
010     */
011    public class Mapper<E> implements Serializable {
012            
013            private int[] indexMap;
014    
015            /**
016             * @param indexMap Array elements contain target indices.
017             */
018            public Mapper(int[] indexMap) {
019                    this.indexMap = indexMap;
020            }
021            
022            boolean mapsTo(int idx) {
023                    for (int i=0; i<indexMap.length; ++i) {
024                            if (idx==indexMap[i]) {
025                                    return true;
026                            }
027                    }
028                    return false;
029            }
030            
031            public int[] getIndexMap() {
032                    return indexMap;
033            }
034            
035            /**
036             * Maps events from input to output.
037             * @param input
038             * @param output
039             */
040            void map(E[] input, E[] output) {
041                    if (input!=null) {
042                            for (int i=0; i<input.length; ++i) {
043                                    if (output.length>indexMap[i]) {
044                                            output[indexMap[i]] = input[i];
045                                    }
046                            }
047                    }
048            }
049    
050            @Override
051            public int hashCode() {
052                    final int prime = 31;
053                    int result = 1;
054                    result = prime * result + Arrays.hashCode(indexMap);
055                    return result;
056            }
057    
058            @Override
059            public boolean equals(Object obj) {
060                    if (this == obj)
061                            return true;
062                    if (obj == null)
063                            return false;
064                    if (getClass() != obj.getClass())
065                            return false;
066                    Mapper other = (Mapper) obj;
067                    if (!Arrays.equals(indexMap, other.indexMap))
068                            return false;
069                    return true;
070            }
071    
072            @Override
073            public String toString() {
074                    return "Mapper [indexMap=" + Arrays.toString(indexMap) + "]";
075            }               
076    
077    }