001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.kahadb.util;
019
020 public class ByteSequence {
021
022 public byte[] data;
023 public int offset;
024 public int length;
025
026 public ByteSequence() {
027 }
028
029 public ByteSequence(byte data[]) {
030 this.data = data;
031 this.offset = 0;
032 this.length = data.length;
033 }
034
035 public ByteSequence(byte data[], int offset, int length) {
036 this.data = data;
037 this.offset = offset;
038 this.length = length;
039 }
040
041 public byte[] getData() {
042 return data;
043 }
044
045 public int getLength() {
046 return length;
047 }
048
049 public int getOffset() {
050 return offset;
051 }
052
053 public void setData(byte[] data) {
054 this.data = data;
055 }
056
057 public void setLength(int length) {
058 this.length = length;
059 }
060
061 public void setOffset(int offset) {
062 this.offset = offset;
063 }
064
065 public void compact() {
066 if (length != data.length) {
067 byte t[] = new byte[length];
068 System.arraycopy(data, offset, t, 0, length);
069 data = t;
070 offset = 0;
071 }
072 }
073
074 public int indexOf(ByteSequence needle, int pos) {
075 int max = length - needle.length;
076 for (int i = pos; i < max; i++) {
077 if (matches(needle, i)) {
078 return i;
079 }
080 }
081 return -1;
082 }
083
084 private boolean matches(ByteSequence needle, int pos) {
085 for (int i = 0; i < needle.length; i++) {
086 if( data[offset + pos+ i] != needle.data[needle.offset + i] ) {
087 return false;
088 }
089 }
090 return true;
091 }
092
093 private byte getByte(int i) {
094 return data[offset+i];
095 }
096
097 final public int indexOf(byte value, int pos) {
098 for (int i = pos; i < length; i++) {
099 if (data[offset + i] == value) {
100 return i;
101 }
102 }
103 return -1;
104 }
105 }