1
2
3
4
5
6 package org.galagosearch.tupleflow;
7
8 import java.io.ByteArrayInputStream;
9 import java.io.DataInputStream;
10 import java.io.IOException;
11
12 /***
13 *
14 * @author trevor
15 */
16 public class MemoryDataStream implements DataStream {
17 byte[] data;
18 int offset;
19 int length;
20 DataInputStream input;
21
22 public MemoryDataStream(byte[] data, int offset, int length) {
23 assert data != null;
24 assert data.length >= offset + length;
25 this.data = data;
26 this.offset = offset;
27 this.length = length;
28 this.input = new DataInputStream(new ByteArrayInputStream(data, offset, length));
29 }
30
31 public MemoryDataStream subStream(long subOffset, long subLength) {
32 assert subOffset <= length;
33 assert subOffset + subLength <= length;
34 return new MemoryDataStream(
35 data, (int) (offset + subOffset),
36 (int) subLength);
37 }
38
39 public long getPosition() {
40 try {
41 return length - input.available();
42 } catch (IOException ex) {
43 return length;
44 }
45 }
46
47 public boolean isDone() {
48 try {
49 return input.available() == 0;
50 } catch (IOException ex) {
51 return true;
52 }
53 }
54
55 public long length() {
56 return length;
57 }
58
59 public void seek(long offset) {
60 if (offset >= length)
61 return;
62
63 try {
64 int needToSkip = (int) (offset - getPosition());
65 while (needToSkip > 0) {
66 int skipped = (int) input.skip(needToSkip);
67 needToSkip -= skipped;
68 }
69 } catch(IOException e) {
70 }
71 }
72
73 public void readFully(byte[] b) throws IOException {
74 input.readFully(b);
75 }
76
77 public void readFully(byte[] b, int off, int len) throws IOException {
78 input.readFully(b, off, len);
79 }
80
81 public int skipBytes(int n) throws IOException {
82 return input.skipBytes(n);
83 }
84
85 public boolean readBoolean() throws IOException {
86 return input.readBoolean();
87 }
88
89 public byte readByte() throws IOException {
90 return input.readByte();
91 }
92
93 public int readUnsignedByte() throws IOException {
94 return input.readUnsignedByte();
95 }
96
97 public short readShort() throws IOException {
98 return input.readShort();
99 }
100
101 public int readUnsignedShort() throws IOException {
102 return input.readUnsignedShort();
103 }
104
105 public char readChar() throws IOException {
106 return input.readChar();
107 }
108
109 public int readInt() throws IOException {
110 return input.readInt();
111 }
112
113 public long readLong() throws IOException {
114 return input.readLong();
115 }
116
117 public float readFloat() throws IOException {
118 return input.readFloat();
119 }
120
121 public double readDouble() throws IOException {
122 return input.readDouble();
123 }
124
125 public String readLine() throws IOException {
126 return input.readLine();
127 }
128
129 public String readUTF() throws IOException {
130 return input.readUTF();
131 }
132 }