public static byte[] bufferToArray(ByteBuffer buffer) {
        if (buffer.hasArray() && buffer.arrayOffset() == 0 &&
                buffer.array().length == buffer.remaining()) {
            return buffer.array();
        } else {
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return bytes;
        }
    }
Returns a byte array with the buffer's contents, trying to avoid copying the data if
possible.
indexr-query-opt/src/main/java/org/apache/spark/util/JavaUtils.java