Java ByteBuffer Contain contains(ByteBuffer buffer, ByteBuffer subBuffer)

Here you can find the source of contains(ByteBuffer buffer, ByteBuffer subBuffer)

Description

Check is the given buffer contains a given sub-buffer.

License

Apache License

Parameter

Parameter Description
buffer The buffer to search for sequence of bytes in.
subBuffer The buffer to match.

Return

true if buffer contains sub-buffer, false otherwise.

Declaration

public static boolean contains(ByteBuffer buffer, ByteBuffer subBuffer) 

Method Source Code

//package com.java2s;
/*//w  ww .j  av  a 2  s  .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 {
    /**
     * Check is the given buffer contains a given sub-buffer.
     *
     * @param buffer The buffer to search for sequence of bytes in.
     * @param subBuffer The buffer to match.
     *
     * @return true if buffer contains sub-buffer, false otherwise.
     */
    public static boolean contains(ByteBuffer buffer, ByteBuffer subBuffer) {
        int len = subBuffer.remaining();
        if (buffer.remaining() - len < 0)
            return false;

        // adapted form the JDK's String.indexOf()
        byte first = subBuffer.get(subBuffer.position());
        int max = buffer.position() + (buffer.remaining() - len);

        for (int i = buffer.position(); i <= max; i++) {
            /* Look for first character. */
            if (buffer.get(i) != first) {
                while (++i <= max && buffer.get(i) != first) {
                }
            }

            /* (maybe) Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + len - 1;
                for (int k = 1 + subBuffer.position(); j < end && buffer.get(j) == subBuffer.get(k); j++, k++) {
                }

                if (j == end)
                    return true;
            }
        }
        return false;
    }
}

Related

  1. contains(ByteBuffer buffer, byte b)