Java ByteBuffer Capacity ensureCapacity(ByteBuffer buff, int len)

Here you can find the source of ensureCapacity(ByteBuffer buff, int len)

Description

Ensure the byte buffer has the given capacity, plus 1 KB.

License

Open Source License

Parameter

Parameter Description
buff the byte buffer
len the minimum remaining capacity

Return

the byte buffer (possibly a new one)

Declaration

public static ByteBuffer ensureCapacity(ByteBuffer buff, int len) 

Method Source Code

//package com.java2s;
/*//from ww  w  .  j a va 2s .c  o  m
 * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
 * Version 1.0, and under the Eclipse Public License, Version 1.0
 * (http://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Ensure the byte buffer has the given capacity, plus 1 KB. If not, a new,
     * larger byte buffer is created and the data is copied.
     *
     * @param buff the byte buffer
     * @param len the minimum remaining capacity
     * @return the byte buffer (possibly a new one)
     */
    public static ByteBuffer ensureCapacity(ByteBuffer buff, int len) {
        len += 1024;
        if (buff.remaining() > len) {
            return buff;
        }
        return grow(buff, len);
    }

    private static ByteBuffer grow(ByteBuffer buff, int len) {
        len = buff.remaining() + len;
        int capacity = buff.capacity();
        // grow at most 1 MB at a time
        len = Math.max(len, Math.min(capacity + 1024 * 1024, capacity * 2));
        ByteBuffer temp = ByteBuffer.allocate(len);
        buff.flip();
        temp.put(buff);
        return temp;
    }
}

Related

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