org.eclipse.jetty.util.SearchPattern Maven / Gradle / Ivy
The newest version!
//
// ========================================================================
// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* SearchPattern
*
* Fast search for patterns within strings and arrays of bytes.
* Uses an implementation of the Boyer–Moore–Horspool algorithm
* with a 256 character alphabet.
*
* The algorithm has an average-case complexity of O(n)
* on random text and O(nm) in the worst case.
* where:
* m = pattern length
* n = length of data to search
*/
public class SearchPattern
{
static final int alphabetSize = 256;
private int[] table;
private byte[] pattern;
/**
* Produces a SearchPattern instance which can be used
* to find matches of the pattern in data
* @param pattern byte array containing the pattern
* @return a new SearchPattern instance using the given pattern
*/
public static SearchPattern compile(byte[] pattern)
{
return new SearchPattern(Arrays.copyOf(pattern, pattern.length));
}
/**
* Produces a SearchPattern instance which can be used
* to find matches of the pattern in data
* @param pattern string containing the pattern
* @return a new SearchPattern instance using the given pattern
*/
public static SearchPattern compile(String pattern)
{
return new SearchPattern(pattern.getBytes(StandardCharsets.UTF_8));
}
/**
* @param pattern byte array containing the pattern used for matching
*/
private SearchPattern(byte[] pattern)
{
this.pattern = pattern;
if(pattern.length == 0)
throw new IllegalArgumentException("Empty Pattern");
//Build up the pre-processed table for this pattern.
table = new int[alphabetSize];
for(int i = 0; i data.length)
throw new IllegalArgumentException("(offset+length) out of bounds of data[]");
}
/**
* @return The length of the pattern in bytes.
*/
public int getLength()
{
return pattern.length;
}
}