forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonIterator.java
More file actions
553 lines (487 loc) · 18.3 KB
/
JsonIterator.java
File metadata and controls
553 lines (487 loc) · 18.3 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
package com.jsoniter;
import com.jsoniter.any.Any;
import com.jsoniter.spi.*;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonIterator implements Closeable {
public Config configCache;
private static boolean isStreamingEnabled = false;
final static ValueType[] valueTypes = new ValueType[256];
InputStream in;
byte[] buf;
int head;
int tail;
int skipStartedAt = -1; // skip should keep bytes starting at this pos
Map<String, Object> tempObjects = null; // used in reflection object decoder
final Slice reusableSlice = new Slice(null, 0, 0);
char[] reusableChars = new char[32];
Object existingObject = null; // the object should be bind to next
static {
for (int i = 0; i < valueTypes.length; i++) {
valueTypes[i] = ValueType.INVALID;
}
valueTypes['"'] = ValueType.STRING;
valueTypes['-'] = ValueType.NUMBER;
valueTypes['0'] = ValueType.NUMBER;
valueTypes['1'] = ValueType.NUMBER;
valueTypes['2'] = ValueType.NUMBER;
valueTypes['3'] = ValueType.NUMBER;
valueTypes['4'] = ValueType.NUMBER;
valueTypes['5'] = ValueType.NUMBER;
valueTypes['6'] = ValueType.NUMBER;
valueTypes['7'] = ValueType.NUMBER;
valueTypes['8'] = ValueType.NUMBER;
valueTypes['9'] = ValueType.NUMBER;
valueTypes['t'] = ValueType.BOOLEAN;
valueTypes['f'] = ValueType.BOOLEAN;
valueTypes['n'] = ValueType.NULL;
valueTypes['['] = ValueType.ARRAY;
valueTypes['{'] = ValueType.OBJECT;
}
private JsonIterator(InputStream in, byte[] buf, int head, int tail) {
this.in = in;
this.buf = buf;
this.head = head;
this.tail = tail;
}
public JsonIterator() {
this(null, new byte[0], 0, 0);
}
public static JsonIterator parse(InputStream in, int bufSize) {
enableStreamingSupport();
return new JsonIterator(in, new byte[bufSize], 0, 0);
}
public static JsonIterator parse(byte[] buf) {
return new JsonIterator(null, buf, 0, buf.length);
}
public static JsonIterator parse(byte[] buf, int head, int tail) {
return new JsonIterator(null, buf, head, tail);
}
public static JsonIterator parse(String str) {
return parse(str.getBytes());
}
public static JsonIterator parse(Slice slice) {
return new JsonIterator(null, slice.data(), slice.head(), slice.tail());
}
public final void reset(byte[] buf) {
this.buf = buf;
this.head = 0;
this.tail = buf.length;
}
public final void reset(byte[] buf, int head, int tail) {
this.buf = buf;
this.head = head;
this.tail = tail;
}
public final void reset(Slice value) {
this.buf = value.data();
this.head = value.head();
this.tail = value.tail();
}
public final void reset(InputStream in) {
JsonIterator.enableStreamingSupport();
this.in = in;
this.head = 0;
this.tail = 0;
}
public final void close() throws IOException {
if (in != null) {
in.close();
}
}
final void unreadByte() {
if (head == 0) {
throw reportError("unreadByte", "unread too many bytes");
}
head--;
}
public final JsonException reportError(String op, String msg) {
int peekStart = head - 10;
if (peekStart < 0) {
peekStart = 0;
}
int peekSize = head - peekStart;
if (head > tail) {
peekSize = tail - peekStart;
}
String peek = new String(buf, peekStart, peekSize);
throw new JsonException(op + ": " + msg + ", head: " + head + ", peek: " + peek + ", buf: " + new String(buf));
}
public final String currentBuffer() {
int peekStart = head - 10;
if (peekStart < 0) {
peekStart = 0;
}
String peek = new String(buf, peekStart, head - peekStart);
return "head: " + head + ", peek: " + peek + ", buf: " + new String(buf);
}
public final boolean readNull() throws IOException {
byte c = IterImpl.nextToken(this);
if (c != 'n') {
unreadByte();
return false;
}
IterImpl.skipFixedBytes(this, 3); // null
return true;
}
public final boolean readBoolean() throws IOException {
byte c = IterImpl.nextToken(this);
if ('t' == c) {
IterImpl.skipFixedBytes(this, 3); // true
return true;
}
if ('f' == c) {
IterImpl.skipFixedBytes(this, 4); // false
return false;
}
throw reportError("readBoolean", "expect t or f, found: " + c);
}
public final short readShort() throws IOException {
int v = readInt();
if (Short.MIN_VALUE <= v && v <= Short.MAX_VALUE) {
return (short) v;
} else {
throw reportError("readShort", "short overflow: " + v);
}
}
public final int readInt() throws IOException {
return IterImplNumber.readInt(this);
}
public final long readLong() throws IOException {
return IterImplNumber.readLong(this);
}
public final boolean readArray() throws IOException {
return IterImplArray.readArray(this);
}
public String readNumberAsString() throws IOException {
IterImplForStreaming.numberChars numberChars = IterImplForStreaming.readNumber(this);
return new String(numberChars.chars, 0, numberChars.charsLength);
}
public static interface ReadArrayCallback {
boolean handle(JsonIterator iter, Object attachment) throws IOException;
}
public final boolean readArrayCB(ReadArrayCallback callback, Object attachment) throws IOException {
return IterImplArray.readArrayCB(this, callback, attachment);
}
public final String readString() throws IOException {
return IterImplString.readString(this);
}
public final Slice readStringAsSlice() throws IOException {
return IterImpl.readSlice(this);
}
public final String readObject() throws IOException {
return IterImplObject.readObject(this);
}
public static interface ReadObjectCallback {
boolean handle(JsonIterator iter, String field, Object attachment) throws IOException;
}
public final void readObjectCB(ReadObjectCallback cb, Object attachment) throws IOException {
IterImplObject.readObjectCB(this, cb, attachment);
}
public final float readFloat() throws IOException {
return IterImplNumber.readFloat(this);
}
public final double readDouble() throws IOException {
return IterImplNumber.readDouble(this);
}
public final BigDecimal readBigDecimal() throws IOException {
// skip whitespace by read next
ValueType valueType = whatIsNext();
if (valueType == ValueType.NULL) {
skip();
return null;
}
if (valueType != ValueType.NUMBER) {
throw reportError("readBigDecimal", "not number");
}
IterImplForStreaming.numberChars numberChars = IterImplForStreaming.readNumber(this);
return new BigDecimal(numberChars.chars, 0, numberChars.charsLength);
}
public final BigInteger readBigInteger() throws IOException {
// skip whitespace by read next
ValueType valueType = whatIsNext();
if (valueType == ValueType.NULL) {
skip();
return null;
}
if (valueType != ValueType.NUMBER) {
throw reportError("readBigDecimal", "not number");
}
IterImplForStreaming.numberChars numberChars = IterImplForStreaming.readNumber(this);
return new BigInteger(new String(numberChars.chars, 0, numberChars.charsLength));
}
public final Any readAny() throws IOException {
try {
return IterImpl.readAny(this);
} catch (ArrayIndexOutOfBoundsException e) {
throw reportError("read", "premature end");
}
}
private final static ReadArrayCallback fillArray = new ReadArrayCallback() {
@Override
public boolean handle(JsonIterator iter, Object attachment) throws IOException {
List list = (List) attachment;
list.add(iter.read());
return true;
}
};
private final static ReadObjectCallback fillObject = new ReadObjectCallback() {
@Override
public boolean handle(JsonIterator iter, String field, Object attachment) throws IOException {
Map map = (Map) attachment;
map.put(field, iter.read());
return true;
}
};
public final Object read() throws IOException {
try {
ValueType valueType = whatIsNext();
switch (valueType) {
case STRING:
return readString();
case NUMBER:
IterImplForStreaming.numberChars numberChars = IterImplForStreaming.readNumber(this);
Double number = Double.valueOf(new String(numberChars.chars, 0, numberChars.charsLength));
if (numberChars.dotFound) {
return number;
}
double doubleNumber = number;
if (doubleNumber == Math.floor(doubleNumber) && !Double.isInfinite(doubleNumber)) {
long longNumber = (long) doubleNumber;
if (longNumber <= Integer.MAX_VALUE && longNumber >= Integer.MIN_VALUE) {
return (int) longNumber;
}
return longNumber;
}
return number;
case NULL:
IterImpl.skipFixedBytes(this, 4);
return null;
case BOOLEAN:
return readBoolean();
case ARRAY:
ArrayList list = new ArrayList(4);
readArrayCB(fillArray, list);
return list;
case OBJECT:
Map map = new HashMap(4);
readObjectCB(fillObject, map);
return map;
default:
throw reportError("read", "unexpected value type: " + valueType);
}
} catch (ArrayIndexOutOfBoundsException e) {
throw reportError("read", "premature end");
}
}
/**
* try to bind to existing object, returned object might not the same instance
*
* @param existingObject the object instance to reuse
* @param <T> object type
* @return data binding result, might not be the same object
* @throws IOException if I/O went wrong
*/
public final <T> T read(T existingObject) throws IOException {
try {
this.existingObject = existingObject;
Class<?> clazz = existingObject.getClass();
String cacheKey = currentConfig().getDecoderCacheKey(clazz);
return (T) Codegen.getDecoder(cacheKey, clazz).decode(this);
} catch (ArrayIndexOutOfBoundsException e) {
throw reportError("read", "premature end");
}
}
private Config currentConfig() {
if (configCache == null) {
configCache = JsoniterSpi.getCurrentConfig();
}
return configCache;
}
/**
* try to bind to existing object, returned object might not the same instance
*
* @param typeLiteral the type object
* @param existingObject the object instance to reuse
* @param <T> object type
* @return data binding result, might not be the same object
* @throws IOException if I/O went wrong
*/
public final <T> T read(TypeLiteral<T> typeLiteral, T existingObject) throws IOException {
try {
this.existingObject = existingObject;
String cacheKey = currentConfig().getDecoderCacheKey(typeLiteral.getType());
return (T) Codegen.getDecoder(cacheKey, typeLiteral.getType()).decode(this);
} catch (ArrayIndexOutOfBoundsException e) {
throw reportError("read", "premature end");
}
}
public final <T> T read(Class<T> clazz) throws IOException {
return (T) read((Type) clazz);
}
public final <T> T read(TypeLiteral<T> typeLiteral) throws IOException {
return (T) read(typeLiteral.getType());
}
public final Object read(Type type) throws IOException {
try {
String cacheKey = currentConfig().getDecoderCacheKey(type);
return Codegen.getDecoder(cacheKey, type).decode(this);
} catch (ArrayIndexOutOfBoundsException e) {
throw reportError("read", "premature end");
}
}
public ValueType whatIsNext() throws IOException {
ValueType valueType = valueTypes[IterImpl.nextToken(this)];
unreadByte();
return valueType;
}
public void skip() throws IOException {
IterImplSkip.skip(this);
}
public static final <T> T deserialize(Config config, String input, Class<T> clazz) {
JsoniterSpi.setCurrentConfig(config);
try {
return deserialize(input.getBytes(), clazz);
} finally {
JsoniterSpi.clearCurrentConfig();
}
}
public static final <T> T deserialize(String input, Class<T> clazz) {
return deserialize(input.getBytes(), clazz);
}
public static final <T> T deserialize(Config config, String input, TypeLiteral<T> typeLiteral) {
JsoniterSpi.setCurrentConfig(config);
try {
return deserialize(input.getBytes(), typeLiteral);
} finally {
JsoniterSpi.clearCurrentConfig();
}
}
public static final <T> T deserialize(String input, TypeLiteral<T> typeLiteral) {
return deserialize(input.getBytes(), typeLiteral);
}
public static final <T> T deserialize(Config config, byte[] input, Class<T> clazz) {
JsoniterSpi.setCurrentConfig(config);
try {
return deserialize(input, clazz);
} finally {
JsoniterSpi.clearCurrentConfig();
}
}
public static final <T> T deserialize(byte[] input, Class<T> clazz) {
int lastNotSpacePos = findLastNotSpacePos(input);
JsonIterator iter = JsonIteratorPool.borrowJsonIterator();
iter.reset(input, 0, lastNotSpacePos);
try {
T val = iter.read(clazz);
if (iter.head != lastNotSpacePos) {
throw iter.reportError("deserialize", "trailing garbage found");
}
return val;
} catch (ArrayIndexOutOfBoundsException e) {
throw iter.reportError("deserialize", "premature end");
} catch (IOException e) {
throw new JsonException(e);
} finally {
JsonIteratorPool.returnJsonIterator(iter);
}
}
public static final <T> T deserialize(Config config, byte[] input, TypeLiteral<T> typeLiteral) {
JsoniterSpi.setCurrentConfig(config);
try {
return deserialize(input, typeLiteral);
} finally {
JsoniterSpi.clearCurrentConfig();
}
}
public static final <T> T deserialize(byte[] input, TypeLiteral<T> typeLiteral) {
int lastNotSpacePos = findLastNotSpacePos(input);
JsonIterator iter = JsonIteratorPool.borrowJsonIterator();
iter.reset(input, 0, lastNotSpacePos);
try {
T val = iter.read(typeLiteral);
if (iter.head != lastNotSpacePos) {
throw iter.reportError("deserialize", "trailing garbage found");
}
return val;
} catch (ArrayIndexOutOfBoundsException e) {
throw iter.reportError("deserialize", "premature end");
} catch (IOException e) {
throw new JsonException(e);
} finally {
JsonIteratorPool.returnJsonIterator(iter);
}
}
public static final Any deserialize(Config config, String input) {
JsoniterSpi.setCurrentConfig(config);
try {
return deserialize(input.getBytes());
} finally {
JsoniterSpi.clearCurrentConfig();
}
}
public static final Any deserialize(String input) {
return deserialize(input.getBytes());
}
public static final Any deserialize(Config config, byte[] input) {
JsoniterSpi.setCurrentConfig(config);
try {
return deserialize(input);
} finally {
JsoniterSpi.clearCurrentConfig();
}
}
public static final Any deserialize(byte[] input) {
int lastNotSpacePos = findLastNotSpacePos(input);
JsonIterator iter = JsonIteratorPool.borrowJsonIterator();
iter.reset(input, 0, lastNotSpacePos);
try {
Any val = iter.readAny();
if (iter.head != lastNotSpacePos) {
throw iter.reportError("deserialize", "trailing garbage found");
}
return val;
} catch (ArrayIndexOutOfBoundsException e) {
throw iter.reportError("deserialize", "premature end");
} catch (IOException e) {
throw new JsonException(e);
} finally {
JsonIteratorPool.returnJsonIterator(iter);
}
}
private static int findLastNotSpacePos(byte[] input) {
for (int i = input.length - 1; i >= 0; i--) {
byte c = input[i];
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') {
return i + 1;
}
}
return 0;
}
public static void setMode(DecodingMode mode) {
Config newConfig = JsoniterSpi.getDefaultConfig().copyBuilder().decodingMode(mode).build();
JsoniterSpi.setDefaultConfig(newConfig);
JsoniterSpi.setCurrentConfig(newConfig);
}
public static void enableStreamingSupport() {
if (isStreamingEnabled) {
return;
}
isStreamingEnabled = true;
try {
DynamicCodegen.enableStreamingSupport();
} catch (JsonException e) {
throw e;
} catch (Exception e) {
throw new JsonException(e);
}
}
}