Serializing EnumSet (with little contrib)

Hi,



the default serializers do not support EnumSet. Here is a small contrib to do it ;



[java]

import com.jme3.network.serializing.Serializer;

import com.jme3.network.serializing.SerializerRegistration;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.util.EnumSet;



public class EnumSetSerializer extends Serializer {



private enum Dummy { }



public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {

int length = data.getInt();



if (length == 0) {

return (T) EnumSet.noneOf(Dummy.class);

}



SerializerRegistration reg = Serializer.readClass(data);

Class clazz = reg.getType();

Serializer serializer = reg.getSerializer();

EnumSet set = EnumSet.noneOf(clazz);

for (int i = 0; i != length; ++i) {

set.add(serializer.readObject(data, clazz));

}

return (T) set;

}



public void writeObject(ByteBuffer buffer, Object object) throws IOException {

EnumSet set = (EnumSet)object;

int length = set.size();



buffer.putInt(length);

if (length == 0) return;



Class enumClass = set.iterator().next().getClass();

Serializer.writeClass(buffer, enumClass);

Serializer serializer = Serializer.getSerializer(enumClass);

for (Object elem : set) {

serializer.writeObject(buffer, elem);

}

}

}

[/java]



To use it, perform explicit registration of it like this for each of your EnumSet (the example is for my Action enum) ;

[java]

Serializer.registerClass(Action.class, new EnumSerializer());

Serializer.registerClass(EnumSet.noneOf(Action.class).getClass(), new EnumSetSerializer());

[/java]

1 Like

Looks good. You might want to add support for a null EnumSet. A couple of the other serializers snag people this way too.



It’s really too bad that EnumSet doesn’t provide access to its internal bit set as that would be a lot more efficient to send. Though I suppose at the expense of some complexity that it could be recreated in code.

Hi, is this in the beta1 release? EnumSetSerializer doesn’t seem to be included in the jars.

If I try to serialize an EnumSet<>, I getting the following error:

	at com.jme3.network.serializing.Serializer.writeClassAndObject(Serializer.java:440)
	at com.jme3.network.serializing.serializers.FieldSerializer.writeObject(FieldSerializer.java:204)
	... 9 more```

You have to take the contribution as provided and include it in your own project. I don’t think it was ever added to core… at least I don’t think I ever saw a patch.