/
CBORParser.java
3372 lines (3097 loc) · 114 KB
/
CBORParser.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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.fasterxml.jackson.dataformat.cbor;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.Arrays;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.ParserMinimalBase;
import com.fasterxml.jackson.core.io.IOContext;
import com.fasterxml.jackson.core.io.NumberInput;
import com.fasterxml.jackson.core.json.DupDetector;
import com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer;
import com.fasterxml.jackson.core.util.ByteArrayBuilder;
import com.fasterxml.jackson.core.util.TextBuffer;
import static com.fasterxml.jackson.dataformat.cbor.CBORConstants.*;
public class CBORParser extends ParserMinimalBase
{
/**
* Enumeration that defines all togglable features for CBOR generators.
*/
public enum Feature implements FormatFeature
{
// BOGUS(false)
;
final boolean _defaultState;
final int _mask;
/**
* Method that calculates bit set (flags) of all features that
* are enabled by default.
*/
public static int collectDefaults()
{
int flags = 0;
for (Feature f : values()) {
if (f.enabledByDefault()) {
flags |= f.getMask();
}
}
return flags;
}
private Feature(boolean defaultState) {
_defaultState = defaultState;
_mask = (1 << ordinal());
}
@Override public boolean enabledByDefault() { return _defaultState; }
@Override public int getMask() { return _mask; }
@Override public boolean enabledIn(int flags) { return (flags & _mask) != 0; }
}
private final static Charset UTF8 = Charset.forName("UTF-8");
private final static int[] UTF8_UNIT_CODES = CBORConstants.sUtf8UnitLengths;
// Constants for handling of 16-bit "mini-floats"
private final static double MATH_POW_2_10 = Math.pow(2, 10);
private final static double MATH_POW_2_NEG14 = Math.pow(2, -14);
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
/**
* Codec used for data binding when (if) requested.
*/
protected ObjectCodec _objectCodec;
/*
/**********************************************************
/* Generic I/O state
/**********************************************************
*/
/**
* I/O context for this reader. It handles buffer allocation
* for the reader.
*/
final protected IOContext _ioContext;
/**
* Flag that indicates whether parser is closed or not. Gets
* set when parser is either closed by explicit call
* ({@link #close}) or when end-of-input is reached.
*/
protected boolean _closed;
/*
/**********************************************************
/* Current input data
/**********************************************************
*/
// Note: type of actual buffer depends on sub-class, can't include
/**
* Pointer to next available character in buffer
*/
protected int _inputPtr = 0;
/**
* Index of character after last available one in the buffer.
*/
protected int _inputEnd = 0;
/*
/**********************************************************
/* Current input location information
/**********************************************************
*/
/**
* Number of characters/bytes that were contained in previous blocks
* (blocks that were already processed prior to the current buffer).
*/
protected long _currInputProcessed = 0L;
/**
* Current row location of current point in input buffer, starting
* from 1, if available.
*/
protected int _currInputRow = 1;
/**
* Current index of the first character of the current row in input
* buffer. Needed to calculate column position, if necessary; benefit
* of not having column itself is that this only has to be updated
* once per line.
*/
protected int _currInputRowStart = 0;
/*
/**********************************************************
/* Information about starting location of event
/* Reader is pointing to; updated on-demand
/**********************************************************
*/
// // // Location info at point when current token was started
/**
* Total number of bytes/characters read before start of current token.
* For big (gigabyte-sized) sizes are possible, needs to be long,
* unlike pointers and sizes related to in-memory buffers.
*/
protected long _tokenInputTotal = 0;
/**
* Input row on which current token starts, 1-based
*/
protected int _tokenInputRow = 1;
/**
* Column on input row that current token starts; 0-based (although
* in the end it'll be converted to 1-based)
*/
protected int _tokenInputCol = 0;
/*
/**********************************************************
/* Parsing state
/**********************************************************
*/
/**
* Information about parser context, context in which
* the next token is to be parsed (root, array, object).
*/
protected CBORReadContext _parsingContext;
/**
* Buffer that contains contents of String values, including
* field names if necessary (name split across boundary,
* contains escape sequence, or access needed to char array)
*/
protected final TextBuffer _textBuffer;
/**
* Temporary buffer that is needed if field name is accessed
* using {@link #getTextCharacters} method (instead of String
* returning alternatives)
*/
protected char[] _nameCopyBuffer = null;
/**
* Flag set to indicate whether the field name is available
* from the name copy buffer or not (in addition to its String
* representation being available via read context)
*/
protected boolean _nameCopied = false;
/**
* ByteArrayBuilder is needed if 'getBinaryValue' is called. If so,
* we better reuse it for remainder of content.
*/
protected ByteArrayBuilder _byteArrayBuilder = null;
/**
* We will hold on to decoded binary data, for duration of
* current event, so that multiple calls to
* {@link #getBinaryValue} will not need to decode data more
* than once.
*/
protected byte[] _binaryValue;
/**
* We will keep track of tag value for possible future use.
*/
protected int _tagValue = -1;
/*
/**********************************************************
/* Input source config, state (from ex StreamBasedParserBase)
/**********************************************************
*/
/**
* Input stream that can be used for reading more content, if one
* in use. May be null, if input comes just as a full buffer,
* or if the stream has been closed.
*/
protected InputStream _inputStream;
/**
* Current buffer from which data is read; generally data is read into
* buffer from input source, but in some cases pre-loaded buffer
* is handed to the parser.
*/
protected byte[] _inputBuffer;
/**
* Flag that indicates whether the input buffer is recycable (and
* needs to be returned to recycler once we are done) or not.
*<p>
* If it is not, it also means that parser can NOT modify underlying
* buffer.
*/
protected boolean _bufferRecyclable;
/*
/**********************************************************
/* Additional parsing state
/**********************************************************
*/
/**
* Flag that indicates that the current token has not yet
* been fully processed, and needs to be finished for
* some access (or skipped to obtain the next token)
*/
protected boolean _tokenIncomplete = false;
/**
* Type byte of the current token
*/
protected int _typeByte;
/**
* Helper variables used when dealing with chunked content.
*/
private int _chunkLeft, _chunkEnd;
/*
/**********************************************************
/* Symbol handling, decoding
/**********************************************************
*/
/**
* Symbol table that contains field names encountered so far
*/
final protected ByteQuadsCanonicalizer _symbols;
/**
* Temporary buffer used for name parsing.
*/
protected int[] _quadBuffer = NO_INTS;
/**
* Quads used for hash calculation
*/
protected int _quad1, _quad2, _quad3;
/*
/**********************************************************
/* Constants and fields of former 'JsonNumericParserBase'
/**********************************************************
*/
// Also, we need some numeric constants
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigInteger BI_MIN_INT = BigInteger.valueOf(Integer.MIN_VALUE);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigInteger BI_MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigInteger BI_MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigInteger BI_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigDecimal BD_MIN_LONG = new BigDecimal(BI_MIN_LONG);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigDecimal BD_MAX_LONG = new BigDecimal(BI_MAX_LONG);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigDecimal BD_MIN_INT = new BigDecimal(BI_MIN_INT);
@SuppressWarnings("hiding") // only since 2.9, remove in 3.0
final static BigDecimal BD_MAX_INT = new BigDecimal(BI_MAX_INT);
// Numeric value holders: multiple fields used for
// for efficiency
/**
* Bitfield that indicates which numeric representations
* have been calculated for the current type
*/
protected int _numTypesValid = NR_UNKNOWN;
// First primitives
protected int _numberInt;
protected long _numberLong;
protected float _numberFloat;
protected double _numberDouble;
// And then object types
protected BigInteger _numberBigInt;
protected BigDecimal _numberBigDecimal;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public CBORParser(IOContext ctxt, int parserFeatures, int cborFeatures,
ObjectCodec codec, ByteQuadsCanonicalizer sym,
InputStream in, byte[] inputBuffer, int start, int end,
boolean bufferRecyclable)
{
super(parserFeatures);
_ioContext = ctxt;
_objectCodec = codec;
_symbols = sym;
_inputStream = in;
_inputBuffer = inputBuffer;
_inputPtr = start;
_inputEnd = end;
_bufferRecyclable = bufferRecyclable;
_textBuffer = ctxt.constructTextBuffer();
DupDetector dups = JsonParser.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(parserFeatures)
? DupDetector.rootDetector(this) : null;
_parsingContext = CBORReadContext.createRootContext(dups);
_tokenInputRow = -1;
_tokenInputCol = -1;
}
@Override
public ObjectCodec getCodec() {
return _objectCodec;
}
@Override
public void setCodec(ObjectCodec c) {
_objectCodec = c;
}
/*
/**********************************************************
/* Versioned
/**********************************************************
*/
@Override
public Version version() {
return PackageVersion.VERSION;
}
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
// public JsonParser overrideStdFeatures(int values, int mask)
@Override
public int getFormatFeatures() {
// No parser features, yet
return 0;
}
//public JsonParser overrideFormatFeatures(int values, int mask) {
/*
/**********************************************************
/* Extended API
/**********************************************************
*/
/**
* Method that can be used to access tag id associated with
* the most recently decoded value (whether completely, for
* scalar values, or partially, for Objects/Arrays), if any.
* If no tag was associated with it, -1 is returned.
*
* @since 2.5
*/
public int getCurrentTag() {
return _tagValue;
}
/*
/**********************************************************
/* Abstract impls
/**********************************************************
*/
@Override
public int releaseBuffered(OutputStream out) throws IOException
{
int count = _inputEnd - _inputPtr;
if (count < 1) {
return 0;
}
// let's just advance ptr to end
int origPtr = _inputPtr;
out.write(_inputBuffer, origPtr, count);
return count;
}
@Override
public Object getInputSource() {
return _inputStream;
}
/**
* Overridden since we do not really have character-based locations,
* but we do have byte offset to specify.
*/
@Override
public JsonLocation getTokenLocation()
{
// token location is correctly managed...
return new JsonLocation(_ioContext.getSourceReference(),
_tokenInputTotal, // bytes
-1, -1, (int) _tokenInputTotal); // char offset, line, column
}
/**
* Overridden since we do not really have character-based locations,
* but we do have byte offset to specify.
*/
@Override
public JsonLocation getCurrentLocation()
{
final long offset = _currInputProcessed + _inputPtr;
return new JsonLocation(_ioContext.getSourceReference(),
offset, // bytes
-1, -1, (int) offset); // char offset, line, column
}
/**
* Method that can be called to get the name associated with
* the current event.
*/
@Override
public String getCurrentName() throws IOException
{
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
CBORReadContext parent = _parsingContext.getParent();
return parent.getCurrentName();
}
return _parsingContext.getCurrentName();
}
@Override
public void overrideCurrentName(String name)
{
// Simple, but need to look for START_OBJECT/ARRAY's "off-by-one" thing:
CBORReadContext ctxt = _parsingContext;
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
ctxt = ctxt.getParent();
}
// Unfortunate, but since we did not expose exceptions, need to wrap
try {
ctxt.setCurrentName(name);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public void close() throws IOException {
if (!_closed) {
_closed = true;
_symbols.release();
try {
_closeInput();
} finally {
// as per [JACKSON-324], do in finally block
// Also, internal buffer(s) can now be released as well
_releaseBuffers();
}
}
}
@Override
public boolean isClosed() { return _closed; }
@Override
public CBORReadContext getParsingContext() {
return _parsingContext;
}
/*
/**********************************************************
/* Overridden methods
/**********************************************************
*/
@Override
public boolean hasTextCharacters()
{
if (_currToken == JsonToken.VALUE_STRING) {
// yes; is or can be made available efficiently as char[]
return _textBuffer.hasTextAsCharacters();
}
if (_currToken == JsonToken.FIELD_NAME) {
// not necessarily; possible but:
return _nameCopied;
}
// other types, no benefit from accessing as char[]
return false;
}
/**
* Method called to release internal buffers owned by the base
* reader. This may be called along with {@link #_closeInput} (for
* example, when explicitly closing this reader instance), or
* separately (if need be).
*/
protected void _releaseBuffers() throws IOException
{
if (_bufferRecyclable) {
byte[] buf = _inputBuffer;
if (buf != null) {
_inputBuffer = null;
_ioContext.releaseReadIOBuffer(buf);
}
}
_textBuffer.releaseBuffers();
char[] buf = _nameCopyBuffer;
if (buf != null) {
_nameCopyBuffer = null;
_ioContext.releaseNameCopyBuffer(buf);
}
}
/*
/**********************************************************
/* JsonParser impl
/**********************************************************
*/
@Override
public JsonToken nextToken() throws IOException
{
_numTypesValid = NR_UNKNOWN;
// For longer tokens (text, binary), we'll only read when requested
if (_tokenIncomplete) {
_skipIncomplete();
}
_tokenInputTotal = _currInputProcessed + _inputPtr;
// also: clear any data retained so far
_binaryValue = null;
/* First: need to keep track of lengths of defined-length Arrays and
* Objects (to materialize END_ARRAY/END_OBJECT as necessary);
* as well as handle names for Object entries.
*/
if (_parsingContext.inObject()) {
if (_currToken != JsonToken.FIELD_NAME) {
_tagValue = -1;
// completed the whole Object?
if (!_parsingContext.expectMoreValues()) {
_parsingContext = _parsingContext.getParent();
return (_currToken = JsonToken.END_OBJECT);
}
return (_currToken = _decodeFieldName());
}
} else {
if (!_parsingContext.expectMoreValues()) {
_tagValue = -1;
_parsingContext = _parsingContext.getParent();
return (_currToken = JsonToken.END_ARRAY);
}
}
if (_inputPtr >= _inputEnd) {
if (!loadMore()) {
return _handleCBOREOF();
}
}
int ch = _inputBuffer[_inputPtr++];
int type = (ch >> 5) & 0x7;
// One special case: need to consider tag as prefix first:
if (type == 6) {
_tagValue = Integer.valueOf(_decodeTag(ch & 0x1F));
if (_inputPtr >= _inputEnd) {
if (!loadMore()) {
return _handleCBOREOF();
}
}
ch = _inputBuffer[_inputPtr++];
type = (ch >> 5) & 0x7;
} else {
_tagValue = -1;
}
final int lowBits = ch & 0x1F;
switch (type) {
case 0: // positive int
_numTypesValid = NR_INT;
if (lowBits <= 23) {
_numberInt = lowBits;
} else {
switch (lowBits - 24) {
case 0:
_numberInt = _decode8Bits();
break;
case 1:
_numberInt = _decode16Bits();
break;
case 2:
// 15-Oct-2016, as per [dataformats-binary#30], we got an edge case here
{
int v = _decode32Bits();
if (v >= 0) {
_numberInt = v;
} else {
long l = (long) v;
_numberLong = l & 0xFFFFFFFFL;
_numTypesValid = NR_LONG;
}
}
break;
case 3:
// 15-Oct-2016, as per [dataformats-binary#30], we got an edge case here
{
long l = _decode64Bits();
if (l >= 0L) {
_numberLong = l;
_numTypesValid = NR_LONG;
} else {
_numberBigInt = _bigPositive(l);
_numTypesValid = NR_BIGINT;
}
}
break;
default:
_invalidToken(ch);
}
}
return (_currToken = JsonToken.VALUE_NUMBER_INT);
case 1: // negative int
_numTypesValid = NR_INT;
if (lowBits <= 23) {
_numberInt = -lowBits - 1;
} else {
switch (lowBits - 24) {
case 0:
_numberInt = -_decode8Bits() - 1;
break;
case 1:
_numberInt = -_decode16Bits() - 1;
break;
case 2:
// 15-Oct-2016, as per [dataformats-binary#30], we got an edge case here
{
int v = _decode32Bits();
if (v < 0) {
long unsignedBase = (long) v & 0xFFFFFFFFL;
_numberLong = -unsignedBase - 1L;
_numTypesValid = NR_LONG;
} else {
_numberInt = -v - 1;
}
}
break;
case 3:
// 15-Oct-2016, as per [dataformats-binary#30], we got an edge case here
{
long l = _decode64Bits();
if (l >= 0L) {
_numberLong = -l - 1L;
_numTypesValid = NR_LONG;
} else {
_numberBigInt = _bigNegative(l);
_numTypesValid = NR_BIGINT;
}
}
break;
default:
_invalidToken(ch);
}
}
return (_currToken = JsonToken.VALUE_NUMBER_INT);
case 2: // byte[]
_typeByte = ch;
_tokenIncomplete = true;
if (_tagValue >= 0) {
return _handleTaggedBinary(_tagValue);
}
return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT);
case 3: // String
_typeByte = ch;
_tokenIncomplete = true;
return (_currToken = JsonToken.VALUE_STRING);
case 4: // Array
{
int len = _decodeExplicitLength(lowBits);
if (_tagValue >= 0) {
return _handleTaggedArray(_tagValue, len);
}
_parsingContext = _parsingContext.createChildArrayContext(len);
}
return (_currToken = JsonToken.START_ARRAY);
case 5: // Object
_currToken = JsonToken.START_OBJECT;
{
int len = _decodeExplicitLength(lowBits);
_parsingContext = _parsingContext.createChildObjectContext(len);
}
return _currToken;
case 6: // another tag; not allowed
_reportError("Multiple tags not allowed per value (first tag: "+_tagValue+")");
default: // misc: tokens, floats
switch (lowBits) {
case 20:
return (_currToken = JsonToken.VALUE_FALSE);
case 21:
return (_currToken = JsonToken.VALUE_TRUE);
case 22:
return (_currToken = JsonToken.VALUE_NULL);
case 23:
return (_currToken = _decodeUndefinedValue());
case 25: // 16-bit float...
// As per [http://stackoverflow.com/questions/5678432/decompressing-half-precision-floats-in-javascript]
{
_numberFloat = (float) _decodeHalfSizeFloat();
_numTypesValid = NR_FLOAT;
}
return (_currToken = JsonToken.VALUE_NUMBER_FLOAT);
case 26: // Float32
{
_numberFloat = Float.intBitsToFloat(_decode32Bits());
_numTypesValid = NR_FLOAT;
}
return (_currToken = JsonToken.VALUE_NUMBER_FLOAT);
case 27: // Float64
_numberDouble = Double.longBitsToDouble(_decode64Bits());
_numTypesValid = NR_DOUBLE;
return (_currToken = JsonToken.VALUE_NUMBER_FLOAT);
case 31: // Break
if (_parsingContext.inArray()) {
if (!_parsingContext.hasExpectedLength()) {
_parsingContext = _parsingContext.getParent();
return (_currToken = JsonToken.END_ARRAY);
}
}
// Object end-marker can't occur here
_reportUnexpectedBreak();
}
_invalidToken(ch);
}
return null;
}
protected String _numberToName(int ch, boolean neg) throws IOException
{
final int lowBits = ch & 0x1F;
int i;
if (lowBits <= 23) {
i = lowBits;
} else {
switch (lowBits) {
case 24:
i = _decode8Bits();
break;
case 25:
i = _decode16Bits();
break;
case 26:
i = _decode32Bits();
break;
case 27:
{
long l = _decode64Bits();
if (neg) {
l = -l - 1L;
}
return String.valueOf(l);
}
default:
throw _constructError("Invalid length indicator for ints ("+lowBits+"), token 0x"+Integer.toHexString(ch));
}
}
if (neg) {
i = -i - 1;
}
return String.valueOf(i);
}
protected JsonToken _handleTaggedBinary(int tag) throws IOException
{
// For now all we should get is BigInteger
boolean neg;
if (tag == TAG_BIGNUM_POS) {
neg = false;
} else if (tag == TAG_BIGNUM_NEG) {
neg = true;
} else {
// 12-May-2016, tatu: Since that's all we know, let's otherwise
// just return default Binary data marker
return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT);
}
// First: get the data
_finishToken();
BigInteger nr = new BigInteger(_binaryValue);
if (neg) {
nr = nr.negate();
}
_numberBigInt = nr;
_numTypesValid = NR_BIGINT;
_tagValue = -1;
return (_currToken = JsonToken.VALUE_NUMBER_INT);
}
protected JsonToken _handleTaggedArray(int tag, int len) throws IOException
{
// For simplicity, let's create matching array context -- in perfect
// world that wouldn't be necessarily, but in this one there are
// some constraints that make it necessary
_parsingContext = _parsingContext.createChildArrayContext(len);
// BigDecimal is the only thing we know for sure
if (tag != CBORConstants.TAG_DECIMAL_FRACTION) {
return (_currToken = JsonToken.START_ARRAY);
}
_currToken = JsonToken.START_ARRAY;
// but has to have length of 2; otherwise we have a problem...
if (len != 2) {
_reportError("Unexpected array size ("+len+") for tagged 'bigfloat' value; should have exactly 2 number elements");
}
// and then use recursion to get values
// First: exponent, which MUST be a simple integer value
if (!_checkNextIsIntInArray("bigfloat")) {
_reportError("Unexpected token ("+currentToken()+") as the first part of 'bigfloat' value: should get VALUE_NUMBER_INT");
}
// 27-Nov-2019, tatu: As per [dataformats-binary#139] need to change sign here
int exp = -getIntValue();
// Should get an integer value; int/long/BigInteger
if (!_checkNextIsIntInArray("bigfloat")) {
_reportError("Unexpected token ("+currentToken()+") as the second part of 'bigfloat' value: should get VALUE_NUMBER_INT");
}
// important: check number type here
BigDecimal dec;
NumberType numberType = getNumberType();
if (numberType == NumberType.BIG_INTEGER) {
dec = new BigDecimal(getBigIntegerValue(), exp);
} else {
dec = BigDecimal.valueOf(getLongValue(), exp);
}
// but verify closing END_ARRAY here, as this will now override current token
if (!_checkNextIsEndArray()) {
_reportError("Unexpected token ("+currentToken()+") after 2 elements of 'bigfloat' value");
}
// which needs to be reset here
_numberBigDecimal = dec;
_numTypesValid = NR_BIGDECIMAL;
return (_currToken = JsonToken.VALUE_NUMBER_FLOAT);
}
/**
* Heavily simplified method that does a subset of what {@code nextTokendoes to basically
* only (1) determine that we are getting {@code JsonToken.VALUE_NUMBER_INT} (if not,
* return with no processing) and (2) if so, prepare state so that number accessor
* method will work).
*<p>
* Note that in particular this method DOES NOT reset state that {@code nextToken()} would do,
* but will change current token type to allow access.
*/
protected final boolean _checkNextIsIntInArray(final String typeDesc) throws IOException
{
// We know we are in array, with length prefix so:
if (!_parsingContext.expectMoreValues()) {
_tagValue = -1;
_parsingContext = _parsingContext.getParent();
_currToken = JsonToken.END_ARRAY;
return false;
}
if (_inputPtr >= _inputEnd) {
if (!loadMore()) {
_handleCBOREOF();
return false;
}
}
int ch = _inputBuffer[_inputPtr++];
int type = (ch >> 5) & 0x7;
// 01-Nov-2019, tatu: We may actually need tag so decode it, but do not assign
// (that'd override tag we already have)
int tagValue = -1;
if (type == 6) {
tagValue = _decodeTag(ch & 0x1F);
if ((_inputPtr >= _inputEnd) && !loadMore()) {
_handleCBOREOF();
return false;
}
ch = _inputBuffer[_inputPtr++];
type = (ch >> 5) & 0x7;
}
final int lowBits = ch & 0x1F;
switch (type) {
case 0: // positive int
_numTypesValid = NR_INT;
if (lowBits <= 23) {
_numberInt = lowBits;
} else {
switch (lowBits - 24) {
case 0:
_numberInt = _decode8Bits();
break;
case 1:
_numberInt = _decode16Bits();
break;
case 2:
{
int v = _decode32Bits();
if (v >= 0) {
_numberInt = v;
} else {
long l = (long) v;
_numberLong = l & 0xFFFFFFFFL;
_numTypesValid = NR_LONG;
}
}
break;
case 3:
{
long l = _decode64Bits();
if (l >= 0L) {
_numberLong = l;
_numTypesValid = NR_LONG;
} else {
_numberBigInt = _bigPositive(l);
_numTypesValid = NR_BIGINT;
}
}
break;
default:
_invalidToken(ch);
}
}
_currToken = JsonToken.VALUE_NUMBER_INT;
return true;
case 1: // negative int
_numTypesValid = NR_INT;
if (lowBits <= 23) {
_numberInt = -lowBits - 1;