package au.com.southsky.jfreesane;

import java.util.Map;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

/**
 * Utilities for dealing with instances of {@link SaneEnum}.
 * 
 * @author James Ring (sjr@jdns.org)
 */
public class SaneEnums {
	private static Map<Class<?>, Map<Integer, ?>> cachedTypeMaps = Maps
			.newHashMap();

	// no public constructor
	private SaneEnums() {
	}

	@SuppressWarnings("unchecked")
	private static synchronized <T extends Enum<T> & SaneEnum> Map<Integer, T> mapForType(
			Class<T> enumType) {
		if (cachedTypeMaps.containsKey(enumType)) {
			return (Map<Integer, T>) cachedTypeMaps.get(enumType);
		}

		ImmutableMap.Builder<Integer, T> mapBuilder = ImmutableMap.builder();

		for (T value : enumType.getEnumConstants()) {
			mapBuilder.put(value.getWireValue(), value);
		}

		Map<Integer, T> result = mapBuilder.build();

		cachedTypeMaps.put(enumType, result);
		return result;
	}

	public static <T extends Enum<T> & SaneEnum> T valueOf(Class<T> enumType,
			int valueType) {
		return mapForType(enumType).get(valueType);
	}
}

@@ -46,19 +46,64 @@
 va.util.
-Map
+List;%0Aimport java.util.Map;%0Aimport java.util.Set
 ;%0A%0Aimpor
@@ -177,19 +177,98 @@
 collect.
-Map
+Lists;%0Aimport com.google.common.collect.Maps;%0Aimport com.google.common.collect.Set
 s;%0A%0A/**%0A
@@ -1075,16 +1075,1086 @@
 lt;%0A%09%7D%0A%0A
+%09/**%0A%09 * Returns a set of %7B@code T%7D obtained by treating %7B@code wireValue%7D as a%0A%09 * bit vector whose bits represent the wire values of the enum constants of%0A%09 * the given %7B@code enumType%7D.%0A%09 */%0A%09public static %3CT extends Enum%3CT%3E & SaneEnum%3E Set%3CT%3E enumSet(%0A%09%09%09Class%3CT%3E enumType, int wireValue) %7B%0A%09%09T%5B%5D enumConstants = enumType.getEnumConstants();%0A%09%09List%3CT%3E values = Lists.newArrayListWithCapacity(enumConstants.length);%0A%0A%09%09for (T value : enumType.getEnumConstants()) %7B%0A%09%09%09if ((wireValue & value.getWireValue()) != 0) %7B%0A%09%09%09%09values.add(value);%0A%09%09%09%7D%0A%09%09%7D%0A%0A%09%09return Sets.immutableEnumSet(values);%0A%09%7D%0A%0A%09/**%0A%09 * Returns the result of bitwise-ORing the wire values of the given%0A%09 * %7B@code SaneEnum%7D set. This method does not check to make sure the result%0A%09 * is sensible: the caller must ensure that the set contains members whose%0A%09 * wire values can be ORed together in a logically correct fashion.%0A%09 */%0A%09public static %3CT extends SaneEnum%3E int wireValue(Set%3CT%3E values) %7B%0A%09%09int result = 0;%0A%0A%09%09for (T value : values) %7B%0A%09%09%09result %7C= value.getWireValue();%0A%09%09%7D%0A%0A%09%09return result;%0A%09%7D%0A%0A
 %09public 

Add helper methods for dealing with bit vectors