79 lines
2.8 KiB
Java
79 lines
2.8 KiB
Java
/*
|
|
* 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<EnumSet<? extends Enum<?>>> {
|
|
|
|
@Override
|
|
public
|
|
EnumSet<? extends Enum<?>> copy(final Kryo kryo, final EnumSet<? extends Enum<?>> original) {
|
|
return original.clone();
|
|
}
|
|
|
|
@Override
|
|
public
|
|
EnumSet read(final Kryo kryo, final Input input, final Class<? extends EnumSet<? extends Enum<?>>> type) {
|
|
final Class<Enum> 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<? extends Enum<?>> set) {
|
|
if (set.isEmpty()) {
|
|
EnumSet<? extends Enum<?>> tmp = EnumSet.complementOf(set);
|
|
if (tmp.isEmpty()) throw new KryoException("An EnumSet must have a defined Enum to be serialized.");
|
|
Class<Enum<?>> type = (Class<Enum<?>>) tmp.iterator()
|
|
.next()
|
|
.getDeclaringClass();
|
|
kryo.writeClass(output, type);
|
|
output.writeInt(0, true);
|
|
}
|
|
else {
|
|
Class<Enum<?>> type = (Class<Enum<?>>) set.iterator()
|
|
.next()
|
|
.getDeclaringClass();
|
|
kryo.writeClass(output, type);
|
|
output.writeInt(set.size(), true);
|
|
|
|
for (final Enum item : set) {
|
|
output.writeInt(item.ordinal(), true);
|
|
}
|
|
}
|
|
}
|
|
}
|