/// <summary> /// Copies compressed contents from <paramref name="source"/> into the <paramref name="target"/> from the <paramref name="targetOffset"/> /// </summary> /// <param name="target">The <see cref="ByteBuffer"/> that will be written to.</param> /// <param name="source">The source <see cref="ByteBuffer"/> to read the data from.</param> /// <param name="targetOffset">The <paramref name="target"/> buffer's offset to start writing from.</param> /// <returns>The number of bytes written.</returns> public static int CompressedCopy(this ByteBuffer target, ByteBuffer source, int targetOffset) { byte[] compressed; using (var ms = new MemoryStream(source.ToArray())) { compressed = Compress(ms); } target.BlockCopy(compressed, 0, targetOffset, compressed.Length); return compressed.Length; }
/// <summary> /// Construct a new histogram by decoding it from a compressed form in a ByteBuffer. /// </summary> /// <param name="buffer">The buffer to decode from</param> /// <param name="minBarForHighestTrackableValue">Force highestTrackableValue to be set at least this high</param> /// <returns>The newly constructed histogram</returns> public static HistogramBase DecodeFromCompressedByteBuffer(ByteBuffer buffer, long minBarForHighestTrackableValue) { var cookie = buffer.GetInt(); var headerSize = GetHeaderSize(cookie); var lengthOfCompressedContents = buffer.GetInt(); HistogramBase histogram; //Skip the first two bytes (from the RFC 1950 specification) and move to the deflate specification (RFC 1951) // http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html using (var inputStream = new MemoryStream(buffer.ToArray(), buffer.Position + Rfc1950HeaderLength, lengthOfCompressedContents - Rfc1950HeaderLength)) using (var decompressor = new DeflateStream(inputStream, CompressionMode.Decompress, leaveOpen: true)) { var headerBuffer = ByteBuffer.Allocate(headerSize); headerBuffer.ReadFrom(decompressor, headerSize); histogram = DecodeFromByteBuffer(headerBuffer, minBarForHighestTrackableValue, decompressor); } return histogram; }