forked from amazon-ion/ion-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIonReaderTextSystemX.java
1403 lines (1275 loc) · 48.5 KB
/
IonReaderTextSystemX.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.ion.impl;
import static com.amazon.ion.impl._Private_ScalarConversions.getValueTypeName;
import com.amazon.ion.Decimal;
import com.amazon.ion.IntegerSize;
import com.amazon.ion.IonBlob;
import com.amazon.ion.IonClob;
import com.amazon.ion.IonException;
import com.amazon.ion.IonList;
import com.amazon.ion.IonSequence;
import com.amazon.ion.IonSexp;
import com.amazon.ion.IonStruct;
import com.amazon.ion.IonSystem;
import com.amazon.ion.IonTimestamp;
import com.amazon.ion.IonType;
import com.amazon.ion.IonValue;
import com.amazon.ion.SymbolTable;
import com.amazon.ion.SymbolToken;
import com.amazon.ion.Timestamp;
import com.amazon.ion.UnknownSymbolException;
import com.amazon.ion.impl.IonReaderTextRawTokensX.IonReaderTextTokenException;
import com.amazon.ion.impl.IonTokenConstsX.CharacterSequence;
import com.amazon.ion.impl._Private_ScalarConversions.AS_TYPE;
import com.amazon.ion.impl._Private_ScalarConversions.CantConvertException;
import com.amazon.ion.impl.bin.PresenceBitmap;
import com.amazon.ion.impl.macro.EExpressionArgsReader;
import com.amazon.ion.impl.macro.EncodingContext;
import com.amazon.ion.impl.macro.Expression;
import com.amazon.ion.impl.macro.Macro;
import com.amazon.ion.impl.macro.MacroEvaluator;
import com.amazon.ion.impl.macro.MacroEvaluatorAsIonReader;
import com.amazon.ion.impl.macro.MacroRef;
import com.amazon.ion.impl.macro.MacroTable;
import com.amazon.ion.impl.macro.MutableMacroTable;
import com.amazon.ion.impl.macro.ReaderAdapter;
import com.amazon.ion.impl.macro.ReaderAdapterIonReader;
import com.amazon.ion.impl.macro.SystemMacro;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* This reader calls the {@link IonReaderTextRawX} for low level events.
* It surfaces the reader functions that construct instances
* of various sorts (numbers, java strings, etc). It also
* caches the fieldname and annotations of the current value.
*
* It does not understand symbol tables nor care about them
* the IonTextUserReader is responsible for that.
*
*/
class IonReaderTextSystemX
extends IonReaderTextRawX
implements _Private_ReaderWriter
{
private static int UNSIGNED_BYTE_MAX_VALUE = 255;
SymbolTable _system_symtab;
// The core MacroEvaluator that this core reader delegates to when evaluating a macro invocation.
private final MacroEvaluator macroEvaluator = new MacroEvaluator();
// The IonReader-like MacroEvaluator that this core reader delegates to when evaluating a macro invocation.
protected final MacroEvaluatorAsIonReader macroEvaluatorIonReader = new MacroEvaluatorAsIonReader(macroEvaluator);
// The encoding context (macro table) that is currently active.
private EncodingContext encodingContext = EncodingContext.getDefault();
// Adapts this reader for use in code that supports multiple reader types.
private final ReaderAdapter readerAdapter = new ReaderAdapterIonReader(this);
// Reads encoding directives from the stream.
private EncodingDirectiveReader encodingDirectiveReader = null;
// Reads macro invocation arguments as expressions and feeds them to the MacroEvaluator.
private final EExpressionArgsReader expressionArgsReader = new TextEExpressionArgsReader();
// Indicates whether the reader is currently evaluating an e-expression.
boolean isEvaluatingEExpression = false;
protected IonReaderTextSystemX(UnifiedInputStreamX iis)
{
_system_symtab = _Private_Utils.systemSymtab(1); // TODO check IVM to determine version: amazon-ion/ion-java/issues/19
init_once();
init(iis, IonType.DATAGRAM);
}
// TODO getIntegerType() is duplicated in IonReaderBinarySystemX. It could
// be consolidated into a single location, but that would have to be part
// of a larger refactor of common logic from both IonReader*SystemX classes
// into a base class (the *Value() methods also share a lot of similarity).
public IntegerSize getIntegerSize()
{
if (_value_type != IonType.INT || isNullValue())
{
return null;
}
load_once();
return _Private_ScalarConversions.getIntegerSize(_v.getAuthoritativeType());
}
/**
* Loads a scalar value (except lob values) from the macro evaluator.
*/
private void loadScalarValueFromMacro() {
switch (_value_type) {
case NULL:
_v.setValueToNull(_value_type);
break;
case BOOL:
_v.setValue(macroEvaluatorIonReader.booleanValue());
break;
case INT:
switch (macroEvaluatorIonReader.getIntegerSize()) {
case INT:
_v.setValue(macroEvaluatorIonReader.intValue());
break;
case LONG:
_v.setValue(macroEvaluatorIonReader.longValue());
break;
case BIG_INTEGER:
_v.setValue(macroEvaluatorIonReader.bigIntegerValue());
break;
}
break;
case FLOAT:
_v.setValue(macroEvaluatorIonReader.doubleValue());
break;
case DECIMAL:
_v.setValue(macroEvaluatorIonReader.decimalValue());
break;
case TIMESTAMP:
_v.setValue(macroEvaluatorIonReader.timestampValue());
break;
case SYMBOL:
// TODO determine how to handle symbols with unknown text.
_v.setValue(macroEvaluatorIonReader.stringValue());
break;
case STRING:
_v.setValue(macroEvaluatorIonReader.stringValue());
break;
case CLOB: // see load_lob_contents
case BLOB: // see load_lob_contents
case LIST:
case SEXP:
case STRUCT:
case DATAGRAM:
throw new IllegalStateException(String.format("Type %s is not loaded by this method.", _value_type));
}
}
private void load_once()
{
if (isEvaluatingEExpression) {
loadScalarValueFromMacro();
return;
}
if (_v.isEmpty()) {
try {
load_scalar_value();
}
catch (IOException e) {
throw new IonException(e);
}
}
}
/**
* this checks the state of the raw reader to make sure
* this is valid. It also checks for an existing cached
* value of the correct type. It will either cast the
* current value from an existing type to the type desired
* or it will construct the desired type from the raw
* input in the raw reader
*
* @param value_type desired value type (in local type terms)
* @throws IOException
*/
private final void load_or_cast_cached_value(int value_type) {
load_once();
if (value_type != 0 && !_v.hasValueOfType(value_type)) {
cast_cached_value(value_type);
}
}
enum Radix
{
DECIMAL
{
@Override
boolean isInt(String image, int len)
{
return valueWithinBounds(image, len, MIN_INT_IMAGE, MAX_INT_IMAGE);
}
@Override
boolean isLong(String image, int len)
{
return valueWithinBounds(image, len, MIN_LONG_IMAGE, MAX_LONG_IMAGE);
}
},
HEX
{
@Override
boolean isInt(String image, int len)
{
return valueWithinBounds(image, len, MIN_HEX_INT_IMAGE, MAX_HEX_INT_IMAGE);
}
@Override
boolean isLong(String image, int len)
{
return valueWithinBounds(image, len, MIN_HEX_LONG_IMAGE, MAX_HEX_LONG_IMAGE);
}
},
BINARY
{
@Override
boolean isInt(String image, int len)
{
return valueWithinBounds(image, len, MIN_BINARY_INT_IMAGE, MAX_BINARY_INT_IMAGE);
}
@Override
boolean isLong(String image, int len)
{
return valueWithinBounds(image, len, MIN_BINARY_LONG_IMAGE, MAX_BINARY_LONG_IMAGE);
}
};
private static final char[] MAX_INT_IMAGE = Integer.toString(Integer.MAX_VALUE).toCharArray();
private static final char[] MIN_INT_IMAGE = Integer.toString(Integer.MIN_VALUE).toCharArray();
private static final char[] MAX_LONG_IMAGE = Long.toString(Long.MAX_VALUE).toCharArray();
private static final char[] MIN_LONG_IMAGE = Long.toString(Long.MIN_VALUE).toCharArray();
private static final char[] MAX_BINARY_INT_IMAGE = Integer.toBinaryString(Integer.MAX_VALUE).toCharArray();
private static final char[] MIN_BINARY_INT_IMAGE = ("-" + Integer.toBinaryString(Integer.MIN_VALUE)).toCharArray();
private static final char[] MAX_BINARY_LONG_IMAGE = Long.toBinaryString(Long.MAX_VALUE).toCharArray();
private static final char[] MIN_BINARY_LONG_IMAGE = ("-" + Long.toBinaryString(Long.MIN_VALUE)).toCharArray();
private static final char[] MAX_HEX_INT_IMAGE = Integer.toHexString(Integer.MAX_VALUE).toCharArray();
private static final char[] MIN_HEX_INT_IMAGE = ("-" + Integer.toHexString(Integer.MIN_VALUE)).toCharArray();
private static final char[] MAX_HEX_LONG_IMAGE = Long.toHexString(Long.MAX_VALUE).toCharArray();
private static final char[] MIN_HEX_LONG_IMAGE = ("-" + Long.toHexString(Long.MIN_VALUE)).toCharArray();
abstract boolean isInt(String image, int len);
abstract boolean isLong(String image, int len);
private static boolean valueWithinBounds(String value, int len, char[] minImage, char[] maxImage)
{
boolean negative = value.charAt(0) == '-';
char[] boundaryImage = negative ? minImage : maxImage;
int maxImageLength = boundaryImage.length;
return len < maxImageLength || (len == maxImageLength && magnitudeLessThanOrEqualTo(value, len, boundaryImage));
}
private static boolean magnitudeLessThanOrEqualTo(String lhs, int lhsLen, char[] rhs)
{
assert lhsLen == rhs.length;
for (int i = lhsLen - 1; i >= 0; i--)
{
if (lhs.charAt(i) > rhs[i])
{
return false;
}
}
return true;
}
}
private final void load_scalar_value() throws IOException {
// make sure we're trying to load a scalar value here
switch(_value_type) {
case NULL:
_v.setValueToNull(_null_type);
_v.setAuthoritativeType(AS_TYPE.null_value);
return;
case BOOL:
case INT:
case FLOAT:
case DECIMAL:
case TIMESTAMP:
case SYMBOL:
case STRING:
break;
default:
return;
}
StringBuilder cs = token_contents_load(_scanner.getToken());
int token_type = _scanner.getToken();
if (_value_type == IonType.DECIMAL) {
// we do this here (instead of in the case below
// so that we can modify the value while it's not
// a string, but still in the StringBuilder
for (int ii=0; ii<cs.length(); ii++) {
int c = cs.charAt(ii);
if (c == 'd' || c == 'D') {
cs.setCharAt(ii, 'e');
break;
}
}
} else if (token_type == IonTokenConstsX.TOKEN_HEX || token_type == IonTokenConstsX.TOKEN_BINARY) {
boolean isNegative = (cs.charAt(0) == '-');
// prefix = is_negative ? "-0x" : "0x";
int pos = isNegative ? 1 : 0;
char caseChar = token_type == IonTokenConstsX.TOKEN_HEX ? 'x' : 'b';
if (cs.length() <= (isNegative ? 3 : 2) || Character.toLowerCase(cs.charAt(pos + 1)) != caseChar) {
parse_error("Invalid " + (caseChar == 'x' ? "hexadecimal" : "binary") + " int value.");
}
cs.deleteCharAt(pos);
cs.deleteCharAt(pos);
}
int len = cs.length();
String s = cs.toString();
clear_current_value_buffer();
switch (token_type) {
case IonTokenConstsX.TOKEN_UNKNOWN_NUMERIC:
switch (_value_type) {
case INT:
if (Radix.DECIMAL.isInt(s, len)) {
_v.setValue(Integer.parseInt(s));
}
else if (Radix.DECIMAL.isLong(s, len)) {
_v.setValue(Long.parseLong(s));
}
else {
_v.setValue(new BigInteger(s));
}
break;
case DECIMAL:
// note that the string was modified above when it was a charsequence
try {
_v.setValue(Decimal.valueOf(s));
}
catch (NumberFormatException e) {
parse_error(e);
}
break;
case FLOAT:
try {
_v.setValue(Double.parseDouble(s));
}
catch (NumberFormatException e) {
parse_error(e);
}
break;
case TIMESTAMP:
_v.setValue(Timestamp.valueOf(s));
break;
default:
String message = "unexpected prefectched value type "
+ getType().toString()
+ " encountered handling an unquoted symbol";
parse_error(message);
}
break;
case IonTokenConstsX.TOKEN_INT:
if (Radix.DECIMAL.isInt(s, len)) {
_v.setValue(Integer.parseInt(s));
}
else if (Radix.DECIMAL.isLong(s, len)) {
_v.setValue(Long.parseLong(s));
}
else {
_v.setValue(new BigInteger(s));
}
break;
case IonTokenConstsX.TOKEN_BINARY:
if (Radix.BINARY.isInt(s, len)) {
_v.setValue(Integer.parseInt(s, 2));
}
else if (Radix.BINARY.isLong(s, len)) {
_v.setValue(Long.parseLong(s, 2));
}
else {
_v.setValue(new BigInteger(s, 2));
}
break;
case IonTokenConstsX.TOKEN_HEX:
if (Radix.HEX.isInt(s, len)) {
int v_int = Integer.parseInt(s, 16);
_v.setValue(v_int);
}
else if (Radix.HEX.isLong(s, len)) {
long v_long = Long.parseLong(s, 16);
_v.setValue(v_long);
}
else {
BigInteger v_big_int = new BigInteger(s, 16);
_v.setValue(v_big_int);
}
break;
case IonTokenConstsX.TOKEN_DECIMAL:
try {
_v.setValue(Decimal.valueOf(s));
}
catch (NumberFormatException e) {
parse_error(e);
}
break;
case IonTokenConstsX.TOKEN_FLOAT:
try {
_v.setValue(Double.parseDouble(s));
}
catch (NumberFormatException e) {
parse_error(e);
}
break;
case IonTokenConstsX.TOKEN_TIMESTAMP:
Timestamp t = null;
try {
t = Timestamp.valueOf(s);
}
catch (IllegalArgumentException e) {
parse_error(e);
}
_v.setValue(t);
break;
case IonTokenConstsX.TOKEN_SYMBOL_IDENTIFIER:
// this includes the various value keywords like true
// and nan, in addition to "normal" unquoted symbols
// we check to make sure it's not null first
// since it could be null.symbol (which would
// have the getType() of SYMBOL and would confuse
// us as to what the saved type is)
if (isNullValue()) {
// the raw parser set _null_type when it
// detected the unquoted symbol null in the
// input (which is what isNullValue looks at)
_v.setValueToNull(_null_type);
}
else {
switch(getType()) {
case SYMBOL:
// TODO this is catching SIDs too, using wrong text.
_v.setValue(s);
break;
case FLOAT:
switch (_value_keyword) {
case IonTokenConstsX.KEYWORD_NAN:
_v.setValue(Double.NaN);
break;
default:
String message = "unexpected keyword "
+ s
+ " identified as a FLOAT";
parse_error(message);
}
break;
case BOOL:
switch (_value_keyword) {
case IonTokenConstsX.KEYWORD_TRUE:
_v.setValue(true);
break;
case IonTokenConstsX.KEYWORD_FALSE:
_v.setValue(false);
break;
default:
String message = "unexpected keyword "
+ s
+ " identified as a BOOL";
parse_error(message);
}
break;
default:
String message = "unexpected prefectched value type "
+ getType().toString()
+ " encountered handling an unquoted symbol";
parse_error(message);
}
}
break;
case IonTokenConstsX.TOKEN_SYMBOL_QUOTED:
case IonTokenConstsX.TOKEN_SYMBOL_OPERATOR:
case IonTokenConstsX.TOKEN_STRING_DOUBLE_QUOTE:
_v.setValue(s);
break;
case IonTokenConstsX.TOKEN_STRING_TRIPLE_QUOTE:
// long strings (triple quoted strings) are never
// finished by the raw parser. At most it reads
// the first triple quoted string.
_v.setValue(s);
break;
default:
parse_error("scalar token "+IonTokenConstsX.getTokenName(_scanner.getToken())+"isn't a recognized type");
}
}
private final void cast_cached_value(int new_type)
{
// this should only be called when it actually has to do some work
assert !_v.hasValueOfType(new_type);
if (_v.isNull()) {
return;
}
if (IonType.SYMBOL.equals(_value_type)) {
switch(new_type) {
case AS_TYPE.string_value:
int sid = _v.getInt();
String sym = getSymbolTable().findKnownSymbol(sid);
_v.addValue(sym);
break;
case AS_TYPE.int_value:
sym = _v.getString();
sid = getSymbolTable().findSymbol(sym);
_v.addValue(sid);
break;
default:
{ String message = "can't cast symbol from "
+getValueTypeName(_v.getAuthoritativeType())
+" to "
+getValueTypeName(new_type);
throw new CantConvertException(message);
}
}
}
else {
if (!_v.can_convert(new_type)) {
String message = "can't cast from "
+getValueTypeName(_v.getAuthoritativeType())
+" to "
+getValueTypeName(new_type);
throw new CantConvertException(message);
}
int fnid = _v.get_conversion_fnid(new_type);
_v.cast(fnid);
}
}
/**
* Loads annotations, either from the stream or from a macro.
* @return the annotations.
*/
private SymbolToken[] loadAnnotations() {
SymbolToken[] annotations;
if (isEvaluatingEExpression) {
annotations = macroEvaluatorIonReader.getTypeAnnotationSymbols();
_annotation_count = annotations == null ? 0 : annotations.length;
} else {
// The annotations are eagerly read from the stream into `_annotations`.
annotations = _annotations;
}
return annotations;
}
//
// public value routines
//
public SymbolToken[] getTypeAnnotationSymbols()
{
SymbolToken[] annotations = loadAnnotations();
final int count = _annotation_count;
if (count == 0) return SymbolToken.EMPTY_ARRAY;
resolveAnnotationSymbols(annotations, count);
SymbolToken[] result = new SymbolToken[count];
System.arraycopy(annotations, 0, result, 0, count);
return result;
}
public String[] getTypeAnnotations()
{
SymbolToken[] annotations = loadAnnotations();
resolveAnnotationSymbols(annotations, _annotation_count);
return _Private_Utils.toStrings(annotations, _annotation_count);
}
/**
* Resolve annotations with the current symbol table.
*/
private void resolveAnnotationSymbols(SymbolToken[] annotations, int count) {
SymbolTable symbols = getSymbolTable();
for (int i = 0; i < count; i++) {
SymbolToken sym = annotations[i];
SymbolToken updated = _Private_Utils.localize(symbols, sym);
if (updated != sym) {
annotations[i] = updated;
}
}
}
public boolean isNullValue()
{
return (isEvaluatingEExpression && macroEvaluatorIonReader.isNullValue()) || _v.isNull();
}
public boolean booleanValue()
{
load_or_cast_cached_value(AS_TYPE.boolean_value);
return _v.getBoolean();
}
public double doubleValue()
{
load_or_cast_cached_value(AS_TYPE.double_value);
return _v.getDouble();
}
private void checkIsIntApplicableType()
{
if (_value_type != IonType.INT &&
_value_type != IonType.DECIMAL &&
_value_type != IonType.FLOAT)
{
throw new IllegalStateException("Unexpected value type: " + _value_type);
}
}
public int intValue()
{
checkIsIntApplicableType();
load_or_cast_cached_value(AS_TYPE.int_value);
return _v.getInt();
}
public long longValue()
{
checkIsIntApplicableType();
load_or_cast_cached_value(AS_TYPE.long_value);
return _v.getLong();
}
private void checkIsBigIntegerApplicableType()
{
if (_value_type != IonType.INT &&
_value_type != IonType.FLOAT)
{
throw new IllegalStateException("Unexpected value type: " + _value_type);
}
}
@Override
public BigInteger bigIntegerValue()
{
checkIsBigIntegerApplicableType();
load_or_cast_cached_value(AS_TYPE.bigInteger_value);
if (_v.isNull()) return null;
return _v.getBigInteger();
}
public BigDecimal bigDecimalValue()
{
load_or_cast_cached_value(AS_TYPE.decimal_value);
if (_v.isNull()) return null;
return _v.getBigDecimal();
}
public Decimal decimalValue()
{
load_or_cast_cached_value(AS_TYPE.decimal_value);
if (_v.isNull()) return null;
return _v.getDecimal();
}
public Date dateValue()
{
load_or_cast_cached_value(AS_TYPE.date_value);
if (_v.isNull()) return null;
return _v.getDate();
}
public Timestamp timestampValue()
{
load_or_cast_cached_value(AS_TYPE.timestamp_value);
if (_v.isNull()) return null;
return _v.getTimestamp();
}
public final String stringValue()
{
if (! IonType.isText(_value_type)) throw new IllegalStateException("Unexpected value type: " + _value_type);
if (isNullValue()) return null;
load_or_cast_cached_value(AS_TYPE.string_value);
String text = _v.getString();
if (text == null) {
int sid = _v.getInt();
throw new UnknownSymbolException(sid);
}
return text;
}
/**
* Horrible temporary hack.
*
* @return not null.
*/
@Override
public SymbolTable getSymbolTable()
{
SymbolTable symtab = super.getSymbolTable();
if (symtab == null)
{
symtab = _system_symtab;
}
return symtab;
}
@Override
public final int getFieldId()
{
int id;
if (isEvaluatingEExpression) {
id = getFieldNameSymbol().getSid();
} else {
// Superclass handles hoisting logic
id = super.getFieldId();
}
if (id == SymbolTable.UNKNOWN_SYMBOL_ID)
{
String fieldname = getRawFieldName();
if (fieldname != null)
{
SymbolTable symbols = getSymbolTable();
id = symbols.findSymbol(fieldname);
}
}
return id;
}
@Override
public final String getFieldName()
{
if (isEvaluatingEExpression) {
_field_name = macroEvaluatorIonReader.getFieldName();
}
// Superclass handles hoisting logic
String text = getRawFieldName();
if (text == null)
{
int id = getFieldId();
if (id != SymbolTable.UNKNOWN_SYMBOL_ID)
{
SymbolTable symbols = getSymbolTable();
text = symbols.findKnownSymbol(id);
if (text == null)
{
throw new UnknownSymbolException(id);
}
}
}
return text;
}
@Override
public SymbolToken getFieldNameSymbol()
{
SymbolToken sym;
if (isEvaluatingEExpression) {
sym = macroEvaluatorIonReader.getFieldNameSymbol();
} else {
sym = super.getFieldNameSymbol();
}
if (sym != null)
{
sym = _Private_Utils.localize(getSymbolTable(), sym);
}
return sym;
}
public SymbolToken symbolValue()
{
if (_value_type != IonType.SYMBOL) throw new IllegalStateException("Unexpected value type: " + _value_type);
if (isNullValue()) return null;
load_or_cast_cached_value(AS_TYPE.string_value);
if (! _v.hasValueOfType(AS_TYPE.int_value))
{
cast_cached_value(AS_TYPE.int_value);
}
String text = _v.getString();
int sid = _v.getInt();
return new SymbolTokenImpl(text, sid);
}
//
// blob and clob support routines
//
public int byteSize()
{
ensureLob("byteSize");
long len;
try {
len = load_lob_contents();
}
catch (IOException e) {
throw new IonException(e);
}
if (len < 0 || len > Integer.MAX_VALUE) {
load_lob_length_overflow_error(len);
}
return (int)len;
}
private final void load_lob_length_overflow_error(long len) {
String message = "Size overflow: "
+ _value_type.toString()
+ " size ("
+ Long.toString(len)
+ ") exceeds int ";
throw new IonException(message);
}
private final long load_lob_save_point() throws IOException
{
if (_lob_loaded == LOB_STATE.EMPTY) {
assert(!_current_value_save_point_loaded && _current_value_save_point.isClear());
_scanner.save_point_start(_current_value_save_point);
_scanner.skip_over_lob(_lob_token, _current_value_save_point);
_current_value_save_point_loaded = true;
tokenValueIsFinished();
_lob_loaded = LOB_STATE.READ;
}
long size = _current_value_save_point.length();
return size;
}
private int load_lob_contents() throws IOException
{
if (isEvaluatingEExpression) {
// TODO performance: reduce allocation / copying. Can getBytes() be used?
_lob_bytes = macroEvaluatorIonReader.newBytes();
_lob_actual_len = _lob_bytes.length;
_lob_loaded = LOB_STATE.FINISHED;
return _lob_actual_len;
}
if (_lob_loaded == LOB_STATE.EMPTY) {
load_lob_save_point();
}
if (_lob_loaded == LOB_STATE.READ) {
long raw_size = _current_value_save_point.length();
if (raw_size < 0 || raw_size > _Private_IonConstants.ARRAY_MAXIMUM_SIZE) {
load_lob_length_overflow_error(raw_size);
}
_lob_bytes = new byte[(int)raw_size];
try {
assert(_current_value_save_point_loaded && _current_value_save_point.isDefined());
_scanner.save_point_activate(_current_value_save_point);
_lob_actual_len = readBytes(_lob_bytes, 0, (int)raw_size);
_scanner.save_point_deactivate(_current_value_save_point);
}
catch (IOException e) {
throw new IonException(e);
}
assert(_lob_actual_len <= raw_size);
_lob_loaded = LOB_STATE.FINISHED;
}
assert( _lob_loaded == LOB_STATE.FINISHED);
return _lob_actual_len;
}
private void ensureLob(String apiName)
{
switch (_value_type) {
case CLOB:
case BLOB:
break;
default:
{
String msg =
apiName +
" is only valid if the reader is on a lob value, not a " +
_value_type +
" value";
throw new IllegalStateException(msg);
}
}
}
public byte[] newBytes()
{
ensureLob("newBytes");
byte[] bytes;
int len;
try {
len = load_lob_contents();
}
catch (IOException e) {
throw new IonException(e);
}
bytes = new byte[len];
System.arraycopy(_lob_bytes, 0, bytes, 0, len);
return bytes;
}
public int getBytes(byte[] buffer, int offset, int len)
{
ensureLob("getBytes");
if (_lob_loaded == LOB_STATE.READ) {
// if we've already read through the lob
// (and therefore have it's length and the
// bytes cached in our input buffer) anyway
// just finish the job of converting the
// data to something useful
try {
load_lob_contents();
}
catch (IOException e) {
throw new IonException(e);
}
}
int len_read;
if (_lob_loaded == LOB_STATE.FINISHED) {
// if we have loaded data, just copy it
len_read = len;
if (len_read > _lob_actual_len) {
len_read = _lob_actual_len;
}
System.arraycopy(_lob_bytes, 0, buffer, offset, len_read);
}
else {
// if we haven't loaded it, the we also haven't
// even read over the data - so we'll read if from
// the input source
try {
if (_current_value_save_point_loaded && _lob_value_position > 0) {
if (_current_value_save_point.isActive()) {
_scanner.save_point_deactivate(_current_value_save_point);
}
_scanner.save_point_activate(_current_value_save_point);
_lob_value_position = 0;
}
_scanner.save_point_activate(_current_value_save_point);
len_read = readBytes(buffer, offset, len);
_scanner.save_point_deactivate(_current_value_save_point);
}
catch (IOException e) {
throw new IonException(e);
}
}
return len_read;
}
private int readBytes(byte[] buffer, int offset, int len)
throws IOException
{
int starting_offset = offset;
int c = -1;
switch (_lob_token) {
// BLOB
case IonTokenConstsX.TOKEN_OPEN_DOUBLE_BRACE:
while (len-- > 0) {
c = _scanner.read_base64_byte();
if (c < 0) break;
buffer[offset++] = (byte)c;
}
break;
// CLOB
case IonTokenConstsX.TOKEN_STRING_DOUBLE_QUOTE:
while (len-- > 0) {
c = _scanner.read_double_quoted_char(true);
if (c < 0) {
if (c == CharacterSequence.CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_1
|| c == CharacterSequence.CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_2
|| c == CharacterSequence.CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_3
) {
continue;