Java ByteBuffer Slice getSlice(ByteBuffer bb, int offset, int length)

Here you can find the source of getSlice(ByteBuffer bb, int offset, int length)

Description

Returns the subset of a byte buffer, using the given offset and length.

License

Open Source License

Parameter

Parameter Description
bb a parameter
offset a parameter
length a parameter

Declaration

public static ByteBuffer getSlice(ByteBuffer bb, int offset, int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    public static final ByteBuffer EMPTY = ByteBuffer.allocate(0);

    /**/*from w  ww  .  j  ava  2s .co  m*/
     * Returns the subset of a byte buffer, using the given offset and length.
     * The position and limit of the original buffer won't change after this
     * operation.
     * 
     * @param bb
     * @param offset
     * @param length
     * @return 
     */
    public static ByteBuffer getSlice(ByteBuffer bb, int offset, int length) {
        if (length == 0) {
            // very funny
            return EMPTY;
        }

        ByteOrder order = bb.order();

        // create duplicate so the position/limit of the original won't change
        bb = bb.duplicate();

        // go to offset
        bb.position(offset);

        // set new limit if length is provided, use current limit otherwise
        if (length > 0) {
            bb.limit(offset + length);
        }

        // do the actual slicing
        ByteBuffer bbSlice = bb.slice();

        // set same byte order
        bbSlice.order(order);

        return bbSlice;
    }

    /**
     * Returns the subset of a byte buffer, starting from the given offset up to
     * the current limit.
     * The position and limit of the original buffer won't change after this
     * operation.
     * 
     * @param bb
     * @param offset
     * @return 
     */
    public static ByteBuffer getSlice(ByteBuffer bb, int offset) {
        return getSlice(bb, offset, -1);
    }
}

Related

  1. preservingSlice(final ByteBuffer byteBuffer, final int position, final int limit)
  2. slice(ByteBuffer buf, int pos, int limit)
  3. slice(ByteBuffer buf, int start, int end)
  4. slice(ByteBuffer data)