1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.archive.io;
24
25 import java.io.IOException;
26
27
28 /***
29 * A repositionable stream backed by an array.
30 *
31 * @author pjack
32 */
33 public class ArraySeekInputStream extends SeekInputStream {
34
35
36 /***
37 * The array of bytes to read from.
38 */
39 private byte[] array;
40
41
42 /***
43 * The offset in the array of the next byte to read.
44 */
45 private int offset;
46
47
48 /***
49 * Constructor. Note that changes to the given array will be reflected
50 * in the stream.
51 *
52 * @param array The array to read bytes from.
53 */
54 public ArraySeekInputStream(byte[] array) {
55 this.array = array;
56 this.offset = 0;
57 }
58
59
60 @Override
61 public int read() {
62 if (offset >= array.length) {
63 return -1;
64 }
65 int r = array[offset] & 0xFF;
66 offset++;
67 return r;
68 }
69
70
71 @Override
72 public int read(byte[] buf, int ofs, int len) {
73 if (offset >= array.length) {
74 return 0;
75 }
76 len = Math.min(len, array.length - offset);
77 System.arraycopy(array, offset, buf, ofs, len);
78 offset += len;
79 return len;
80 }
81
82
83 @Override
84 public int read(byte[] buf) {
85 return read(buf, 0, buf.length);
86 }
87
88
89 /***
90 * Returns the position of the stream.
91 */
92 public long position() {
93 return offset;
94 }
95
96
97 /***
98 * Repositions the stream.
99 *
100 * @param p the new position for the stream
101 * @throws IOException if the given position is out of bounds
102 */
103 public void position(long p) throws IOException {
104 if ((p < 0) || (p > array.length)) {
105 throw new IOException("Invalid position: " + p);
106 }
107 offset = (int)p;
108 }
109
110 }