Returns a compact byte-buffer representation of this ApproximateHistogram object
storing actual values as opposed to histogram bins

Requires 3 + 4 * count bytes of storage with count &lt;= 127

@param buf ByteBuffer to write the ApproximateHistogram to
334210
public void toBytesCompact(ByteBuffer buf)
  {
    Preconditions.checkState(canStoreCompact(), "Approximate histogram cannot be stored in compact form");

    buf.putShort((short) (-1 * size)); // use negative size to indicate compact storage

    final long exactCount = getExactCount();
    if (exactCount != count) {
      // use negative count to indicate approximate bins
      buf.put((byte) (-1 * (count - exactCount)));

      // store actual values instead of bins
      for (int i = 0; i < binCount; ++i) {
        // repeat each value bins[i] times for approximate bins
        if ((bins[i] & APPROX_FLAG_BIT) != 0) {
          for (int k = 0; k < (bins[i] & COUNT_BITS); ++k) {
            buf.putFloat(positions[i]);
          }
        }
      }

      // tack on min and max since they may be lost int the approximate bins
      buf.putFloat(min);
      buf.putFloat(max);
    }

    buf.put((byte) exactCount);
    // store actual values instead of bins
    for (int i = 0; i < binCount; ++i) {
      // repeat each value bins[i] times for exact bins
      if ((bins[i] & APPROX_FLAG_BIT) == 0) {
        for (int k = 0; k < (bins[i] & COUNT_BITS); ++k) {
          buf.putFloat(positions[i]);
        }
      }
    }
  }
886744
public static byte[] byteBufToArray(ByteBuf byteBuf) {
        int length = byteBuf.readableBytes();
        byte[] byteArray = new byte[length];
        byteBuf.getBytes(byteBuf.readerIndex(), byteArray);
        return byteArray;
    }
676397
private int write(ByteBuffer outbuf)
    {
        int nbytes;
        try {
            nbytes = fd.write(outbuf);
            if (nbytes == 0) {
                errno.set(ZError.EAGAIN);
            }
        }
        catch (IOException e) {
            errno.set(ZError.ENOTCONN);
            nbytes = -1;
        }

        return nbytes;
    }
61064
private static ByteBuffer trim(ByteBuffer buf) {
        if (buf.capacity() <= 4 * buf.remaining()) {
            return buf;
        } else {
            ByteBuffer clone = ByteBuffer.allocate(buf.remaining());
            buf.get(clone.array());
            return clone;
        }
    }
530429
private byte[] bufB(int bpv) {
    assert bpv == 1 || bpv == 2 : "Only bit vectors with/without NA are supported";
    final int off = CBSChunk.OFF;
    int clen  = off + CBSChunk.clen(_len, bpv);
    byte bs[] = new byte[clen];
    // Save the gap = number of unfilled bits and bpv value
    bs[0] = (byte) (((_len*bpv)&7)==0 ? 0 : (8-((_len*bpv)&7)));
    bs[1] = (byte) bpv;

    // Dense bitvector
    int  boff = 0;
    byte b    = 0;
    int  idx  = CBSChunk.OFF;
    int j = 0;
    for (int i=0; i<_len; i++) {
      byte val = 0;
      if(_id == null || (j < _id.length && _id[j] == i)) {
        assert bpv == 2 || !isNA2(j);
        val = (byte)(isNA2(j)?CBSChunk._NA:_ls[j]);
        ++j;
      }
      if( bpv==1 )
        b = CBSChunk.write1b(b, val, boff);
      else
        b = CBSChunk.write2b(b, val, boff);
      boff += bpv;
      if (boff>8-bpv) { assert boff == 8; bs[idx] = b; boff = 0; b = 0; idx++; }
    }
    assert j == _sparseLen;
    assert bs[0] == (byte) (boff == 0 ? 0 : 8-boff):"b[0] = " + bs[0] + ", boff = " + boff + ", bpv = " + bpv;
    // Flush last byte
    if (boff>0) bs[idx] = b;
    return bs;
  }
145135
public static byte[] getBytes(ByteBuf buf, int start, int length) {
        return getBytes(buf, start, length, true);
    }
178379
public static byte[] newByteArrayFromByteBuffer(ByteBuffer buf) {
    final int length = buf.remaining();
    byte[] bytes = new byte[length];
    // transfer bytes from this buffer into the given destination array
    buf.duplicate().get(bytes, 0, length);
    return bytes;
  }
665296
public static ApproximateHistogram fromBytes(ByteBuffer buf)
  {
    // negative size indicates compact representation
    // this works regardless of whether we use int or short for the size since the leftmost bit is the sign bit
    if (buf.getShort(buf.position()) < 0) {
      return fromBytesCompact(buf);
    } else {
      // ignore size, determine if sparse or dense based on sign of binCount
      if (buf.getInt(buf.position() + Integer.BYTES) < 0) {
        return fromBytesSparse(buf);
      } else {
        return fromBytesDense(buf);
      }
    }
  }
620214
public static ByteBuf copyShort(int value) {
        ByteBuf buf = buffer(2);
        buf.writeShort(value);
        return buf;
    }
1103451
private static FixedBucketsHistogram fromBytesSparse(ByteBuffer buf)
  {
    double lowerLimit = buf.getDouble();
    double upperLimit = buf.getDouble();
    int numBuckets = buf.getInt();
    OutlierHandlingMode outlierHandlingMode = OutlierHandlingMode.values()[buf.get()];

    long count = buf.getLong();
    long lowerOutlierCount = buf.getLong();
    long upperOutlierCount = buf.getLong();
    long missingValueCount = buf.getLong();

    double max = buf.getDouble();
    double min = buf.getDouble();

    int nonEmptyBuckets = buf.getInt();
    long histogram[] = new long[numBuckets];
    for (int i = 0; i < nonEmptyBuckets; i++) {
      int bucket = buf.getInt();
      long bucketCount = buf.getLong();
      histogram[bucket] = bucketCount;
    }

    return new FixedBucketsHistogram(
        lowerLimit,
        upperLimit,
        numBuckets,
        outlierHandlingMode,
        histogram,
        count,
        max,
        min,
        lowerOutlierCount,
        upperOutlierCount,
        missingValueCount
    );
  }
1092494
private static void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }
1065796
static int getUnsignedShort(ByteBuf buf, int offset) {
        return (buf.getByte(offset)     & 0xFF) << 8 |
                buf.getByte(offset + 1) & 0xFF;
    }
428979
public void deserialize(final ByteBuffer buf) {
		wordsInUse = buf.getInt();
		words = new long[wordsInUse];
		for (int i = 0; i < words.length; i++) {
			words[i] = buf.getLong();
		}

		// Assume maximum length then find real length
		// because recalculateWordsInUse assumes maintenance
		// or reduction in logical size
		wordsInUse = words.length;
		recalculateWordsInUse();
		sizeIsSticky = (words.length > 0 && words[words.length-1] == 0L); // heuristic
		checkInvariants();
	}
722187
public void toBytes(ByteBuffer buf)
  {
    if (canStoreCompact() && getCompactStorageSize() < getSparseStorageSize()) {
      // store compact
      toBytesCompact(buf);
    } else {
      // store sparse
      toBytesSparse(buf);
    }
  }
525494
protected ByteBuf toByteBuf(final SipMessage msg) {
        try {
            final Buffer b = msg.toBuffer();
            final int capacity = b.capacity() + 2;
            final ByteBuf buffer = this.channel.alloc().buffer(capacity, capacity);

            for (int i = 0; i < b.getReadableBytes(); ++i) {
                buffer.writeByte(b.getByte(i));
            }
            buffer.writeByte(SipParser.CR);
            buffer.writeByte(SipParser.LF);
            return buffer;
        } catch (final IOException e) {
            // shouldn't be possible since the underlying buffer
            // from the msg is backed by a byte-array.
            // TODO: do something appropriate other than this
            throw new RuntimeException("Unable to convert SipMessage to a ByteBuf due to IOException", e);
        }
    }
143054
public static ByteBuffer copyBuffer(final ByteBuffer buf) {
        if(buf == null)
            return null;
        int offset=buf.hasArray()? buf.arrayOffset() + buf.position() : buf.position(), len=buf.remaining();
        byte[] tmp=new byte[len];
        if(!buf.isDirect())
            System.arraycopy(buf.array(), offset, tmp, 0, len);
        else {
         //   buf.get(tmp, 0, len);
            for(int i=0; i < len; i++)
                tmp[i]=buf.get(i+offset);
        }
        return ByteBuffer.wrap(tmp);
    }
121000
public static String toStringBinary(ByteBuffer buf) {
    if (buf == null) {
      return "null";
    }
    return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit());
  }