Skip to content

Instantly share code, notes, and snippets.

@eneveu
Created August 29, 2012 09:34
Show Gist options
  • Save eneveu/3509121 to your computer and use it in GitHub Desktop.
Save eneveu/3509121 to your computer and use it in GitHub Desktop.
Static utility methods to read/write collections to/from a byte stream, using protostuff.
package com.foo.serialization;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Static utility methods to read/write collections to/from a byte stream, using protostuff.
*/
public final class CollectionSerializationUtils {
private CollectionSerializationUtils() { /* prevents instantiation */ }
public static <T> void writeListTo(OutputStream out, List<T> messages, Schema<T> schema) throws IOException {
writeSize(out, messages);
writeMessages(out, messages, schema);
}
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema) throws IOException {
int size = readSize(in);
return readMessages(in, schema, size);
}
private static <T> void writeSize(OutputStream out, List<T> messages) throws IOException {
out.write(messages.size());
}
private static int readSize(InputStream in) throws IOException {
return in.read();
}
private static <T> void writeMessages(OutputStream out, List<T> messages, Schema<T> schema) throws IOException {
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
for (T message : messages) {
ProtostuffIOUtil.writeDelimitedTo(out, message, schema, buffer);
buffer.clear();
}
}
private static <T> List<T> readMessages(InputStream in, Schema<T> schema, int size) throws IOException {
List<T> messages = Lists.newArrayListWithCapacity(size);
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
for (int i = 0; i < size; i++) {
T message = schema.newMessage();
ProtostuffIOUtil.mergeDelimitedFrom(in, message, schema, buffer);
messages.add(message);
buffer.clear();
}
return messages;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment