Guest User

Untitled

a guest
May 17th, 2012
155
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.nio.ByteBuffer;
  2.  
  3. public class Blobber {
  4.  
  5. public static byte[] blobify(byte[][] blobs) {
  6. int size = 4 + (4 * blobs.length);
  7. for (byte blob[] : blobs) {
  8. size += blob.length;
  9. }
  10. if (size > 1024 * 1024 * 49) {
  11. throw new IllegalArgumentException("Wire protocol only " +
  12. "supports 50 megabyte messages, 49 megs is really close.");
  13. }
  14. ByteBuffer buf = ByteBuffer.allocate(size);
  15. buf.putInt(blobs.length);
  16. for (byte blob[] : blobs) {
  17. buf.putInt(blob.length);
  18. buf.put(blob);
  19. }
  20. return buf.array();
  21. }
  22.  
  23. public static byte[][] unblobify(byte[] blobs) {
  24. ByteBuffer buf = ByteBuffer.wrap(blobs);
  25. byte[][] deBlobs = new byte[buf.getInt()][];
  26. int index = 0;
  27. while (buf.hasRemaining()) {
  28. byte bytes[] = new byte[buf.getInt()];
  29. buf.get(bytes);
  30. deBlobs[index++] = bytes;
  31. }
  32. return deBlobs;
  33. }
  34.  
  35. public static void main(String args[]) {
  36. byte foo[][] = new byte[3][];
  37. foo [0] = new byte[3];
  38. foo[1] = new byte[5];
  39. foo[2] = new byte[6];
  40.  
  41. byte blobified[] = blobify(foo);
  42. byte unblobified[][] = unblobify(blobified);
  43.  
  44. assert(foo[0].length == unblobified[0].length);
  45. assert(foo[1].length == unblobified[1].length);
  46. assert(foo[2].length == unblobified[2].length);
  47. }
  48. }
RAW Paste Data