Java ByteBuffer Capacity growBuffer(ByteBuffer b, int newCapacity)

Here you can find the source of growBuffer(ByteBuffer b, int newCapacity)

Description

Grow a byte buffer, so it has a minimal capacity or at least the double capacity of the original buffer

License

Apache License

Parameter

Parameter Description
b The original buffer.
newCapacity The minimal requested new capacity.

Return

A byte buffer r with r.capacity() = max(b.capacity()*2,newCapacity) and all the data contained in b copied to the beginning of r.

Declaration

static ByteBuffer growBuffer(ByteBuffer b, int newCapacity) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.nio.ByteBuffer;

public class Main {
    /**// w  w  w .j a v a 2 s . co  m
     * Grow a byte buffer, so it has a minimal capacity or at least
     * the double capacity of the original buffer
     *
     * @param b           The original buffer.
     * @param newCapacity The minimal requested new capacity.
     * @return A byte buffer <code>r</code> with
     * <code>r.capacity() = max(b.capacity()*2,newCapacity)</code> and
     * all the data contained in <code>b</code> copied to the beginning
     * of <code>r</code>.
     */
    static ByteBuffer growBuffer(ByteBuffer b, int newCapacity) {
        b.limit(b.position());
        b.rewind();

        int c2 = b.capacity() * 2;
        ByteBuffer on = ByteBuffer.allocate(c2 < newCapacity ? newCapacity : c2);

        on.put(b);
        return on;
    }
}

Related

  1. ensureCapacity(ByteBuffer existingBuffer, int newLength)
  2. ensureCapacity(ByteBuffer original, int newCapacity)
  3. expand(ByteBuffer buffer, int newCapacity)
  4. getByteBuffer(int capacity)
  5. grow(ByteBuffer buffer, int minCapacityIncrease)
  6. increaseCapacity(ByteBuffer buffer, int size)
  7. leByteBuffer(int capacity)
  8. nativeByteBuffer(int capacity)
  9. newByteBuffer(int margin, int capacity)