Java ByteBuffer Size check(ByteBuffer buffer, int size)

Here you can find the source of check(ByteBuffer buffer, int size)

Description

Check if the buffer has the remaining capacity to hold the number of bytes.

License

Open Source License

Parameter

Parameter Description
buffer a parameter
size a parameter

Declaration

public static ByteBuffer check(ByteBuffer buffer, int size) 

Method Source Code

//package com.java2s;
/**********************************************************************
Copyright (c) 2010 Todd Nine. All rights reserved.
Licensed 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//from ww w. j  av  a2  s .c  o  m
    
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.
    
Contributors :
...
 ***********************************************************************/

import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
    /**
     * Check if the buffer has the remaining capacity to hold the number
     * of bytes.  If not, create a new buffer with the required size and return it
     * @param buffer
     * @param size
     * @return
     */
    public static ByteBuffer check(ByteBuffer buffer, int size) {

        if (buffer == null) {
            ByteBuffer newBuffer = ByteBuffer.allocate(size);
            newBuffer.mark();
            return newBuffer;
        }

        if (buffer.remaining() < size) {

            int position = buffer.position();

            ByteBuffer newBuffer = ByteBuffer.allocate(position + size + 1);
            newBuffer.mark();

            buffer.reset();

            newBuffer.put(Arrays.copyOfRange(buffer.array(), 0, position));

            return newBuffer;

        }

        return buffer;
    }
}

Related

  1. adaptImageSize(final BufferedImage img, final int width, final int height)
  2. addToStringBuilder(StringBuilder sb, ByteBuffer buffer, int size)
  3. calcSize(ByteBuffer buffer)
  4. checkBounds(BufferedImage image, int xStart, int yStart, int width, int height)
  5. checkBufferSize(ByteBuffer buf, int elementSize)
  6. chooseAppropriateTileSize(BufferedImage image)
  7. collidesWithImage(BufferedImage image, int x, int y, int width, int height, boolean pixelPerfect)