/// <summary> /// Encodes and compresses this container. /// </summary> /// <returns> The buffer. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public ByteBuffer Encode() { var data = GetData(); // so we have a read only view, making this method thread safe /* grab the data as a byte array for compression */ var bytes = new byte[data.limit()]; data.mark(); data.get(bytes); data.reset(); /* compress the data */ byte[] compressed; if (type == COMPRESSION_NONE) { compressed = bytes; } else if (type == COMPRESSION_GZIP) { compressed = CompressionUtils.Gzip(bytes); } else if (type == COMPRESSION_BZIP2) { compressed = CompressionUtils.Bzip2(bytes); } else { throw new IOException("Invalid compression type"); } /* calculate the size of the header and trailer and allocate a buffer */ var header = 5 + (type == COMPRESSION_NONE ? 0 : 4) + (IsVersioned() ? 2 : 0); var buf = ByteBuffer.allocate(header + compressed.Length); /* write the header, with the optional uncompressed length */ buf.put((byte)type); buf.putInt(compressed.Length); if (type != COMPRESSION_NONE) { buf.putInt(data.limit()); } /* write the compressed length */ buf.put(compressed); /* write the trailer with the optional version */ if (IsVersioned()) { buf.putShort((short)version); } /* flip the buffer and return it */ return((ByteBuffer)buf.flip()); }