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 package org.apache.kahadb.util;
018
019 import java.io.IOException;
020 import java.io.InputStream;
021
022 /**
023 * Very similar to the java.io.ByteArrayInputStream but this version is not
024 * thread safe.
025 */
026 public class ByteArrayInputStream extends InputStream {
027
028 byte buffer[];
029 int limit;
030 int pos;
031 int mark;
032
033 public ByteArrayInputStream(byte data[]) {
034 this(data, 0, data.length);
035 }
036
037 public ByteArrayInputStream(ByteSequence sequence) {
038 this(sequence.getData(), sequence.getOffset(), sequence.getLength());
039 }
040
041 public ByteArrayInputStream(byte data[], int offset, int size) {
042 this.buffer = data;
043 this.mark = offset;
044 this.pos = offset;
045 this.limit = offset + size;
046 }
047
048 public int read() throws IOException {
049 if (pos < limit) {
050 return buffer[pos++] & 0xff;
051 } else {
052 return -1;
053 }
054 }
055
056 public int read(byte[] b) throws IOException {
057 return read(b, 0, b.length);
058 }
059
060 public int read(byte b[], int off, int len) {
061 if (pos < limit) {
062 len = Math.min(len, limit - pos);
063 if (len > 0) {
064 System.arraycopy(buffer, pos, b, off, len);
065 pos += len;
066 }
067 return len;
068 } else {
069 return -1;
070 }
071 }
072
073 public long skip(long len) throws IOException {
074 if (pos < limit) {
075 len = Math.min(len, limit - pos);
076 if (len > 0) {
077 pos += len;
078 }
079 return len;
080 } else {
081 return -1;
082 }
083 }
084
085 public int available() {
086 return limit - pos;
087 }
088
089 public boolean markSupported() {
090 return true;
091 }
092
093 public void mark(int markpos) {
094 mark = pos;
095 }
096
097 public void reset() {
098 pos = mark;
099 }
100 }