Debian Codegraph @

src/main/org/h2/store/DataReader.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.EOFException;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.Reader;
12
13 /**
14 * This class is backed by an input stream and supports reading values and
15 * variable size data.
16 */
17 public class DataReader extends Reader {
18
19 private final InputStream in;
20
21 /**
22 * Create a new data reader.
23 *
24 * @param in the input stream
25 */
26 public DataReader(InputStream in) {
27 this.in = in;
28 }
29
30 /**
31 * Read a byte.
32 *
33 * @return the byte
34 * @throws IOException on failure
35 */
36 public byte readByte() throws IOException {
37 int x = in.read();
38 if (x < 0) {
39 throw new FastEOFException();
40 }
41 return (byte) x;
42 }
43
44 /**
45 * Read a variable size integer.
46 *
47 * @return the value
48 * @throws IOException on failure
49 */
50 public int readVarInt() throws IOException {
51 int b = readByte();
52 if (b >= 0) {
53 return b;
54 }
55 int x = b & 0x7f;
56 b = readByte();
57 if (b >= 0) {
58 return x | (b << 7);
59 }
60 x |= (b & 0x7f) << 7;
61 b = readByte();
62 if (b >= 0) {
63 return x | (b << 14);
64 }
65 x |= (b & 0x7f) << 14;
66 b = readByte();
67 if (b >= 0) {
68 return x | b << 21;
69 }
70 return x | ((b & 0x7f) << 21) | (readByte() << 28);
71 }
72
73 /**
74 * Read one character from the input stream.
75 *
76 * @return the character
77 */
78 private char readChar() throws IOException {
79 int x = readByte() & 0xff;
80 if (x < 0x80) {
81 return (char) x;
82 } else if (x >= 0xe0) {
83 return (char) (((x & 0xf) << 12) +
84 ((readByte() & 0x3f) << 6) +
85 (readByte() & 0x3f));
86 } else {
87 return (char) (((x & 0x1f) << 6) +
88 (readByte() & 0x3f));
89 }
90 }
91
92 @Override
93 public void close() throws IOException {
94 // ignore
95 }
96
97 @Override
98 public int read(char[] buff, int off, int len) throws IOException {
99 if (len == 0) {
100 return 0;
101 }
102 int i = 0;
103 try {
104 for (; i < len; i++) {
105 buff[off + i] = readChar();
106 }
107 return len;
108 } catch (EOFException e) {
109 if (i == 0) {
110 return -1;
111 }
112 return i;
113 }
114 }
115
116 /**
117 * Constructing such an EOF exception is fast, because the stack trace is
118 * not filled in. If used in a static context, this will also avoid
119 * classloader memory leaks.
120 */
121 static class FastEOFException extends EOFException {
122
123 private static final long serialVersionUID = 1L;
124
125 @Override
126 public synchronized Throwable fillInStackTrace() {
127 return null;
128 }
129
130 }
131
132 }