001: /* ArraySeekInputStream
002: *
003: * Created on September 18, 2006
004: *
005: * Copyright (C) 2006 Internet Archive.
006: *
007: * This file is part of the Heritrix web crawler (crawler.archive.org).
008: *
009: * Heritrix is free software; you can redistribute it and/or modify
010: * it under the terms of the GNU Lesser Public License as published by
011: * the Free Software Foundation; either version 2.1 of the License, or
012: * any later version.
013: *
014: * Heritrix is distributed in the hope that it will be useful,
015: * but WITHOUT ANY WARRANTY; without even the implied warranty of
016: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
017: * GNU Lesser Public License for more details.
018: *
019: * You should have received a copy of the GNU Lesser Public License
020: * along with Heritrix; if not, write to the Free Software
021: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
022: */
023: package org.archive.io;
024:
025: import java.io.IOException;
026:
027: /**
028: * A repositionable stream backed by an array.
029: *
030: * @author pjack
031: */
032: public class ArraySeekInputStream extends SeekInputStream {
033:
034: /**
035: * The array of bytes to read from.
036: */
037: private byte[] array;
038:
039: /**
040: * The offset in the array of the next byte to read.
041: */
042: private int offset;
043:
044: /**
045: * Constructor. Note that changes to the given array will be reflected
046: * in the stream.
047: *
048: * @param array The array to read bytes from.
049: */
050: public ArraySeekInputStream(byte[] array) {
051: this .array = array;
052: this .offset = 0;
053: }
054:
055: @Override
056: public int read() {
057: if (offset >= array.length) {
058: return -1;
059: }
060: int r = array[offset] & 0xFF;
061: offset++;
062: return r;
063: }
064:
065: @Override
066: public int read(byte[] buf, int ofs, int len) {
067: if (offset >= array.length) {
068: return 0;
069: }
070: len = Math.min(len, array.length - offset);
071: System.arraycopy(array, offset, buf, ofs, len);
072: offset += len;
073: return len;
074: }
075:
076: @Override
077: public int read(byte[] buf) {
078: return read(buf, 0, buf.length);
079: }
080:
081: /**
082: * Returns the position of the stream.
083: */
084: public long position() {
085: return offset;
086: }
087:
088: /**
089: * Repositions the stream.
090: *
091: * @param p the new position for the stream
092: * @throws IOException if the given position is out of bounds
093: */
094: public void position(long p) throws IOException {
095: if ((p < 0) || (p > array.length)) {
096: throw new IOException("Invalid position: " + p);
097: }
098: offset = (int) p;
099: }
100:
101: }
|