Debian Codegraph @

src/com/drew/lang/RandomAccessStreamReader.java

raw symbols SCIP
1 /*
2 * Copyright 2002-2019 Drew Noakes and contributors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * More information about this project is available at:
17 *
18 * https://drewnoakes.com/code/exif/
19 * https://github.com/drewnoakes/metadata-extractor
20 */
21
22 package com.drew.lang;
23
24 import com.drew.lang.annotations.NotNull;
25
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.ArrayList;
29
30 /**
31 * @author Drew Noakes https://drewnoakes.com
32 */
33 public class RandomAccessStreamReader extends RandomAccessReader
34 {
35 public final static int DEFAULT_CHUNK_LENGTH = 2 * 1024;
36
37 @NotNull
38 private final InputStream _stream;
39 private final int _chunkLength;
40
41 private final ArrayList<byte[]> _chunks = new ArrayList<byte[]>();
42
43 private boolean _isStreamFinished;
44 private long _streamLength;
45
46 public RandomAccessStreamReader(@NotNull InputStream stream)
47 {
48 this(stream, DEFAULT_CHUNK_LENGTH, -1);
49 }
50
51 public RandomAccessStreamReader(@NotNull InputStream stream, int chunkLength)
52 {
53 this(stream, chunkLength, -1);
54 }
55
56 public RandomAccessStreamReader(@NotNull InputStream stream, int chunkLength, long streamLength)
57 {
58 if (stream == null)
59 throw new NullPointerException();
60 if (chunkLength <= 0)
61 throw new IllegalArgumentException("chunkLength must be greater than zero");
62
63 _chunkLength = chunkLength;
64 _stream = stream;
65 _streamLength = streamLength;
66 }
67
68 /**
69 * Reads to the end of the stream, in order to determine the total number of bytes.
70 * In general, this is not a good idea for this implementation of {@link RandomAccessReader}.
71 *
72 * @return the length of the data source, in bytes.
73 */
74 @Override
75 public long getLength() throws IOException
76 {
77 if (_streamLength != -1) {
78 return _streamLength;
79 }
80
81 isValidIndex(Integer.MAX_VALUE, 1);
82 assert(_isStreamFinished);
83 return _streamLength;
84 }
85
86 /**
87 * Ensures that the buffered bytes extend to cover the specified index. If not, an attempt is made
88 * to read to that point.
89 * <p>
90 * If the stream ends before the point is reached, a {@link BufferBoundsException} is raised.
91 *
92 * @param index the index from which the required bytes start
93 * @param bytesRequested the number of bytes which are required
94 * @throws BufferBoundsException if the stream ends before the required number of bytes are acquired
95 */
96 @Override
97 protected void validateIndex(int index, int bytesRequested) throws IOException
98 {
99 if (index < 0) {
100 throw new BufferBoundsException(String.format("Attempt to read from buffer using a negative index (%d)", index));
101 } else if (bytesRequested < 0) {
102 throw new BufferBoundsException("Number of requested bytes must be zero or greater");
103 } else if ((long)index + bytesRequested - 1 > Integer.MAX_VALUE) {
104 throw new BufferBoundsException(String.format("Number of requested bytes summed with starting index exceed maximum range of signed 32 bit integers (requested index: %d, requested count: %d)", index, bytesRequested));
105 }
106
107 if (!isValidIndex(index, bytesRequested)) {
108 assert(_isStreamFinished);
109 // TODO test that can continue using an instance of this type after this exception
110 throw new BufferBoundsException(index, bytesRequested, _streamLength);
111 }
112 }
113
114 @Override
115 protected boolean isValidIndex(int index, int bytesRequested) throws IOException
116 {
117 if (index < 0 || bytesRequested < 0) {
118 return false;
119 }
120
121 long endIndexLong = (long)index + bytesRequested - 1;
122
123 if (endIndexLong > Integer.MAX_VALUE) {
124 return false;
125 }
126
127 int endIndex = (int)endIndexLong;
128
129 if (_isStreamFinished) {
130 return endIndex < _streamLength;
131 }
132
133 int chunkIndex = endIndex / _chunkLength;
134
135 // TODO test loading several chunks for a single request
136 while (chunkIndex >= _chunks.size()) {
137 assert (!_isStreamFinished);
138
139 byte[] chunk = new byte[_chunkLength];
140 int totalBytesRead = 0;
141 while (!_isStreamFinished && totalBytesRead != _chunkLength) {
142 int bytesRead = _stream.read(chunk, totalBytesRead, _chunkLength - totalBytesRead);
143 if (bytesRead == -1) {
144 // the stream has ended, which may be ok
145 _isStreamFinished = true;
146 int observedStreamLength = _chunks.size() * _chunkLength + totalBytesRead;
147 if (_streamLength == -1) {
148 _streamLength = observedStreamLength;
149 } else if (_streamLength != observedStreamLength) {
150 assert(false);
151 }
152
153 // check we have enough bytes for the requested index
154 if (endIndex >= _streamLength) {
155 _chunks.add(chunk);
156 return false;
157 }
158 } else {
159 totalBytesRead += bytesRead;
160 }
161 }
162
163 _chunks.add(chunk);
164 }
165
166 return true;
167 }
168
169 @Override
170 public int toUnshiftedOffset(int localOffset)
171 {
172 return localOffset;
173 }
174
175 @Override
176 public byte getByte(int index) throws IOException
177 {
178 assert(index >= 0);
179
180 final int chunkIndex = index / _chunkLength;
181 final int innerIndex = index % _chunkLength;
182 final byte[] chunk = _chunks.get(chunkIndex);
183
184 return chunk[innerIndex];
185 }
186
187 @NotNull
188 @Override
189 public byte[] getBytes(int index, int count) throws IOException
190 {
191 validateIndex(index, count);
192
193 byte[] bytes = new byte[count];
194
195 int remaining = count;
196 int fromIndex = index;
197 int toIndex = 0;
198
199 while (remaining != 0) {
200 int fromChunkIndex = fromIndex / _chunkLength;
201 int fromInnerIndex = fromIndex % _chunkLength;
202 int length = Math.min(remaining, _chunkLength - fromInnerIndex);
203
204 byte[] chunk = _chunks.get(fromChunkIndex);
205
206 System.arraycopy(chunk, fromInnerIndex, bytes, toIndex, length);
207
208 remaining -= length;
209 fromIndex += length;
210 toIndex += length;
211 }
212
213 return bytes;
214 }
215 }