Debian Codegraph @

src/main/org/h2/store/RangeReader.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.IOException;
9 import java.io.Reader;
10
11 import org.h2.util.IOUtils;
12
13 /**
14 * Reader that reads only a specified range from the source reader.
15 */
16 public final class RangeReader extends Reader {
17 private final Reader r;
18
19 private long limit;
20
21 /**
22 * Creates new instance of range reader.
23 *
24 * @param r
25 * source reader
26 * @param offset
27 * offset of the range
28 * @param limit
29 * length of the range
30 * @throws IOException
31 * on I/O exception during seeking to the specified offset
32 */
33 public RangeReader(Reader r, long offset, long limit) throws IOException {
34 this.r = r;
35 this.limit = limit;
36 IOUtils.skipFully(r, offset);
37 }
38
39 @Override
40 public int read() throws IOException {
41 if (limit <= 0) {
42 return -1;
43 }
44 int c = r.read();
45 if (c >= 0) {
46 limit--;
47 }
48 return c;
49 }
50
51 @Override
52 public int read(char cbuf[], int off, int len) throws IOException {
53 if (limit <= 0) {
54 return -1;
55 }
56 if (len > limit) {
57 len = (int) limit;
58 }
59 int cnt = r.read(cbuf, off, len);
60 if (cnt > 0) {
61 limit -= cnt;
62 }
63 return cnt;
64 }
65
66 @Override
67 public long skip(long n) throws IOException {
68 if (n > limit) {
69 n = (int) limit;
70 }
71 n = r.skip(n);
72 limit -= n;
73 return n;
74 }
75
76 @Override
77 public boolean ready() throws IOException {
78 if (limit > 0) {
79 return r.ready();
80 }
81 return false;
82 }
83
84 @Override
85 public boolean markSupported() {
86 return false;
87 }
88
89 @Override
90 public void mark(int readAheadLimit) throws IOException {
91 throw new IOException("mark() not supported");
92 }
93
94 @Override
95 public void reset() throws IOException {
96 throw new IOException("reset() not supported");
97 }
98
99 @Override
100 public void close() throws IOException {
101 r.close();
102 }
103 }