From b4c8b3fda8b36af133ac218f7c278c3f35917a9b Mon Sep 17 00:00:00 2001 From: "ray.j.greenwell" Date: Mon, 1 Mar 2010 20:17:26 +0000 Subject: [PATCH] Added setToInt() and intToSet(), for turning a Set into an encoded form for storing in a database or otherwise persisting into an int. It would be snazzy if Depot could do this automatically if a PersistentRecord contained a Set & ByteEnum>. git-svn-id: https://samskivert.googlecode.com/svn/trunk@2751 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../com/samskivert/util/ByteEnumUtil.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/java/com/samskivert/util/ByteEnumUtil.java b/src/java/com/samskivert/util/ByteEnumUtil.java index c02367a8..fdd8a723 100644 --- a/src/java/com/samskivert/util/ByteEnumUtil.java +++ b/src/java/com/samskivert/util/ByteEnumUtil.java @@ -20,6 +20,9 @@ package com.samskivert.util; +import java.util.EnumSet; +import java.util.Set; + /** * {@link ByteEnum} utility methods. */ @@ -40,4 +43,48 @@ public class ByteEnumUtil } throw new IllegalArgumentException(eclass + " has no value with code " + code); } + + /** + * Convert a Set of ByteEnums into an integer compactly representing the elements that are + * included. + */ + public static & ByteEnum> int setToInt (Set set) + { + int flags = 0; + for (E value : set) { + flags |= (1 << toIntFlag(value)); + } + return flags; + } + + /** + * Convert an int representation of ByteEnum flags into an EnumSet. + */ + public static & ByteEnum> EnumSet intToSet (Class eclass, int flags) + { + EnumSet set = EnumSet.noneOf(eclass); + for (E value : eclass.getEnumConstants()) { + if ((flags & (1 << toIntFlag(value))) != 0) { + set.add(value); + } + } + return set; + } + + /** + * A helper function for setToInt() and intToSet() that validates that the specified + * ByteEnum value is not null and has a code between 0 and 31, inclusive. + */ + protected static & ByteEnum> byte toIntFlag (E value) + { + byte code = value.toByte(); // allow this to throw NPE + if (code < 0 || code > 31) { + throw new IllegalArgumentException( + "ByteEnum code is outside the range that can be turned into an int " + + "[value=" + value + ", code=" + code + "]"); + } + return code; + } + + // TODO: setToByteArray() and byteArrayToSet(), for larger ByteEnums? }