-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateInputStream.java
341 lines (299 loc) · 9.79 KB
/
StateInputStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* Copyright 2019 Sabirov Evgenii (sabirov.e@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sabirove.codec.util;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static com.github.sabirove.codec.util.CodecUtil.checkArgument;
import static com.github.sabirove.codec.util.CodecUtil.throwUnchecked;
/**
* {@link FilterInputStream} implementation that can be used to read most of the common Java types
* with binary deserialization semantics.
* Intended to be used in tandem with complementary {@link StateOutputStream} that uses the same encoding format
* to serialize the data.
* <p>
* This is the more robust analog of the {@link DataInputStream} that can be used to implement binary
* deserialization of an arbitrary object ({@code state}) by sequentially reading the individual fields.
*
* @apiNote <ul>
* <li>supports reading the LEB128 variable-length encoded signed/unsigned {@code int} and {@code long} values</li>
* <li>underlying IOExceptions are rethrown as {@link UncheckedIOException} to keep the API clean</li>
* <li>all {@code getXXX} methods will throw {@link EOFException} wrapped in {@link UncheckedIOException}
* when the end of stream reached while reading. Use {@link #isEOF()} if the explicit check is required.</li>
* <li>no nulls will ever be read</li>
* </ul>
* @see StateOutputStream
*/
public final class StateInputStream extends FilterInputStream {
public StateInputStream(InputStream in) {
super(in);
}
public boolean isEOF() {
try {
return in.read() == -1;
} catch (IOException e) {
return throwUnchecked(e);
}
}
public byte getByte() {
try {
int b = in.read();
if (b == -1) {
throw new EOFException();
}
return (byte) b;
} catch (IOException e) {
return throwUnchecked(e);
}
}
public boolean getBoolean() {
byte b = getByte();
boolean out = b == 1;
checkArgument(out || b == 0, "illegal boolean byte value");
return out;
}
public short getShort() {
try {
int b1 = in.read();
int b2 = in.read();
if (b2 == -1) {
throw new EOFException();
}
return (short) ((b1 << 8) | (b2 & 0xff));
} catch (IOException e) {
return throwUnchecked(e);
}
}
public char getChar() {
return (char) getShort();
}
public int getInt() {
try {
InputStream in = this.in;
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
int b4 = in.read();
if (b4 == -1) {
throw new EOFException();
}
return ((b1 << 24) |
((b2 & 0xff) << 16) |
((b3 & 0xff) << 8) |
((b4 & 0xff)));
} catch (IOException e) {
return throwUnchecked(e);
}
}
/**
* @see Varint#readUnsignedVarInt(InputStream)
*/
public int getUnsignedVarInt() {
return Varint.readUnsignedVarInt(in);
}
/**
* @see Varint#readUnsignedVarInt(InputStream)
*/
public int getSignedVarInt() {
return Varint.readUnsignedVarInt(in);
}
public long getLong() {
try {
InputStream in = this.in;
long val = 0;
int b = -1;
for (int offset = Long.SIZE - Byte.SIZE; offset >= 0; offset -= Byte.SIZE) {
b = in.read();
val |= ((long) b) << offset;
}
if (b == -1) {
throw new EOFException();
}
return val;
} catch (IOException e) {
return throwUnchecked(e);
}
}
/**
* @see Varint#readUnsignedVarLong(InputStream)
*/
public long getUnsignedVarLong() {
return Varint.readUnsignedVarLong(in);
}
/**
* @see Varint#readSignedVarLong(InputStream)
*/
public long getSignedVarLong() {
return Varint.readSignedVarLong(in);
}
public float getFloat() {
int bits = getInt();
return Float.intBitsToFloat(bits);
}
public double getDouble() {
long bits = getLong();
return Double.longBitsToDouble(bits);
}
public byte[] getBytes() {
try {
InputStream in = this.in;
int len = Varint.readUnsignedVarInt(in);
byte[] bytes = new byte[len];
if (len > 0) {
for (int i = 0; i < len; i++) {
int b = in.read();
if (b == -1) {
throw new EOFException();
}
bytes[i] = (byte) b;
}
}
return bytes;
} catch (IOException e) {
return throwUnchecked(e);
}
}
public boolean[] getBooleans() {
int size = Varint.readUnsignedVarInt(in);
boolean[] values = new boolean[size];
for (int i = 0; i < size; i++) {
values[i] = getBoolean();
}
return values;
}
public short[] getShorts() {
int size = Varint.readUnsignedVarInt(in);
short[] values = new short[size];
for (int i = 0; i < size; i++) {
values[i] = getShort();
}
return values;
}
public char[] getChars() {
int size = Varint.readUnsignedVarInt(in);
char[] values = new char[size];
for (int i = 0; i < size; i++) {
values[i] = getChar();
}
return values;
}
public int[] getInts() {
int size = Varint.readUnsignedVarInt(in);
int[] values = new int[size];
for (int i = 0; i < size; i++) {
values[i] = getInt();
}
return values;
}
public long[] getLongs() {
int size = Varint.readUnsignedVarInt(in);
long[] values = new long[size];
for (int i = 0; i < size; i++) {
values[i] = getLong();
}
return values;
}
public float[] getFloats() {
int size = Varint.readUnsignedVarInt(in);
float[] values = new float[size];
for (int i = 0; i < size; i++) {
values[i] = getFloat();
}
return values;
}
public double[] getDoubles() {
int size = Varint.readUnsignedVarInt(in);
double[] values = new double[size];
for (int i = 0; i < size; i++) {
values[i] = getDouble();
}
return values;
}
public String getString() {
return new String(getBytes(), UTF_8);
}
public <T extends Enum<T>> T getEnum(Class<T> type) {
int ordinal = Varint.readUnsignedVarInt(in);
return type.getEnumConstants()[ordinal];
}
public UUID getUUID() {
return new UUID(getLong(), getLong());
}
public LocalTime getLocalTime() {
return LocalTime.ofNanoOfDay(getLong());
}
public LocalDate getLocalDate() {
return LocalDate.ofEpochDay(getLong());
}
public LocalDateTime getLocalDateTime() {
return LocalDateTime.of(getLocalDate(), getLocalTime());
}
public ZonedDateTime getZonedDateTime() {
LocalDateTime localDateTime = getLocalDateTime();
ZoneOffset offset = ZoneOffset.ofTotalSeconds(getInt());
return ZonedDateTime.of(localDateTime, offset);
}
public ZoneOffset getZoneOffset() {
return ZoneOffset.ofTotalSeconds(getInt());
}
public Instant getInstant() {
return Instant.ofEpochSecond(getLong(), getInt());
}
public Date getDate() {
return new Date(getLong());
}
public BigInteger getBigInteger() {
return new BigInteger(getBytes());
}
public BigDecimal getBigDecimal() {
return new BigDecimal(getBigInteger(), getInt());
}
public <T> Collection<T> getCollection(Function<StateInputStream, T> elementReader) {
return Stream.generate(() -> elementReader.apply(this))
.limit(Varint.readUnsignedVarInt(in))
.collect(toList());
}
@SuppressWarnings("unchecked")
public <T> T[] getArray(Class<T> elementType, Function<StateInputStream, T> elementReader) {
return Stream.generate(() -> elementReader.apply(this))
.limit(Varint.readUnsignedVarInt(in))
.toArray(s -> (T[]) Array.newInstance(elementType, s));
}
public <K, V> Map<K, V> getMap(Function<StateInputStream, K> keyReader,
Function<StateInputStream, V> valueReader) {
return Stream.generate(() -> null)
.limit(Varint.readUnsignedVarInt(in))
.collect(toMap(
none -> keyReader.apply(this),
none -> valueReader.apply(this)));
}
@Override
public void close() {
try {
super.close();
} catch (IOException e) {
throwUnchecked(e);
}
}
}