1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
/* Glazed Lists (c) 2003-2006 */
/* http://publicobject.com/glazedlists/ publicobject.com,*/
/* O'Dell Engineering Ltd.*/
package ca.odell.glazedlists.impl.adt.barcode2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Try to make conversions and color operations as efficient as possible
* by using bytes as values rather than full-size objects. This exploits
* a limitation that there's at most 8 possible values in the list of colors.
*
* @author <a href="mailto:jesse@swank.ca">Jesse Wilson</a>
*/
public class ListToByteCoder<C> {
private final List<C> allColors;
private final int colorCount;
public ListToByteCoder(List<C> allColors) {
if(allColors.size() > 7) throw new IllegalArgumentException("Max 7 colors!");
this.allColors = Collections.unmodifiableList(new ArrayList<C>(allColors));
this.colorCount = this.allColors.size();
}
/**
* List the colors encoded by this coder.
*/
public List<C> getColors() {
return allColors;
}
/**
* Encode the specified list of colors into a byte.
*/
public byte colorsToByte(List<C> colors) {
int result = 0;
for(int i = 0; i < colors.size(); i++) {
C color = colors.get(i);
int index = allColors.indexOf(color);
result = result | (1 << index);
}
return (byte)result;
}
/**
* Encode the specified color into a byte.
*/
public byte colorToByte(C color) {
int index = allColors.indexOf(color);
int result = (1 << index);
return (byte)result;
}
/**
* Decode the specified byte into a color.
*/
public C byteToColor(byte encoded) {
for(int i = 0; i < colorCount; i++) {
if(((1 << i) & encoded) > 0) return allColors.get(i);
}
throw new IllegalStateException();
}
/**
* Decode the specified bytes into colors.
*/
public List<C> byteToColors(byte encoded) {
List<C> result = new ArrayList<C>(colorCount);
for(int i = 0; i < colorCount; i++) {
if(((1 << i) & encoded) > 0) result.add(allColors.get(i));
}
return result;
}
}
|