Java ByteBuffer Capacity ensureCapacity(ByteBuffer buffer, int capacity)

Here you can find the source of ensureCapacity(ByteBuffer buffer, int capacity)

Description

ensure Capacity

License

Open Source License

Declaration

public static ByteBuffer ensureCapacity(ByteBuffer buffer, int capacity) 

Method Source Code

//package com.java2s;
//  are made available under the terms of the Eclipse Public License v1.0

import java.nio.ByteBuffer;

import java.util.Arrays;

public class Main {
    public static ByteBuffer ensureCapacity(ByteBuffer buffer, int capacity) {
        if (buffer == null)
            return allocate(capacity);

        if (buffer.capacity() >= capacity)
            return buffer;

        if (buffer.hasArray())
            return ByteBuffer.wrap(
                    Arrays.copyOfRange(buffer.array(), buffer.arrayOffset(), buffer.arrayOffset() + capacity),
                    buffer.position(), buffer.remaining());

        throw new UnsupportedOperationException();
    }//from  w  w  w  .  j  a v  a2s.co m

    /** Allocate ByteBuffer in flush mode.
     * The position and limit will both be zero, indicating that the buffer is
     * empty and must be flipped before any data is put to it.
     * @param capacity capacity of the allocated ByteBuffer
     * @return Buffer
     */
    public static ByteBuffer allocate(int capacity) {
        ByteBuffer buf = ByteBuffer.allocate(capacity);
        buf.limit(0);
        return buf;
    }
}

Related

  1. borrowByteBuffer(final int capacity)
  2. ensureCapacity(ByteBuffer buff, int len)
  3. ensureCapacity(ByteBuffer existingBuffer, int newLength)
  4. ensureCapacity(ByteBuffer original, int newCapacity)
  5. expand(ByteBuffer buffer, int newCapacity)
  6. getByteBuffer(int capacity)