Created
April 29, 2012 01:00
-
-
Save shrijeet/2523029 to your computer and use it in GitHub Desktop.
A Protobuffer implementation of com.esotericsoftware.kryo.Serializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class PBSerialize<T extends Message> extends | |
Serializer { | |
protected abstract T parseForm(CodedInputStream in); | |
private final ThreadLocal<byte[]> thread_local_buffer = new ThreadLocal<byte[]>() { | |
@Override | |
protected byte[] initialValue() { | |
return new byte[1024 * 10]; // 10 KB | |
} | |
}; | |
@SuppressWarnings("unchecked") | |
@Override | |
public <U> U readObjectData(ByteBuffer bb, Class<U> type) { | |
int len = bb.getInt(); | |
byte[] tempBuf = thread_local_buffer.get(); | |
if (tempBuf.length < len) { | |
tempBuf = new byte[len]; | |
thread_local_buffer.set(tempBuf); | |
} | |
bb.get(tempBuf, 0, len); | |
return (U) parseForm(CodedInputStream.newInstance(tempBuf, 0, len)); | |
} | |
@Override | |
public void writeObjectData(ByteBuffer bb, Object obj) { | |
Message message = (Message) obj; | |
byte[] tempBuf = thread_local_buffer.get(); | |
int len = message.getSerializedSize(); | |
if (tempBuf.length < len) { | |
tempBuf = new byte[len]; | |
thread_local_buffer.set(tempBuf); | |
} | |
CodedOutputStream codedOut = CodedOutputStream.newInstance(tempBuf); | |
try { | |
message.writeTo(codedOut); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
bb.putInt(message.getSerializedSize()); | |
bb.put(tempBuf, 0, len); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment