Debian Codegraph @

src/main/org/h2/store/RangeInputStream.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.store;
7
8 import java.io.FilterInputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11
12 import org.h2.util.IOUtils;
13
14 /**
15 * Input stream that reads only a specified range from the source stream.
16 */
17 public final class RangeInputStream extends FilterInputStream {
18 private long limit;
19
20 /**
21 * Creates new instance of range input stream.
22 *
23 * @param in
24 * source stream
25 * @param offset
26 * offset of the range
27 * @param limit
28 * length of the range
29 * @throws IOException
30 * on I/O exception during seeking to the specified offset
31 */
32 public RangeInputStream(InputStream in, long offset, long limit) throws IOException {
33 super(in);
34 this.limit = limit;
35 IOUtils.skipFully(in, offset);
36 }
37
38 @Override
39 public int read() throws IOException {
40 if (limit <= 0) {
41 return -1;
42 }
43 int b = in.read();
44 if (b >= 0) {
45 limit--;
46 }
47 return b;
48 }
49
50 @Override
51 public int read(byte b[], int off, int len) throws IOException {
52 if (limit <= 0) {
53 return -1;
54 }
55 if (len > limit) {
56 len = (int) limit;
57 }
58 int cnt = in.read(b, off, len);
59 if (cnt > 0) {
60 limit -= cnt;
61 }
62 return cnt;
63 }
64
65 @Override
66 public long skip(long n) throws IOException {
67 if (n > limit) {
68 n = (int) limit;
69 }
70 n = in.skip(n);
71 limit -= n;
72 return n;
73 }
74
75 @Override
76 public int available() throws IOException {
77 int cnt = in.available();
78 if (cnt > limit) {
79 return (int) limit;
80 }
81 return cnt;
82 }
83
84 @Override
85 public void close() throws IOException {
86 in.close();
87 }
88
89 @Override
90 public void mark(int readlimit) {
91 }
92
93 @Override
94 public synchronized void reset() throws IOException {
95 throw new IOException("mark/reset not supported");
96 }
97
98 @Override
99 public boolean markSupported() {
100 return false;
101 }
102 }