Android ByteBuffer Grow 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;
/*// w w w  . j a  v  a 2s. c o  m
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * 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. extendLimit(ByteBuffer buffer, int numBytes)