package com.telenav.tnt.benchmark.serialization;
import com.telenav.tnt.benchmark.data.Gps;
import org.msgpack.MessagePack;
import org.msgpack.template.ObjectArrayTemplate;
import org.msgpack.template.Template;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
public class MsgpackSerializer implements Serializer {
private final MessagePack messagePack;
private final Map<Class, Template> templates = new HashMap<Class, Template>();
public MsgpackSerializer() {
messagePack = new MessagePack();
messagePack.register(Gps[].class, new ObjectArrayTemplate(Gps.class, messagePack.lookup(Gps.class)));
}
public String getName() {
return "Msgpack";
}
public void serialize(Object data, OutputStream outputStream) throws Exception {
Template template = getTemplate(data.getClass());
messagePack.write(outputStream, data, template);
}
public Object deserialize(Class clazz, InputStream inputStream) throws Exception {
Template template = getTemplate(clazz);
return messagePack.read(inputStream, template);
}
private Template getTemplate(Class clazz) {
Template template = templates.get(clazz);
if (template == null) {
if (clazz.isArray()) {
template = new ObjectArrayTemplate(clazz.getComponentType(), messagePack.lookup(clazz.getComponentType()));
} else {
template = messagePack.lookup(clazz);
}
templates.put(clazz, template);
}
return template;
}
}