/* * Copyright 2010 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package dorkbox.serializers; import java.util.EnumSet; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** * A serializer for {@link EnumSet}s. */ @SuppressWarnings({"unchecked", "rawtypes"}) public class EnumSetSerializer extends Serializer>> { @Override public EnumSet> copy(final Kryo kryo, final EnumSet> original) { return original.clone(); } @Override public EnumSet read(final Kryo kryo, final Input input, final Class>> type) { final Class elementType = kryo.readClass(input) .getType(); final EnumSet result = EnumSet.noneOf(elementType); final int size = input.readInt(true); final Enum[] enumConstants = elementType.getEnumConstants(); for (int i = 0; i < size; i++) { result.add(enumConstants[input.readInt(true)]); } return result; } @Override public void write(final Kryo kryo, final Output output, final EnumSet> set) { if (set.isEmpty()) { EnumSet> tmp = EnumSet.complementOf(set); if (tmp.isEmpty()) throw new KryoException("An EnumSet must have a defined Enum to be serialized."); Class> type = (Class>) tmp.iterator() .next() .getDeclaringClass(); kryo.writeClass(output, type); output.writeInt(0, true); } else { Class> type = (Class>) set.iterator() .next() .getDeclaringClass(); kryo.writeClass(output, type); output.writeInt(set.size(), true); for (final Enum item : set) { output.writeInt(item.ordinal(), true); } } } }