Java ByteBuffer Clear clear(ByteBuffer buffer, int position, int length, byte filler)

Here you can find the source of clear(ByteBuffer buffer, int position, int length, byte filler)

Description

clear

License

Open Source License

Declaration

public static void clear(ByteBuffer buffer, int position, int length, byte filler) 

Method Source Code

//package com.java2s;
/**/* www .jav  a  2  s  .c o  m*/
 *  Copyright (c) 2012, 2014 Sme.UP and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 * 
 * Contributors: 
 *   Mattia Rocchi - Initial API and implementation 
 */

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

public class Main {
    public static void clear(ByteBuffer buffer, int position, int length, byte filler) {
        assert buffer != null;

        prepare(buffer, position, length);

        fill(buffer, position, buffer.limit(), filler);
    }

    public static void prepare(ByteBuffer buffer, int position, int length) {
        assert buffer != null;

        if (position > 0) {
            // overflow
            if (position + length > buffer.capacity())
                buffer.limit(buffer.capacity());
            else
                buffer.limit(position + length);

            buffer.position(position);
        } else {
            buffer.position(0);
            if (length > buffer.capacity())
                buffer.limit(buffer.capacity());
            else
                buffer.limit(length);
        }
    }

    public static void fill(ByteBuffer buffer, int position, int length, byte filler) {

        if (buffer.hasArray())
            Arrays.fill(buffer.array(), position, length, filler);
        else {
            for (int i = position; i < length; i++) {
                buffer.put(filler);
            }
        }
    }
}

Related

  1. clear(ByteBuffer b)
  2. clear(ByteBuffer buffer)
  3. clear(ByteBuffer[] buffers)
  4. clearAll(ByteBuffer[] buffers)
  5. clearAndEnsureCapacity(ByteBuffer buffer, int elements)
  6. clearRemaining(ByteBuffer buffer)