Java ByteBuffer from Byte Array readByteArray(ByteBuffer in)

Here you can find the source of readByteArray(ByteBuffer in)

Description

read Byte Array

License

Apache License

Declaration

public static byte[] readByteArray(ByteBuffer in) 

Method Source Code

//package com.java2s;
/*/* www . j av a 2  s.co  m*/
 * Copyright 2013-2014 eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    public static byte[] readByteArray(ByteBuffer in) {
        int len = readVInt(in);
        if (len < 0)
            return null;

        byte[] array = new byte[len];
        in.get(array);
        return array;
    }

    public static int readVInt(ByteBuffer in) {
        long n = readVLong(in);
        if ((n > Integer.MAX_VALUE) || (n < Integer.MIN_VALUE)) {
            throw new IllegalArgumentException("value too long to fit in integer");
        }
        return (int) n;
    }

    public static long readVLong(ByteBuffer in) {
        byte firstByte = in.get();
        int len = decodeVIntSize(firstByte);
        if (len == 1) {
            return firstByte;
        }
        long i = 0;
        for (int idx = 0; idx < len - 1; idx++) {
            byte b = in.get();
            i = i << 8;
            i = i | (b & 0xFF);
        }
        return (isNegativeVInt(firstByte) ? (i ^ -1L) : i);
    }

    private static int decodeVIntSize(byte value) {
        if (value >= -112) {
            return 1;
        } else if (value < -120) {
            return -119 - value;
        }
        return -111 - value;
    }

    private static boolean isNegativeVInt(byte value) {
        return value < -120 || (value >= -112 && value < 0);
    }
}

Related

  1. buffer2Bytes(ByteBuffer bbuf)
  2. bufToArray(ByteBuffer b)
  3. bufToArray(ByteBuffer b)
  4. byteBuffer(byte[] a)
  5. readByteArray(ByteBuffer byteBuffer, int length)
  6. readByteArray(ByteBuffer logBuf)
  7. readByteAsInt(ByteBuffer buffer)
  8. readBytes(ByteBuffer bb, int length)
  9. readBytes(ByteBuffer bb, int length)