Java Code Examples for java.nio.ByteBuffer#position()

The following examples show how to use java.nio.ByteBuffer#position() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BufferTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private void testGetMethods(ByteBuffer b) {
    b.position(0);
    b.get();
    b.get(0);
    b.get(new byte[1]);
    b.get(new byte[1], 0, 1);
    b.getChar();
    b.getChar(0);
    b.position(0);
    b.getDouble();
    b.getDouble(0);
    b.position(0);
    b.getFloat();
    b.getFloat(0);
    b.getInt();
    b.getInt(0);
    b.position(0);
    b.getLong();
    b.getLong(0);
    b.position(0);
    b.getShort();
    b.getShort(0);
}
 
Example 2
Source File: BrotliStreamCompressorByteBufferTest.java    From jbrotli with Apache License 2.0 6 votes vote down vote up
@Test
public void compress_with_direct_ByteBuffer_without_flushing() throws Exception {
  ByteBuffer inBuffer = ByteBuffer.allocateDirect(A_BYTES.length);
  inBuffer.put(A_BYTES);
  inBuffer.position(0);

  // when
  ByteBuffer outBuffer = compressor.compressNext(inBuffer, false);
  // then
  assertThat(outBuffer.capacity()).isEqualTo(0);

  // when
  outBuffer = compressor.compressNext(ByteBuffer.allocateDirect(0), true);
  // then
  assertThat(outBuffer.capacity()).isEqualTo(A_BYTES_COMPRESSED.length);

  // then
  assertThat(getByteArray(outBuffer)).startsWith(A_BYTES_COMPRESSED);
}
 
Example 3
Source File: Encrypt.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void combination_12(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(buf);

    // prepare an empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocate(0);
    emptyBuf.put(new byte[0]);
    ci.updateAAD(emptyBuf);
    byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len12 = ci.update(plainText, 0, plainText.length - offset,
            part12_1, 0);
    int rest12 = ci.doFinal(plainText, plainText.length - offset, offset,
            part12_1, len12);
    byte[] outputText12 = new byte[len12 + rest12];
    System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length);
    results.add(outputText12);
}
 
Example 4
Source File: BinaryUtil.java    From iceberg with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a byte buffer whose length is lesser than or equal to truncateLength and is greater than the given input
 */
public static Literal<ByteBuffer> truncateBinaryMax(Literal<ByteBuffer> input, int length) {
  ByteBuffer inputBuffer = input.value();
  if (length >= inputBuffer.remaining()) {
    return input;
  }

  // Truncate the input to the specified truncate length.
  ByteBuffer truncatedInput = truncateBinary(inputBuffer, length);

  // Try incrementing the bytes from the end. If all bytes overflow after incrementing, then return null
  for (int i = length - 1; i >= 0; --i) {
    byte element = truncatedInput.get(i);
    element = (byte) (element + 1);
    if (element != 0) { // No overflow
      truncatedInput.put(i, element);
      // Return a byte buffer whose position is zero and limit is i + 1
      truncatedInput.position(0);
      truncatedInput.limit(i + 1);
      return Literal.of(truncatedInput);
    }
  }
  return null; // Cannot find a valid upper bound
}
 
Example 5
Source File: PEPeerControlImpl.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
private byte[] computeMd5Hash(DirectByteBuffer buffer)
{
	BrokenMd5Hasher md5 	= new BrokenMd5Hasher();

	md5.reset();
	final int position = buffer.position(DirectByteBuffer.SS_DW);
	md5.update(buffer.getBuffer(DirectByteBuffer.SS_DW));
	buffer.position(DirectByteBuffer.SS_DW, position);
	ByteBuffer md5Result	= ByteBuffer.allocate(16);
	md5Result.position(0);
	md5.finalDigest( md5Result );

	final byte[] result =new byte[16];
	md5Result.position(0);
	for (int i =0; i <result.length; i++ )
	{
		result[i] = md5Result.get();
	}

	return result;
}
 
Example 6
Source File: PositionedCryptoInputStream.java    From commons-crypto with Apache License 2.0 6 votes vote down vote up
/**
 * Does the decryption using inBuffer as input and outBuffer as output. Upon
 * return, inBuffer is cleared; the decrypted data starts at
 * outBuffer.position() and ends at outBuffer.limit().
 *
 * @param state the CipherState instance.
 * @param inByteBuffer the input buffer.
 * @param outByteBuffer the output buffer.
 * @param padding the padding.
 * @throws IOException if an I/O error occurs.
 */
private void decrypt(final CipherState state, final ByteBuffer inByteBuffer,
        final ByteBuffer outByteBuffer, final byte padding) throws IOException {
    Utils.checkState(inByteBuffer.position() >= padding);
    if (inByteBuffer.position() == padding) {
        // There is no real data in inBuffer.
        return;
    }
    inByteBuffer.flip();
    outByteBuffer.clear();
    decryptBuffer(state, inByteBuffer, outByteBuffer);
    inByteBuffer.clear();
    outByteBuffer.flip();
    if (padding > 0) {
        /*
         * The plain text and cipher text have a 1:1 mapping, they start at
         * the same position.
         */
        outByteBuffer.position(padding);
    }
}
 
Example 7
Source File: FSA.java    From vespa with Apache License 2.0 5 votes vote down vote up
/** Jumps ahead by string */
public void delta(String string){
    ByteBuffer buf = fsa.encode(string);
    Maps m = fsa.map();
    while (state >0 && buf.position()<buf.limit()){
        delta(m, buf.get());
    }
}
 
Example 8
Source File: QueuedMuxer.java    From EZFilter with MIT License 5 votes vote down vote up
public void writeSampleData(SampleType sampleType, ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) {
    if (mStarted) {
        mMuxer.writeSampleData(getTrackIndexForSampleType(sampleType), byteBuf, bufferInfo);
        return;
    }
    byteBuf.limit(bufferInfo.offset + bufferInfo.size);
    byteBuf.position(bufferInfo.offset);
    if (mByteBuffer == null) {
        mByteBuffer = ByteBuffer.allocate(MediaUtil.BUFFER_SIZE);
    }
    mByteBuffer.put(byteBuf);
    mSampleInfoList.add(new SampleInfo(sampleType, bufferInfo.size, bufferInfo));
}
 
Example 9
Source File: Layer3Packet.java    From meshnet with GNU General Public License v3.0 5 votes vote down vote up
private int calculateHmac(int baseNonce, int networkKey){
	ByteBuffer key = ByteBuffer.allocate(8);
	key.order(ByteOrder.LITTLE_ENDIAN);
	key.putInt(baseNonce);
	key.putInt(networkKey);
	ByteBuffer buf = packet.duplicate();
	buf.position(0);
	return generateHmac(buf, PACKET_LEN-4, key).getInt();
}
 
Example 10
Source File: Encrypt.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void combination_14(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);
    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);

    // process the first half of AAD data
    buf.position(0);
    buf.limit(AAD.length / 2);
    c.updateAAD(buf);

    // process the rest of AAD data
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocate(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer out = ByteBuffer.allocate(c.getOutputSize(in.limit()));
    out.position(0);
    out.limit(c.getOutputSize(in.limit()));

    // process input text
    c.update(in, out);
    c.doFinal(in, out);
    int resultSize = out.position();
    byte[] result14 = new byte[resultSize];
    out.position(0);
    out.limit(resultSize);
    out.get(result14, 0, resultSize);
    results.add(result14);
}
 
Example 11
Source File: HandleNativeHeap.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void handleNHSG(Client client, ByteBuffer data) {
    byte dataCopy[] = new byte[data.limit()];
    data.rewind();
    data.get(dataCopy);
    data = ByteBuffer.wrap(dataCopy);
    client.getClientData().getNativeHeapData().addHeapData(data);

    if (true) {
        return;
    }

    byte[] copy = new byte[data.limit()];
    data.get(copy);

    ByteBuffer buffer = ByteBuffer.wrap(copy);
    buffer.order(ByteOrder.BIG_ENDIAN);

    int id = buffer.getInt();
    int unitsize = buffer.get();
    long startAddress = buffer.getInt() & 0x00000000ffffffffL;
    int offset = buffer.getInt();
    int allocationUnitCount = buffer.getInt();

    // read the usage
    while (buffer.position() < buffer.limit()) {
        int eState = buffer.get() & 0x000000ff;
        int eLen = (buffer.get() & 0x000000ff) + 1;
    }
}
 
Example 12
Source File: AbstractPerfDataBufferPrologue.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the minor version number from the given ByteBuffer.
 *
 * @return int - the minor version
 */
public static int getMinorVersion(ByteBuffer bb) {
    // save buffer state
    int position = bb.position();

    bb.position(PERFDATA_PROLOG_MINOR_OFFSET);
    int minor = (int)bb.get();

    // restore buffer state.
    bb.position(position);

    return minor;
}
 
Example 13
Source File: WingDings.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    try {
        while (sp < sl) {
            char c = sa[sp];
            if (dl - dp < 1)
                return CoderResult.OVERFLOW;
            if (!canEncode(c))
                return CoderResult.unmappableForLength(1);
            sp++;
            da[dp++] = table[c - 0x2700];
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 14
Source File: SctpMultiChannelImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private int send(int fd,
                 ByteBuffer src,
                 int assocId,
                 SocketAddress target,
                 MessageInfo messageInfo)
        throws IOException {
    int streamNumber = messageInfo.streamNumber();
    boolean unordered = messageInfo.isUnordered();
    int ppid = messageInfo.payloadProtocolID();

    if (src instanceof DirectBuffer)
        return sendFromNativeBuffer(fd, src, target, assocId,
                streamNumber, unordered, ppid);

    /* Substitute a native buffer */
    int pos = src.position();
    int lim = src.limit();
    assert (pos <= lim && streamNumber >= 0);

    int rem = (pos <= lim ? lim - pos : 0);
    ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
    try {
        bb.put(src);
        bb.flip();
        /* Do not update src until we see how many bytes were written */
        src.position(pos);

        int n = sendFromNativeBuffer(fd, bb, target, assocId,
                streamNumber, unordered, ppid);
        if (n > 0) {
            /* now update src */
            src.position(pos + n);
        }
        return n;
    } finally {
        Util.releaseTemporaryDirectBuffer(bb);
    }
}
 
Example 15
Source File: DatagramChannelImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private int receiveIntoNativeBuffer(FileDescriptor fd, ByteBuffer bb,
                                    int rem, int pos)
    throws IOException
{
    int n = receive0(fd, ((DirectBuffer)bb).address() + pos, rem,
                     isConnected());
    if (n > 0)
        bb.position(pos + n);
    return n;
}
 
Example 16
Source File: FlexBase64.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Decodes one Base64 byte buffer into another. This method will return and save state
 * if the target does not have the required capacity. Subsequent calls with a new target will
 * resume reading where it last left off (the source buffer's position). Similarly not all of the
 * source data need be available, this method can be repetitively called as data is made available.
 *
 * <p>The decoder will skip white space, but will error if it detects corruption.</p>
 *
 * @param source the byte buffer to read encoded data from
 * @param target the byte buffer to write decoded data to
 * @throws IOException if the encoded data is corrupted
 */
public void decode(ByteBuffer source, ByteBuffer target) throws IOException {
    if (target == null)
        throw new IllegalStateException();

    int last = this.last;
    int state = this.state;

    int remaining = source.remaining();
    int targetRemaining = target.remaining();
    int b = 0;
    while (remaining-- > 0 && targetRemaining > 0) {
        b = nextByte(source, state, last, false);
        if (b == MARK) {
            last = MARK;
            if (--remaining <= 0) {
                break;
            }
            b = nextByte(source, state, last, false);
        }
        if (b == DONE) {
            last = state = 0;
            break;
        }
        if (b == SKIP) {
            continue;
        }
        //  ( 6 | 2) (4 | 4) (2 | 6)
        if (state == 0) {
            last = b << 2;
            state++;
            if (remaining-- <= 0) {
                break;
            }
            b = nextByte(source, state, last, false);
            if ((b & 0xF000) != 0) {
                source.position(source.position() - 1);
                continue;
            }
        }
        if (state == 1) {
            target.put((byte)(last | (b >>> 4)));
            last = (b & 0x0F) << 4;
            state++;
            if (remaining-- <= 0 || --targetRemaining <= 0) {
                break;
            }
            b = nextByte(source, state, last, false);
            if ((b & 0xF000) != 0) {
                source.position(source.position() - 1);
                continue;
            }
        }
        if (state == 2) {
            target.put((byte) (last | (b >>> 2)));
            last = (b & 0x3) << 6;
            state++;
            if (remaining-- <= 0 || --targetRemaining <= 0) {
                break;
            }
            b = nextByte(source, state, last, false);
            if ((b & 0xF000) != 0) {
                source.position(source.position() - 1);
                continue;
            }
        }
        if (state == 3) {
            target.put((byte)(last | b));
            last = state = 0;
            targetRemaining--;
        }
    }

    if (remaining > 0) {
        drain(source, b, state, last);
    }

    this.last = last;
    this.state = state;
    this.lastPos = source.position();
}
 
Example 17
Source File: ResamplingAudioProcessor.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
@Override
public void queueInput(ByteBuffer inputBuffer) {
  // Prepare the output buffer.
  int position = inputBuffer.position();
  int limit = inputBuffer.limit();
  int size = limit - position;
  int resampledSize;
  switch (inputAudioFormat.encoding) {
    case C.ENCODING_PCM_8BIT:
      resampledSize = size * 2;
      break;
    case C.ENCODING_PCM_24BIT:
      resampledSize = (size / 3) * 2;
      break;
    case C.ENCODING_PCM_32BIT:
      resampledSize = size / 2;
      break;
    case C.ENCODING_PCM_16BIT:
    case C.ENCODING_PCM_FLOAT:
    case C.ENCODING_PCM_A_LAW:
    case C.ENCODING_PCM_MU_LAW:
    case C.ENCODING_INVALID:
    case Format.NO_VALUE:
    default:
      throw new IllegalStateException();
  }

  // Resample the little endian input and update the input/output buffers.
  ByteBuffer buffer = replaceOutputBuffer(resampledSize);
  switch (inputAudioFormat.encoding) {
    case C.ENCODING_PCM_8BIT:
      // 8->16 bit resampling. Shift each byte from [0, 256) to [-128, 128) and scale up.
      for (int i = position; i < limit; i++) {
        buffer.put((byte) 0);
        buffer.put((byte) ((inputBuffer.get(i) & 0xFF) - 128));
      }
      break;
    case C.ENCODING_PCM_24BIT:
      // 24->16 bit resampling. Drop the least significant byte.
      for (int i = position; i < limit; i += 3) {
        buffer.put(inputBuffer.get(i + 1));
        buffer.put(inputBuffer.get(i + 2));
      }
      break;
    case C.ENCODING_PCM_32BIT:
      // 32->16 bit resampling. Drop the two least significant bytes.
      for (int i = position; i < limit; i += 4) {
        buffer.put(inputBuffer.get(i + 2));
        buffer.put(inputBuffer.get(i + 3));
      }
      break;
    case C.ENCODING_PCM_16BIT:
    case C.ENCODING_PCM_FLOAT:
    case C.ENCODING_PCM_A_LAW:
    case C.ENCODING_PCM_MU_LAW:
    case C.ENCODING_INVALID:
    case Format.NO_VALUE:
    default:
      // Never happens.
      throw new IllegalStateException();
  }
  inputBuffer.position(inputBuffer.limit());
  buffer.flip();
}
 
Example 18
Source File: MetalBasic3DRenderer.java    From robovm-samples with Apache License 2.0 4 votes vote down vote up
public void configure(MetalBasic3DView view) {
    // find a usable Device
    device = view.getDevice();
    
    // setup view with drawable formats
    view.setDepthPixelFormat(MTLPixelFormat.Depth32Float);
    view.setStencilPixelFormat(MTLPixelFormat.Invalid);
    view.setSampleCount(1);
    
    // create a new command queue
    commandQueue = device.newCommandQueue();
    
    defaultLibrary = device.newDefaultLibrary();
    if (defaultLibrary == null) {
        // If the shader libary isn't loading, nothing good will happen
        throw new Error(">> ERROR: Couldnt create a default shader library");
    }
    
    preparePipelineState(view);
    
    MTLDepthStencilDescriptor depthStateDesc = new MTLDepthStencilDescriptor();
    depthStateDesc.setDepthCompareFunction(MTLCompareFunction.Less);
    depthStateDesc.setDepthWriteEnabled(true);
    depthState = device.newDepthStencilState(depthStateDesc);
    
    // allocate a number of buffers in memory that matches the sempahore count so that
    // we always have one self contained memory buffer for each buffered frame.
    // In this case triple buffering is the optimal way to go so we cycle through 3 memory buffers
    for (int i = 0; i < kInFlightCommandBuffers; i++) {
        dynamicConstantBuffer[i] = device.newBuffer(maxBufferBytesPerFrame, MTLResourceOptions.CPUCacheModeDefaultCache);
        dynamicConstantBuffer[i].setLabel("ConstantBuffer" + i);
        
        // write initial color values for both cubes (at each offset).
        // Note, these will get animated during update
        ByteBuffer constant_buffer = dynamicConstantBuffer[i].getContents();
        constant_buffer.order(ByteOrder.nativeOrder());

        for (int j = 0; j < kNumberOfBoxes; j++) {
            if (j % 2 == 0) {
                constant_buffer.position((sizeOfConstantT * j) + ambientColorOffset);
                BufferUtils.copy(kBoxAmbientColors[0], 0, 4, constant_buffer);
                constant_buffer.position((sizeOfConstantT * j) + diffuseColorOffset);
                BufferUtils.copy(kBoxDiffuseColors[0], 0, 4, constant_buffer);
                constant_buffer.putInt((sizeOfConstantT * j) + multiplierOffset, 1);
            } else {
                constant_buffer.position((sizeOfConstantT * j) + ambientColorOffset);
                BufferUtils.copy(kBoxAmbientColors[1], 0, 4, constant_buffer);
                constant_buffer.position((sizeOfConstantT * j) + diffuseColorOffset);
                BufferUtils.copy(kBoxDiffuseColors[1], 0, 4, constant_buffer);
                constant_buffer.putInt((sizeOfConstantT * j) + multiplierOffset, -1);
            }
        }
    }
}
 
Example 19
Source File: NIOUtils.java    From mpegts-streamer with Apache License 2.0 4 votes vote down vote up
public static int skip(ByteBuffer buffer, int count) {
	int toSkip = Math.min(buffer.remaining(), count);
	buffer.position(buffer.position() + toSkip);
	return toSkip;
}
 
Example 20
Source File: DBCS_IBM_ASCII_Decoder.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
    byte[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    char[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    try {
        while (sp < sl) {
            int b1, b2;
            b1 = sa[sp];
            int inputSize = 1;
            int v = 0;
            char outputChar = REPLACE_CHAR;
            if (b1 < 0)
                b1 += 256;

            if (!leadByte[b1])
            {
              outputChar = singleByteToChar.charAt(b1);
            } else {
                if (sl - sp < 2)
                    return CoderResult.UNDERFLOW;
                b2 = sa[sp + 1];
                if (b2 < 0)
                    b2 += 256;

                inputSize++;

                // Lookup in the two level index
                v = b1 * 256 + b2;
                outputChar = index2.charAt(index1[((v & mask1) >> shift)]
                                            + (v & mask2));
            }
            if (outputChar == '\uFFFD')
                return CoderResult.unmappableForLength(inputSize);

            if (dl - dp < 1)
                return CoderResult.OVERFLOW;
            da[dp++] = outputChar;
            sp += inputSize;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}