Debian Codegraph @

src/main/java/com/fasterxml/jackson/dataformat/smile/async/NonBlockingParserImpl.java

raw ◀ ▶
1 Debian patch touch this file
1 package com.fasterxml.jackson.dataformat.smile.async;
2
3 import java.io.*;
4 import java.lang.ref.SoftReference;
5 //import java.math.BigDecimal;
6 //import java.math.BigInteger;
7 import java.util.Arrays;
8
9 import com.fasterxml.jackson.core.*;
10 import com.fasterxml.jackson.core.base.ParserBase;
11 import com.fasterxml.jackson.core.io.IOContext;
12 import com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer;
13 import com.fasterxml.jackson.dataformat.smile.*;
14
15 import static com.fasterxml.jackson.dataformat.smile.SmileConstants.BYTE_MARKER_END_OF_STRING;
16
17 public class NonBlockingParserImpl
18 extends ParserBase
19 implements NonBlockingParser, NonBlockingInputFeeder
20 {
21 private final static byte[] NO_BYTES = new byte[0];
22 private final static int[] NO_INTS = new int[0];
23 private final static String[] NO_STRINGS = new String[0];
24
25 /*
26 /**********************************************************************
27 /* State constants
28 /**********************************************************************
29 */
30
31 // // // Initial bootstrapping states:
32
33 /**
34 * State right after parser has been constructed: waiting for header
35 * (which may or may not be mandatory).
36 */
37 protected final static int STATE_INITIAL = 0;
38
39
40 /**
41 * State for recognized header marker, either in-feed or initial.
42 */
43 protected final static int STATE_HEADER = 1;
44
45 /**
46 * State in which we are right after decoding a full token.
47 */
48 protected final static int STATE_TOKEN_COMPLETE = 2;
49
50 // // // States for decoding numbers:
51 protected final static int STATE_NUMBER_INT = 10;
52 protected final static int STATE_NUMBER_LONG = 11;
53 protected final static int STATE_NUMBER_BIGINT = 12;
54 protected final static int STATE_NUMBER_FLOAT = 13;
55 protected final static int STATE_NUMBER_DOUBLE = 14;
56 protected final static int STATE_NUMBER_BIGDEC = 15;
57
58 protected final static int STATE_SHORT_ASCII = 20;
59 protected final static int STATE_SHORT_UNICODE = 21;
60 protected final static int STATE_LONG_ASCII = 22;
61 protected final static int STATE_LONG_UNICODE = 23;
62 protected final static int STATE_LONG_SHARED = 24;
63 protected final static int STATE_RAW_BINARY = 25;
64 protected final static int STATE_QUOTED_BINARY = 26;
65
66 /*
67 /**********************************************************************
68 /* Configuration
69 /**********************************************************************
70 */
71
72 /**
73 * Codec used for data binding when (if) requested.
74 */
75 protected ObjectCodec _objectCodec;
76
77 /**
78 * Flag that indicates whether content can legally have raw (unquoted)
79 * binary data. Since this information is included both in header and
80 * in actual binary data blocks there is redundancy, and we want to
81 * ensure settings are compliant. Using application may also want to
82 * know this setting in case it does some direct (random) access.
83 */
84 protected boolean _mayContainRawBinary;
85
86 protected final boolean _cfgRequireHeader;
87
88 /**
89 * Helper object used for low-level recycling of Smile-generator
90 * specific buffers.
91 */
92 final protected SmileBufferRecycler<String> _smileBufferRecycler;
93
94 /*
95 /**********************************************************************
96 /* Input source config
97 /**********************************************************************
98 */
99
100 /**
101 * This buffer is actually provided via {@link NonBlockingInputFeeder}
102 */
103 protected byte[] _inputBuffer = NO_BYTES;
104
105 /**
106 * In addition to current buffer pointer, and end pointer,
107 * we will also need to know number of bytes originally
108 * contained. This is needed to correctly update location
109 * information when the block has been completed.
110 */
111 protected int _origBufferLen;
112
113 // And from ParserBase:
114 // protected int _inputPtr;
115 // protected int _inputEnd;
116
117 /*
118 /**********************************************************************
119 /* Additional parsing state
120 /**********************************************************************
121 */
122
123 /**
124 * Current main decoding state
125 */
126 protected int _state;
127
128 /**
129 * Addition indicator within state; contextually relevant for just that state
130 */
131 protected int _substate;
132
133 /**
134 * Flag that indicates that the current token has not yet
135 * been fully processed, and needs to be finished for
136 * some access (or skipped to obtain the next token)
137 */
138 protected boolean _tokenIncomplete;
139
140 /**
141 * Specific flag that is set when we encountered a 32-bit
142 * floating point value; needed since numeric super classes do
143 * not track distinction between float and double, but Smile
144 * format does, and we want to retain that separation.
145 */
146 protected boolean _got32BitFloat;
147
148 /**
149 * For 32-bit values, we may use this for combining values
150 */
151 protected int _pendingInt;
152
153 /**
154 * For 64-bit values, we may use this for combining values
155 */
156 protected long _pendingLong;
157
158 /**
159 * Flag that is sent when calling application indicates that there will
160 * be no more input to parse.
161 */
162 protected boolean _endOfInput = false;
163
164 /*
165 /**********************************************************************
166 /* Symbol handling, decoding
167 /**********************************************************************
168 */
169
170 /**
171 * Symbol table that contains field names encountered so far
172 */
173 final protected ByteQuadsCanonicalizer _symbols;
174
175 /**
176 * Temporary buffer used for name parsing.
177 */
178 protected int[] _quadBuffer = NO_INTS;
179
180 /*
181 /**********************************************************************
182 /* Name/entity parsing state
183 /**********************************************************************
184 */
185
186 /**
187 * Number of complete quads parsed for current name (quads
188 * themselves are stored in {@link #_quadBuffer}).
189 */
190 protected int _quadCount;
191
192 /**
193 * Bytes parsed for the current, incomplete, quad
194 */
195 protected int _currQuad;
196
197 /**
198 * Number of bytes pending/buffered, stored in {@link #_currQuad}
199 */
200 protected int _currQuadBytes = 0;
201
202 /**
203 * Array of recently seen field names, which may be back referenced
204 * by later fields.
205 * Defaults set to enable handling even if no header found.
206 */
207 protected String[] _seenNames = NO_STRINGS;
208
209 protected int _seenNameCount = 0;
210
211 /**
212 * Array of recently seen field names, which may be back referenced
213 * by later fields
214 * Defaults set to disable handling if no header found.
215 */
216 protected String[] _seenStringValues = null;
217
218 protected int _seenStringValueCount = -1;
219
220 /*
221 /**********************************************************************
222 /* Thread-local recycling
223 /**********************************************************************
224 */
225
226 /**
227 * <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference}
228 * to a buffer recycler used to provide a low-cost
229 * buffer recycling for Smile-specific buffers.
230 */
231 final protected static ThreadLocal<SoftReference<SmileBufferRecycler<String>>> _smileRecyclerRef
232 = new ThreadLocal<SoftReference<SmileBufferRecycler<String>>>();
233
234 /*
235 /**********************************************************************
236 /* Life-cycle
237 /**********************************************************************
238 */
239
240 public NonBlockingParserImpl(IOContext ctxt, int parserFeatures, int smileFeatures,
241 ObjectCodec codec, ByteQuadsCanonicalizer sym)
242 {
243 super(ctxt, parserFeatures);
244 _objectCodec = codec;
245 _symbols = sym;
246
247 _tokenInputRow = -1;
248 _tokenInputCol = -1;
249 _smileBufferRecycler = _smileBufferRecycler();
250
251 _currToken = JsonToken.NOT_AVAILABLE;
252 _state = STATE_INITIAL;
253 _tokenIncomplete = true;
254
255 _cfgRequireHeader = (smileFeatures & SmileParser.Feature.REQUIRE_HEADER.getMask()) != 0;
256 }
257
258 @Override
259 public ObjectCodec getCodec() {
260 return _objectCodec;
261 }
262
263 @Override
264 public void setCodec(ObjectCodec c) {
265 _objectCodec = c;
266 }
267
268 /**
269 * Helper method called when it looks like input might contain the signature;
270 * and it is necessary to detect and handle signature to get configuration
271 * information it might have.
272 *
273 * @return True if valid signature was found and handled; false if not
274 */
275 protected boolean handleSignature(boolean consumeFirstByte, boolean throwException)
276 throws IOException, JsonParseException
277 {
278 if (consumeFirstByte) {
279 ++_inputPtr;
280 }
281 if (_inputPtr >= _inputEnd) {
282 loadMoreGuaranteed();
283 }
284 if (_inputBuffer[_inputPtr] != SmileConstants.HEADER_BYTE_2) {
285 if (throwException) {
286 _reportError("Malformed content: signature not valid, starts with 0x3a but followed by 0x"
287 +Integer.toHexString(_inputBuffer[_inputPtr])+", not 0x29");
288 }
289 return false;
290 }
291 if (++_inputPtr >= _inputEnd) {
292 loadMoreGuaranteed();
293 }
294 if (_inputBuffer[_inputPtr] != SmileConstants.HEADER_BYTE_3) {
295 if (throwException) {
296 _reportError("Malformed content: signature not valid, starts with 0x3a, 0x29, but followed by 0x"
297 +Integer.toHexString(_inputBuffer[_inputPtr])+", not 0xA");
298 }
299 return false;
300 }
301 // Good enough; just need version info from 4th byte...
302 if (++_inputPtr >= _inputEnd) {
303 loadMoreGuaranteed();
304 }
305 int ch = _inputBuffer[_inputPtr++];
306 int versionBits = (ch >> 4) & 0x0F;
307 // but failure with version number is fatal, can not ignore
308 if (versionBits != SmileConstants.HEADER_VERSION_0) {
309 _reportError("Header version number bits (0x"+Integer.toHexString(versionBits)+") indicate unrecognized version; only 0x0 handled by parser");
310 }
311
312 // can avoid tracking names, if explicitly disabled
313 if ((ch & SmileConstants.HEADER_BIT_HAS_SHARED_NAMES) == 0) {
314 _seenNames = null;
315 _seenNameCount = -1;
316 }
317 // conversely, shared string values must be explicitly enabled
318 if ((ch & SmileConstants.HEADER_BIT_HAS_SHARED_STRING_VALUES) != 0) {
319 _seenStringValues = NO_STRINGS;
320 _seenStringValueCount = 0;
321 }
322 _mayContainRawBinary = ((ch & SmileConstants.HEADER_BIT_HAS_RAW_BINARY) != 0);
323 return true;
324 }
325
326 protected final static SmileBufferRecycler<String> _smileBufferRecycler()
327 {
328 SoftReference<SmileBufferRecycler<String>> ref = _smileRecyclerRef.get();
329 SmileBufferRecycler<String> br = (ref == null) ? null : ref.get();
330
331 if (br == null) {
332 br = new SmileBufferRecycler<String>();
333 _smileRecyclerRef.set(new SoftReference<SmileBufferRecycler<String>>(br));
334 }
335 return br;
336 }
337
338 /*
339 /**********************************************************************
340 /* Versioned
341 /**********************************************************************
342 */
343
344 @Override
345 public Version version() {
346 return PackageVersion.VERSION;
347 }
348
349 /*
350 /**********************************************************************
351 /* Former StreamBasedParserBase methods
352 /**********************************************************************
353 */
354
355 @Override
356 public int releaseBuffered(OutputStream out) throws IOException
357 {
358 int count = _inputEnd - _inputPtr;
359 if (count < 1) {
360 return 0;
361 }
362 // let's just advance ptr to end
363 int origPtr = _inputPtr;
364 out.write(_inputBuffer, origPtr, count);
365 return count;
366 }
367
368 @Override
369 public Object getInputSource() {
370 // since input is "pushed", to traditional source...
371 return null;
372 }
373
374 /**
375 * Overridden since we do not really have character-based locations,
376 * but we do have byte offset to specify.
377 */
378 @Override
379 public JsonLocation getTokenLocation()
380 {
381 // token location is correctly managed...
382 return new JsonLocation(_ioContext.getSourceReference(),
383 _tokenInputTotal, // bytes
384 -1, -1, (int) _tokenInputTotal); // char offset, line, column
385 }
386
387 /**
388 * Overridden since we do not really have character-based locations,
389 * but we do have byte offset to specify.
390 */
391 @Override
392 public JsonLocation getCurrentLocation()
393 {
394 final long offset = _currInputProcessed + _inputPtr;
395 return new JsonLocation(_ioContext.getSourceReference(),
396 offset, // bytes
397 -1, -1, (int) offset); // char offset, line, column
398 }
399
400 /*
401 /**********************************************************************
402 /* Low-level reading, other
403 /**********************************************************************
404 */
405
406 @Override
407 protected final boolean loadMore() throws IOException {
408 _throwInternal();
409 return false;
410 }
411
412 /**
413 * Helper method that will try to load at least specified number bytes in
414 * input buffer, possible moving existing data around if necessary
415 */
416 protected final boolean _loadToHaveAtLeast(int minAvailable) throws IOException
417 {
418 _throwInternal();
419 return false;
420 }
421
422 @Override
423 protected void _closeInput() throws IOException {
424 // nothing to do here
425 }
426
427 /*
428 /**********************************************************************
429 /* Overridden methods
430 /**********************************************************************
431 */
432
433 @Override
434 protected void _finishString() throws IOException, JsonParseException {
435 // should never be called; but must be defined for superclass
436 _throwInternal();
437 }
438
439 @Override
440 public void close() throws IOException
441 {
442 super.close();
443 // Merge found symbols, if any:
444 _symbols.release();
445 }
446
447 @Override
448 public boolean hasTextCharacters()
449 {
450 if (_currToken == JsonToken.VALUE_STRING) {
451 // yes; is or can be made available efficiently as char[]
452 return _textBuffer.hasTextAsCharacters();
453 }
454 if (_currToken == JsonToken.FIELD_NAME) {
455 // not necessarily; possible but:
456 return _nameCopied;
457 }
458 // other types, no benefit from accessing as char[]
459 return false;
460 }
461
462 /**
463 * Method called to release internal buffers owned by the base
464 * reader. This may be called along with {@link #_closeInput} (for
465 * example, when explicitly closing this reader instance), or
466 * separately (if need be).
467 */
468 @Override
469 protected void _releaseBuffers() throws IOException
470 {
471 super._releaseBuffers();
472 {
473 String[] nameBuf = _seenNames;
474 if (nameBuf != null && nameBuf.length > 0) {
475 _seenNames = null;
476 /* 28-Jun-2011, tatu: With 1.9, caller needs to clear the buffer;
477 * but we only need to clear up to count as it is not a hash area
478 */
479 if (_seenNameCount > 0) {
480 Arrays.fill(nameBuf, 0, _seenNameCount, null);
481 }
482 _smileBufferRecycler.releaseSeenNamesBuffer(nameBuf);
483 }
484 }
485 {
486 String[] valueBuf = _seenStringValues;
487 if (valueBuf != null && valueBuf.length > 0) {
488 _seenStringValues = null;
489 /* 28-Jun-2011, tatu: With 1.9, caller needs to clear the buffer;
490 * but we only need to clear up to count as it is not a hash area
491 */
492 if (_seenStringValueCount > 0) {
493 Arrays.fill(valueBuf, 0, _seenStringValueCount, null);
494 }
495 _smileBufferRecycler.releaseSeenStringValuesBuffer(valueBuf);
496 }
497 }
498 }
499
500 /*
501 /**********************************************************************
502 /* Extended API
503 /**********************************************************************
504 */
505
506 public boolean mayContainRawBinary() {
507 return _mayContainRawBinary;
508 }
509
510 /*
511 /**********************************************************************
512 /* JsonParser impl
513 /**********************************************************************
514 */
515
516 @Override
517 public JsonToken nextToken() throws IOException, JsonParseException
518 {
519 _numTypesValid = NR_UNKNOWN;
520 // have we already decoded part of event? If so, continue...
521 if (_tokenIncomplete) {
522 // we might be able to optimize by separate skipping, but for now:
523 return _finishToken();
524 }
525 _tokenInputTotal = _currInputProcessed + _inputPtr;
526 // also: clear any data retained so far
527 _binaryValue = null;
528 // Two main modes: values, and field names.
529 if (_parsingContext.inObject() && _currToken != JsonToken.FIELD_NAME) {
530 return (_currToken = _handleFieldName());
531 }
532 if (_inputPtr >= _inputEnd) {
533 return JsonToken.NOT_AVAILABLE;
534 }
535 int ch = _inputBuffer[_inputPtr++];
536 switch ((ch >> 5) & 0x7) {
537 case 0: // short shared string value reference
538 if (ch == 0) { // important: this is invalid, don't accept
539 _reportError("Invalid token byte 0x00");
540 }
541 return _handleSharedString(ch-1);
542
543 case 1: // simple literals, numbers
544 {
545 _numTypesValid = 0;
546 switch (ch & 0x1F) {
547 case 0x00:
548 _textBuffer.resetWithEmpty();
549 return (_currToken = JsonToken.VALUE_STRING);
550 case 0x01:
551 return (_currToken = JsonToken.VALUE_NULL);
552 case 0x02: // false
553 return (_currToken = JsonToken.VALUE_FALSE);
554 case 0x03: // 0x03 == true
555 return (_currToken = JsonToken.VALUE_TRUE);
556 case 0x04:
557 _state = STATE_NUMBER_INT;
558 return _nextInt(0, 0);
559 case 0x05:
560 _numberLong = 0;
561 _state = STATE_NUMBER_LONG;
562 return _nextLong(0, 0L);
563 case 0x06:
564 _state = STATE_NUMBER_BIGINT;
565 return _nextBigInt(0);
566 case 0x07: // illegal
567 break;
568 case 0x08:
569 _pendingInt = 0;
570 _state = STATE_NUMBER_FLOAT;
571 _got32BitFloat = true;
572 return _nextFloat(0, 0);
573 case 0x09:
574 _pendingLong = 0L;
575 _state = STATE_NUMBER_DOUBLE;
576 _got32BitFloat = false;
577 return _nextDouble(0, 0L);
578 case 0x0A:
579 _state = STATE_NUMBER_BIGDEC;
580 return _nextBigDecimal(0);
581 case 0x0B: // illegal
582 break;
583 case 0x1A: // == 0x3A == ':' -> possibly header signature for next chunk?
584 if (!_handleHeader(0)) {
585 return JsonToken.NOT_AVAILABLE;
586 }
587 //if (handleSignature(false, false)) {
588 /* Ok, now; end-marker and header both imply doc boundary and a
589 * 'null token'; but if both are seen, they are collapsed.
590 * We can check this by looking at current token; if it's null,
591 * need to get non-null token
592 */
593 if (_currToken == null) {
594 return nextToken();
595 }
596 return (_currToken = null);
597 }
598 }
599 // and everything else is reserved, for now
600 break;
601 case 2: // tiny ASCII
602 // fall through
603 case 3: // short ASCII
604 // fall through
605 return _nextShortAscii(0);
606
607 case 4: // tiny Unicode
608 // fall through
609 case 5: // short Unicode
610 // No need to decode, unless we have to keep track of back-references (for shared string values)
611 _currToken = JsonToken.VALUE_STRING;
612 if (_seenStringValueCount >= 0) { // shared text values enabled
613 _addSeenStringValue();
614 } else {
615 _tokenIncomplete = true;
616 }
617 return _nextShortUnicode(0);
618
619 case 6: // small integers; zigzag encoded
620 _numberInt = SmileUtil.zigzagDecode(ch & 0x1F);
621 _numTypesValid = NR_INT;
622 return (_currToken = JsonToken.VALUE_NUMBER_INT);
623 case 7: // binary/long-text/long-shared/start-end-markers
624 switch (ch & 0x1F) {
625 case 0x00: // long variable length ASCII
626 return _nextLongAscii(0);
627 case 0x04: // long variable length unicode
628 return _nextLongUnicode(0);
629 case 0x08: // binary, 7-bit
630 return _nextQuotedBinary(0);
631 case 0x0C: // long shared string
632 case 0x0D:
633 case 0x0E:
634 case 0x0F:
635 return _nextLongSharedString(0);
636 // return _handleSharedString(((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF));
637 case 0x18: // START_ARRAY
638 _parsingContext = _parsingContext.createChildArrayContext(-1, -1);
639 return (_currToken = JsonToken.START_ARRAY);
640 case 0x19: // END_ARRAY
641 if (!_parsingContext.inArray()) {
642 _reportMismatchedEndMarker(']', '}');
643 }
644 _parsingContext = _parsingContext.getParent();
645 return (_currToken = JsonToken.END_ARRAY);
646 case 0x1A: // START_OBJECT
647 _parsingContext = _parsingContext.createChildObjectContext(-1, -1);
648 return (_currToken = JsonToken.START_OBJECT);
649 case 0x1B: // not used in this mode; would be END_OBJECT
650 _reportError("Invalid type marker byte 0xFB in value mode (would be END_OBJECT in key mode)");
651 case 0x1D: // binary, raw
652 // should we validate this is legal? (as per header)
653 return _nextRawBinary(0);
654 case 0x1F: // 0xFF, end of content
655 return (_currToken = null);
656 }
657 break;
658 }
659 // If we get this far, type byte is corrupt
660 _reportError("Invalid type marker byte 0x"+Integer.toHexString(ch & 0xFF)+" for expected value token");
661 return null;
662 }
663
664 private final JsonToken _handleSharedString(int index)
665 throws IOException, JsonParseException
666 {
667 if (index >= _seenStringValueCount) {
668 _reportInvalidSharedStringValue(index);
669 }
670 _textBuffer.resetWithString(_seenStringValues[index]);
671 return (_currToken = JsonToken.VALUE_STRING);
672 }
673
674 private final void _addSeenStringValue()
675 throws IOException, JsonParseException
676 {
677 _finishToken();
678 if (_seenStringValueCount < _seenStringValues.length) {
679 // !!! TODO: actually only store char[], first time around?
680 _seenStringValues[_seenStringValueCount++] = _textBuffer.contentsAsString();
681 return;
682 }
683 _expandSeenStringValues();
684 }
685
•686 private final void _expandSeenStringValues() throws IOException
687 {
688 String[] oldShared = _seenStringValues;
689 int len = oldShared.length;
690 String[] newShared;
691 if (len == 0) {
692 newShared = _smileBufferRecycler.allocSeenStringValuesBuffer();
693 if (newShared == null) {
694 newShared = new String[SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH];
695 }
696 } else if (len == SmileConstants.MAX_SHARED_STRING_VALUES) { // too many? Just flush...
697 newShared = oldShared;
698 _seenStringValueCount = 0; // could also clear, but let's not yet bother
699 } else {
700 int newSize = (len == SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH) ? 256 : SmileConstants.MAX_SHARED_STRING_VALUES;
701 newShared = new String[newSize];
702 System.arraycopy(oldShared, 0, newShared, 0, oldShared.length);
703 }
704 _seenStringValues = newShared;
705 _seenStringValues[_seenStringValueCount++] = _textBuffer.contentsAsString();
706 }
707
708 @Override
709 public String getCurrentName() throws IOException, JsonParseException
710 {
711 return _parsingContext.getCurrentName();
712 }
713
714 @Override
715 public NumberType getNumberType()
716 throws IOException, JsonParseException
717 {
718 if (_got32BitFloat) {
719 return NumberType.FLOAT;
720 }
721 return super.getNumberType();
722 }
723
724 /*
725 /**********************************************************************
726 /* AsyncInputFeeder impl
727 /**********************************************************************
728 */
729
730 @Override
731 public final boolean needMoreInput() {
732 return (_inputPtr >=_inputEnd) && !_endOfInput;
733 }
734
735 @Override
736 public void feedInput(byte[] buf, int start, int len)
737 throws IOException
738 {
739 // Must not have remaining input
740 if (_inputPtr < _inputEnd) {
741 throw new IOException("Still have "+(_inputEnd - _inputPtr)+" undecoded bytes, should not call 'feedInput'");
742 }
743 // and shouldn't have been marked as end-of-input
744 if (_endOfInput) {
745 throw new IOException("Already closed, can not feed more input");
746 }
747 // Time to update pointers first
748 _currInputProcessed += _origBufferLen;
749 _currInputRowStart -= _origBufferLen;
750
751 // And then update buffer settings
752 _inputBuffer = buf;
753 _inputPtr = start;
754 _inputEnd = start+len;
755 _origBufferLen = len;
756 }
757
758 @Override
759 public void endOfInput() {
760 _endOfInput = true;
761 }
762
763 /*
764 /**********************************************************************
765 /* NonBlockParser impl (except for NonBlockingInputFeeder)
766 /**********************************************************************
767 */
768
769 @Override
770 public JsonToken peekNextToken() throws IOException, JsonParseException
771 {
772 if (!_tokenIncomplete) {
773 return JsonToken.NOT_AVAILABLE;
774 }
775 switch (_state) {
776 case STATE_INITIAL: // the case if no input has yet been fed
777 return JsonToken.NOT_AVAILABLE;
778 case STATE_HEADER:
779 return JsonToken.NOT_AVAILABLE;
780 case STATE_NUMBER_INT:
781 case STATE_NUMBER_LONG:
782 return JsonToken.VALUE_NUMBER_INT;
783 case STATE_NUMBER_FLOAT:
784 case STATE_NUMBER_DOUBLE:
785 case STATE_NUMBER_BIGDEC:
786 return JsonToken.VALUE_NUMBER_FLOAT;
787 }
788 throw new IllegalStateException("Internal error: unknown 'state', "+_state);
789 }
790
791 /*
792 /**********************************************************************
793 /* Internal methods: second-level parsing:
794 /**********************************************************************
795 */
796
797 private final JsonToken _nextInt(int substate, int value)
798 throws IOException, JsonParseException
799 {
800 while (_inputPtr < _inputEnd) {
801 int b = _inputBuffer[_inputPtr++];
802 if (b < 0) { // got it all; these are last 6 bits
803 value = (value << 6) | (b & 0x3F);
804 _numberInt = SmileUtil.zigzagDecode(value);
805 _numTypesValid = NR_INT;
806 _tokenIncomplete = false;
807 return (_currToken = JsonToken.VALUE_NUMBER_INT);
808 }
809 // can't get too big; 5 bytes is max
810 if (++substate >= 5 ) {
811 _reportError("Corrupt input; 32-bit VInt extends beyond 5 data bytes");
812 }
813 value = (value << 7) | b;
814 }
815 // did not get it all; mark the state so we know where to return:
816 _tokenIncomplete = true;
817 _substate = substate;
818 _pendingInt = value;
819 _state = STATE_NUMBER_INT;
820 return (_currToken = JsonToken.NOT_AVAILABLE);
821 }
822
823 private final JsonToken _nextLong(int substate, long value) throws IOException, JsonParseException
824 {
825 while (_inputPtr < _inputEnd) {
826 int b = _inputBuffer[_inputPtr++];
827 if (b < 0) { // got it all; these are last 6 bits
828 value = (value << 6) | (b & 0x3F);
829 _numberLong = SmileUtil.zigzagDecode(value);
830 _numTypesValid = NR_LONG;
831 _tokenIncomplete = false;
832 return (_currToken = JsonToken.VALUE_NUMBER_INT);
833 }
834 // can't get too big; 10 bytes is max
835 if (++substate >= 10) {
836 _reportError("Corrupt input; 64-bit VInt extends beyond 10 data bytes");
837 }
838 value = (value << 7) | b;
839 }
840 // did not get it all; mark the state so we know where to return:
841 _tokenIncomplete = true;
842 _substate = substate;
843 _pendingLong = value;
844 _state = STATE_NUMBER_LONG;
845 return (_currToken = JsonToken.NOT_AVAILABLE);
846 }
847
848 private final JsonToken _nextBigInt(int substate) throws IOException, JsonParseException
849 {
850 // !!! TBI
851 _tokenIncomplete = true;
852 _substate = substate;
853 // _pendingLong = value;
854 _state = STATE_NUMBER_BIGDEC;
855 return (_currToken = JsonToken.NOT_AVAILABLE);
856 }
857
858 /*
859 private final boolean _finishBigInteger()
860 throws IOException, JsonParseException
861 {
862 byte[] raw = _read7BitBinaryWithLength();
863 if (raw == null) {
864 return false;
865 }
866 _numberBigInt = new BigInteger(raw);
867 _numTypesValid = NR_BIGINT;
868 return true;
869 }
870 */
871
872 private final JsonToken _nextFloat(int substate, int value) throws IOException, JsonParseException
873 {
874 while (_inputPtr < _inputEnd) {
875 int b = _inputBuffer[_inputPtr++];
876 value = (value << 7) + b;
877 if (++substate == 5) { // done!
878 _numberDouble = (double) Float.intBitsToFloat(value);
879 _numTypesValid = NR_DOUBLE;
880 _tokenIncomplete = false;
881 return (_currToken = JsonToken.VALUE_NUMBER_FLOAT);
882 }
883 }
884 _tokenIncomplete = true;
885 _substate = substate;
886 _pendingInt = value;
887 _state = STATE_NUMBER_FLOAT;
888 return (_currToken = JsonToken.NOT_AVAILABLE);
889 }
890
891 private final JsonToken _nextDouble(int substate, long value) throws IOException, JsonParseException
892 {
893 while (_inputPtr < _inputEnd) {
894 int b = _inputBuffer[_inputPtr++];
895 value = (value << 7) + b;
896 if (++substate == 10) { // done!
897 _numberDouble = Double.longBitsToDouble(value);
898 _numTypesValid = NR_DOUBLE;
899 _tokenIncomplete = false;
900 return (_currToken = JsonToken.VALUE_NUMBER_FLOAT);
901 }
902 }
903 _tokenIncomplete = true;
904 _substate = substate;
905 _pendingLong = value;
906 _state = STATE_NUMBER_DOUBLE;
907 return (_currToken = JsonToken.NOT_AVAILABLE);
908 }
909
910 private final JsonToken _nextBigDecimal(int substate) throws IOException, JsonParseException
911 {
912 // !!! TBI
913 _tokenIncomplete = true;
914 _substate = substate;
915 // _pendingLong = value;
916 _state = STATE_NUMBER_BIGDEC;
917 return (_currToken = JsonToken.NOT_AVAILABLE);
918 }
919 /*
920 private final void _finishBigDecimal()
921 throws IOException, JsonParseException
922 {
923 int scale = SmileUtil.zigzagDecode(_readUnsignedVInt());
924 byte[] raw = _read7BitBinaryWithLength();
925 _numberBigDecimal = new BigDecimal(new BigInteger(raw), scale);
926 _numTypesValid = NR_BIGDECIMAL;
927 }
928
929 */
930
931 /*
932 private final int _readUnsignedVInt()
933 throws IOException, JsonParseException
934 {
935 int value = 0;
936 while (true) {
937 if (_inputPtr >= _inputEnd) {
938 loadMoreGuaranteed();
939 }
940 int i = _inputBuffer[_inputPtr++];
941 if (i < 0) { // last byte
942 value = (value << 6) + (i & 0x3F);
943 return value;
944 }
945 value = (value << 7) + i;
946 }
947 }
948 */
949
950 private final boolean _handleHeader(int substate) throws IOException, JsonParseException
951 {
952 while (_inputPtr < _inputEnd) {
953 byte b = _inputBuffer[_inputPtr++];
954 switch (substate) {
955 case 0: // after first byte
956 if (b != SmileConstants.HEADER_BYTE_2) {
957 _reportError("Malformed content: header signature not valid, starts with 0x3a but followed by 0x"
958 +Integer.toHexString(_inputBuffer[_inputPtr] & 0xFF)+", not 0x29");
959 }
960 break;
961 case 1:
962 if (b != SmileConstants.HEADER_BYTE_3) {
963 _reportError("Malformed content: signature not valid, starts with 0x3a, 0x29, but followed by 0x"
964 +Integer.toHexString(_inputBuffer[_inputPtr & 0xFF])+", not 0x0A");
965 }
966 break;
967 case 2: // ok, here be the version, config bits...
968 int versionBits = (b >> 4) & 0x0F;
969 // but failure with version number is fatal, can not ignore
970 if (versionBits != SmileConstants.HEADER_VERSION_0) {
971 _reportError("Header version number bits (0x"+Integer.toHexString(versionBits)+") indicate unrecognized version; only 0x0 handled by parser");
972 }
973
974 // can avoid tracking names, if explicitly disabled
975 if ((b & SmileConstants.HEADER_BIT_HAS_SHARED_NAMES) == 0) {
976 _seenNames = null;
977 _seenNameCount = -1;
978 }
979 // conversely, shared string values must be explicitly enabled
980 if ((b & SmileConstants.HEADER_BIT_HAS_SHARED_STRING_VALUES) != 0) {
981 _seenStringValues = NO_STRINGS;
982 _seenStringValueCount = 0;
983 }
984 _mayContainRawBinary = ((b & SmileConstants.HEADER_BIT_HAS_RAW_BINARY) != 0);
985 _tokenIncomplete = false;
986 return true;
987 }
988 }
989 _tokenIncomplete = true;
990 _state = STATE_HEADER;
991 _substate = substate;
992 return false;
993 }
994
995 private final JsonToken _nextShortAscii(int substate) throws IOException, JsonParseException
996 {
997 _state = STATE_SHORT_ASCII;
998 _tokenIncomplete = true;
999 _substate = substate;
1000 return (_currToken = JsonToken.NOT_AVAILABLE);
1001 }
1002
1003 private final JsonToken _nextShortUnicode(int substate) throws IOException, JsonParseException
1004 {
1005 _state = STATE_SHORT_UNICODE;
1006 _tokenIncomplete = true;
1007 _substate = substate;
1008 return (_currToken = JsonToken.NOT_AVAILABLE);
1009 }
1010
1011 /*
1012 protected final void _decodeShortAsciiValue(int len)
1013 throws IOException, JsonParseException
1014 {
1015 if ((_inputEnd - _inputPtr) < len) {
1016 _loadToHaveAtLeast(len);
1017 }
1018 // Note: we count on fact that buffer must have at least 'len' (<= 64) empty char slots
1019 final char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
1020 int outPtr = 0;
1021 final byte[] inBuf = _inputBuffer;
1022 int inPtr = _inputPtr;
1023
1024 // meaning: regular tight loop is no slower, typically faster here:
1025 for (final int end = inPtr + len; inPtr < end; ++inPtr) {
1026 outBuf[outPtr++] = (char) inBuf[inPtr];
1027 }
1028
1029 _inputPtr = inPtr;
1030 _textBuffer.setCurrentLength(len);
1031 }
1032
1033 protected final void _decodeShortUnicodeValue(int len)
1034 throws IOException, JsonParseException
1035 {
1036 if ((_inputEnd - _inputPtr) < len) {
1037 _loadToHaveAtLeast(len);
1038 }
1039 int outPtr = 0;
1040 char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
1041 int inPtr = _inputPtr;
1042 _inputPtr += len;
1043 final int[] codes = SmileConstants.sUtf8UnitLengths;
1044 final byte[] inputBuf = _inputBuffer;
1045 for (int end = inPtr + len; inPtr < end; ) {
1046 int i = inputBuf[inPtr++] & 0xFF;
1047 int code = codes[i];
1048 if (code != 0) {
1049 // trickiest one, need surrogate handling
1050 switch (code) {
1051 case 1:
1052 i = ((i & 0x1F) << 6) | (inputBuf[inPtr++] & 0x3F);
1053 break;
1054 case 2:
1055 i = ((i & 0x0F) << 12)
1056 | ((inputBuf[inPtr++] & 0x3F) << 6)
1057 | (inputBuf[inPtr++] & 0x3F);
1058 break;
1059 case 3:
1060 i = ((i & 0x07) << 18)
1061 | ((inputBuf[inPtr++] & 0x3F) << 12)
1062 | ((inputBuf[inPtr++] & 0x3F) << 6)
1063 | (inputBuf[inPtr++] & 0x3F);
1064 // note: this is the codepoint value; need to split, too
1065 i -= 0x10000;
1066 outBuf[outPtr++] = (char) (0xD800 | (i >> 10));
1067 i = 0xDC00 | (i & 0x3FF);
1068 break;
1069 default: // invalid
1070 _reportError("Invalid byte "+Integer.toHexString(i)+" in short Unicode text block");
1071 }
1072 }
1073 outBuf[outPtr++] = (char) i;
1074 }
1075 _textBuffer.setCurrentLength(outPtr);
1076 }
1077 */
1078
1079 private final JsonToken _nextLongAscii(int substate) throws IOException, JsonParseException
1080 {
1081 // did not get it all; mark the state so we know where to return:
1082 _state = STATE_LONG_ASCII;
1083 _tokenIncomplete = true;
1084 _substate = substate;
1085 return (_currToken = JsonToken.NOT_AVAILABLE);
1086 }
1087
1088 /*
1089 private final void _decodeLongAscii()
1090 throws IOException, JsonParseException
1091 {
1092 int outPtr = 0;
1093 char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
1094 main_loop:
1095 while (true) {
1096 if (_inputPtr >= _inputEnd) {
1097 loadMoreGuaranteed();
1098 }
1099 int inPtr = _inputPtr;
1100 int left = _inputEnd - inPtr;
1101 if (outPtr >= outBuf.length) {
1102 outBuf = _textBuffer.finishCurrentSegment();
1103 outPtr = 0;
1104 }
1105 left = Math.min(left, outBuf.length - outPtr);
1106 do {
1107 byte b = _inputBuffer[inPtr++];
1108 if (b == SmileConstants.BYTE_MARKER_END_OF_STRING) {
1109 _inputPtr = inPtr;
1110 break main_loop;
1111 }
1112 outBuf[outPtr++] = (char) b;
1113 } while (--left > 0);
1114 _inputPtr = inPtr;
1115 }
1116 _textBuffer.setCurrentLength(outPtr);
1117 }
1118 */
1119
1120 private final JsonToken _nextLongUnicode(int substate) throws IOException, JsonParseException
1121 {
1122 // did not get it all; mark the state so we know where to return:
1123 _state = STATE_LONG_UNICODE;
1124 _tokenIncomplete = true;
1125 _substate = substate;
1126 return (_currToken = JsonToken.NOT_AVAILABLE);
1127 }
1128
1129
1130 /*
1131 private final void _decodeLongUnicode()
1132 throws IOException, JsonParseException
1133 {
1134 int outPtr = 0;
1135 char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
1136 final int[] codes = SmileConstants.sUtf8UnitLengths;
1137 int c;
1138 final byte[] inputBuffer = _inputBuffer;
1139
1140 main_loop:
1141 while (true) {
1142 // First the tight ASCII loop:
1143 ascii_loop:
1144 while (true) {
1145 int ptr = _inputPtr;
1146 if (ptr >= _inputEnd) {
1147 loadMoreGuaranteed();
1148 ptr = _inputPtr;
1149 }
1150 if (outPtr >= outBuf.length) {
1151 outBuf = _textBuffer.finishCurrentSegment();
1152 outPtr = 0;
1153 }
1154 int max = _inputEnd;
1155 {
1156 int max2 = ptr + (outBuf.length - outPtr);
1157 if (max2 < max) {
1158 max = max2;
1159 }
1160 }
1161 while (ptr < max) {
1162 c = (int) inputBuffer[ptr++] & 0xFF;
1163 if (codes[c] != 0) {
1164 _inputPtr = ptr;
1165 break ascii_loop;
1166 }
1167 outBuf[outPtr++] = (char) c;
1168 }
1169 _inputPtr = ptr;
1170 }
1171 // Ok: end marker, escape or multi-byte?
1172 if (c == SmileConstants.INT_MARKER_END_OF_STRING) {
1173 break main_loop;
1174 }
1175
1176 switch (codes[c]) {
1177 case 1: // 2-byte UTF
1178 c = _decodeUtf8_2(c);
1179 break;
1180 case 2: // 3-byte UTF
1181 if ((_inputEnd - _inputPtr) >= 2) {
1182 c = _decodeUtf8_3fast(c);
1183 } else {
1184 c = _decodeUtf8_3(c);
1185 }
1186 break;
1187 case 3: // 4-byte UTF
1188 c = _decodeUtf8_4(c);
1189 // Let's add first part right away:
1190 outBuf[outPtr++] = (char) (0xD800 | (c >> 10));
1191 if (outPtr >= outBuf.length) {
1192 outBuf = _textBuffer.finishCurrentSegment();
1193 outPtr = 0;
1194 }
1195 c = 0xDC00 | (c & 0x3FF);
1196 // And let the other char output down below
1197 break;
1198 default:
1199 // Is this good enough error message?
1200 _reportInvalidChar(c);
1201 }
1202 // Need more room?
1203 if (outPtr >= outBuf.length) {
1204 outBuf = _textBuffer.finishCurrentSegment();
1205 outPtr = 0;
1206 }
1207 // Ok, let's add char to output:
1208 outBuf[outPtr++] = (char) c;
1209 }
1210 _textBuffer.setCurrentLength(outPtr);
1211 }
1212 */
1213
1214 private final JsonToken _nextLongSharedString(int substate) throws IOException, JsonParseException
1215 {
1216 // did not get it all; mark the state so we know where to return:
1217 _tokenIncomplete = true;
1218 _state = STATE_LONG_SHARED;
1219 _substate = substate;
1220 return (_currToken = JsonToken.NOT_AVAILABLE);
1221 }
1222
1223 private final JsonToken _nextRawBinary(int substate) throws IOException, JsonParseException
1224 {
1225 // did not get it all; mark the state so we know where to return:
1226 _tokenIncomplete = true;
1227 _state = STATE_RAW_BINARY;
1228 _substate = substate;
1229 return (_currToken = JsonToken.NOT_AVAILABLE);
1230 }
1231
1232 /*
1233
1234 private final void _finishRawBinary()
1235 throws IOException, JsonParseException
1236 {
1237 int byteLen = _readUnsignedVInt();
1238 _binaryValue = new byte[byteLen];
1239 if (_inputPtr >= _inputEnd) {
1240 loadMoreGuaranteed();
1241 }
1242 int ptr = 0;
1243 while (true) {
1244 int toAdd = Math.min(byteLen, _inputEnd - _inputPtr);
1245 System.arraycopy(_inputBuffer, _inputPtr, _binaryValue, ptr, toAdd);
1246 _inputPtr += toAdd;
1247 ptr += toAdd;
1248 byteLen -= toAdd;
1249 if (byteLen <= 0) {
1250 return;
1251 }
1252 loadMoreGuaranteed();
1253 }
1254 }
1255 */
1256
1257 private final JsonToken _nextQuotedBinary(int substate) throws IOException, JsonParseException
1258 {
1259 // did not get it all; mark the state so we know where to return:
1260 _tokenIncomplete = true;
1261 _state = STATE_QUOTED_BINARY;
1262 _substate = substate;
1263 return (_currToken = JsonToken.NOT_AVAILABLE);
1264 }
1265
1266 /*
1267 private final byte[] _read7BitBinaryWithLength()
1268 throws IOException, JsonParseException
1269 {
1270 int byteLen = _readUnsignedVInt();
1271 byte[] result = new byte[byteLen];
1272 int ptr = 0;
1273 int lastOkPtr = byteLen - 7;
1274
1275 // first, read all 7-by-8 byte chunks
1276 while (ptr <= lastOkPtr) {
1277 if ((_inputEnd - _inputPtr) < 8) {
1278 _loadToHaveAtLeast(8);
1279 }
1280 int i1 = (_inputBuffer[_inputPtr++] << 25)
1281 + (_inputBuffer[_inputPtr++] << 18)
1282 + (_inputBuffer[_inputPtr++] << 11)
1283 + (_inputBuffer[_inputPtr++] << 4);
1284 int x = _inputBuffer[_inputPtr++];
1285 i1 += x >> 3;
1286 int i2 = ((x & 0x7) << 21)
1287 + (_inputBuffer[_inputPtr++] << 14)
1288 + (_inputBuffer[_inputPtr++] << 7)
1289 + _inputBuffer[_inputPtr++];
1290 // Ok: got our 7 bytes, just need to split, copy
1291 result[ptr++] = (byte)(i1 >> 24);
1292 result[ptr++] = (byte)(i1 >> 16);
1293 result[ptr++] = (byte)(i1 >> 8);
1294 result[ptr++] = (byte)i1;
1295 result[ptr++] = (byte)(i2 >> 16);
1296 result[ptr++] = (byte)(i2 >> 8);
1297 result[ptr++] = (byte)i2;
1298 }
1299 // and then leftovers: n+1 bytes to decode n bytes
1300 int toDecode = (result.length - ptr);
1301 if (toDecode > 0) {
1302 if ((_inputEnd - _inputPtr) < (toDecode+1)) {
1303 _loadToHaveAtLeast(toDecode+1);
1304 }
1305 int value = _inputBuffer[_inputPtr++];
1306 for (int i = 1; i < toDecode; ++i) {
1307 value = (value << 7) + _inputBuffer[_inputPtr++];
1308 result[ptr++] = (byte) (value >> (7 - i));
1309 }
1310 // last byte is different, has remaining 1 - 6 bits, right-aligned
1311 value <<= toDecode;
1312 result[ptr] = (byte) (value + _inputBuffer[_inputPtr++]);
1313 }
1314 return result;
1315 }
1316 */
1317
1318 /*
1319 /**********************************************************************
1320 /* Public API, traversal, nextXxxValue/nextFieldName
1321 /**********************************************************************
1322 */
1323
1324 /* Implementing these methods efficiently for non-blocking cases would
1325 * be complicated; so for now let's just use the default non-optimized
1326 * implementation
1327 */
1328
1329 // public boolean nextFieldName(SerializableString str) throws IOException, JsonParseException
1330 // public String nextTextValue() throws IOException, JsonParseException
1331 // public int nextIntValue(int defaultValue) throws IOException, JsonParseException
1332 // public long nextLongValue(long defaultValue) throws IOException, JsonParseException
1333 // public Boolean nextBooleanValue() throws IOException, JsonParseException
1334
1335 /*
1336 /**********************************************************************
1337 /* Public API, access to token information, text
1338 /**********************************************************************
1339 */
1340
1341 /**
1342 * Method for accessing textual representation of the current event;
1343 * if no current event (before first call to {@link #nextToken}, or
1344 * after encountering end-of-input), returns null.
1345 * Method can be called for any event.
1346 */
1347 @Override
1348 public String getText()
1349 throws IOException, JsonParseException
1350 {
1351 if (_currToken == JsonToken.VALUE_STRING) {
1352 return _textBuffer.contentsAsString();
1353 }
1354 if (_tokenIncomplete) {
1355 return null;
1356 }
1357 JsonToken t = _currToken;
1358 if (t == null) { // null only before/after document
1359 return null;
1360 }
1361 if (t == JsonToken.FIELD_NAME) {
1362 return _parsingContext.getCurrentName();
1363 }
1364 if (t.isNumeric()) {
1365 // TODO: optimize?
1366 return getNumberValue().toString();
1367 }
1368 return _currToken.asString();
1369 }
1370
1371 @Override
1372 public char[] getTextCharacters()
1373 throws IOException, JsonParseException
1374 {
1375 if (_currToken != null) { // null only before/after document
1376 switch (_currToken) {
1377 case VALUE_STRING:
1378 return _textBuffer.getTextBuffer();
1379 case FIELD_NAME:
1380 if (!_nameCopied) {
1381 String name = _parsingContext.getCurrentName();
1382 int nameLen = name.length();
1383 if (_nameCopyBuffer == null) {
1384 _nameCopyBuffer = _ioContext.allocNameCopyBuffer(nameLen);
1385 } else if (_nameCopyBuffer.length < nameLen) {
1386 _nameCopyBuffer = new char[nameLen];
1387 }
1388 name.getChars(0, nameLen, _nameCopyBuffer, 0);
1389 _nameCopied = true;
1390 }
1391 return _nameCopyBuffer;
1392
1393 // fall through
1394 case VALUE_NUMBER_INT:
1395 case VALUE_NUMBER_FLOAT:
1396 // TODO: optimize
1397 return getNumberValue().toString().toCharArray();
1398 default:
1399 if (_tokenIncomplete) {
1400 return null;
1401 }
1402 return _currToken.asCharArray();
1403 }
1404 }
1405 return null;
1406 }
1407
1408 @Override
1409 public int getTextLength()
1410 throws IOException, JsonParseException
1411 {
1412 if (_currToken != null) { // null only before/after document
1413 if (_tokenIncomplete) {
1414 return -1; // or throw exception?
1415 }
1416 switch (_currToken) {
1417 case VALUE_STRING:
1418 return _textBuffer.size();
1419 case FIELD_NAME:
1420 return _parsingContext.getCurrentName().length();
1421 // fall through
1422 case VALUE_NUMBER_INT:
1423 case VALUE_NUMBER_FLOAT:
1424 // TODO: optimize
1425 return getNumberValue().toString().length();
1426
1427 default:
1428 return _currToken.asCharArray().length;
1429 }
1430 }
1431 return 0;
1432 }
1433
1434 @Override
1435 public int getTextOffset() throws IOException, JsonParseException
1436 {
1437 return 0;
1438 }
1439
1440 /*
1441 /**********************************************************************
1442 /* Public API, access to token information, binary
1443 /**********************************************************************
1444 */
1445
1446 @Override
1447 public byte[] getBinaryValue(Base64Variant b64variant)
1448 throws IOException, JsonParseException
1449 {
1450 if (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT ) {
1451 // Todo, maybe: support base64 for text?
1452 _reportError("Current token ("+_currToken+") not VALUE_EMBEDDED_OBJECT, can not access as binary");
1453 }
1454 return _binaryValue;
1455 }
1456
1457 @Override
1458 public Object getEmbeddedObject()
1459 throws IOException, JsonParseException
1460 {
1461 if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT ) {
1462 return _binaryValue;
1463 }
1464 return null;
1465 }
1466
1467 // could possibly implement this... or maybe not.
1468 @Override
1469 public int readBinaryValue(Base64Variant b64variant, OutputStream out)
1470 throws IOException, JsonParseException {
1471 throw new UnsupportedOperationException();
1472 }
1473
1474 /*
1475 /**********************************************************************
1476 /* Internal methods, field name parsing
1477 /**********************************************************************
1478 */
1479
1480 /**
1481 * Method that handles initial token type recognition for token
1482 * that has to be either FIELD_NAME or END_OBJECT.
1483 */
1484 protected final JsonToken _handleFieldName() throws IOException, JsonParseException
1485 {
1486 if (_inputPtr >= _inputEnd) {
1487 loadMoreGuaranteed();
1488 }
1489 int ch = _inputBuffer[_inputPtr++];
1490 switch ((ch >> 6) & 3) {
1491 case 0: // misc, including end marker
1492 switch (ch) {
1493 case 0x20: // empty String as name, legal if unusual
1494 _parsingContext.setCurrentName("");
1495 return JsonToken.FIELD_NAME;
1496 case 0x30: // long shared
1497 case 0x31:
1498 case 0x32:
1499 case 0x33:
1500 {
1501 if (_inputPtr >= _inputEnd) {
1502 loadMoreGuaranteed();
1503 }
1504 int index = ((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF);
1505 if (index >= _seenNameCount) {
1506 _reportInvalidSharedName(index);
1507 }
1508 _parsingContext.setCurrentName(_seenNames[index]);
1509 }
1510 return JsonToken.FIELD_NAME;
1511 case 0x34: // long ASCII/Unicode name
1512 _handleLongFieldName();
1513 return JsonToken.FIELD_NAME;
1514 }
1515 break;
1516 case 1: // short shared, can fully process
1517 {
1518 int index = (ch & 0x3F);
1519 if (index >= _seenNameCount) {
1520 _reportInvalidSharedName(index);
1521 }
1522 _parsingContext.setCurrentName(_seenNames[index]);
1523 }
1524 return JsonToken.FIELD_NAME;
1525 case 2: // short ASCII
1526 {
1527 int len = 1 + (ch & 0x3f);
1528 String name = _findDecodedFromSymbols(len);
1529 if (name != null) {
1530 _inputPtr += len;
1531 } else {
1532 name = _decodeShortAsciiName(len);
1533 name = _addDecodedToSymbols(len, name);
1534 }
1535 if (_seenNames != null) {
1536 if (_seenNameCount >= _seenNames.length) {
1537 _seenNames = _expandSeenNames(_seenNames);
1538 }
1539 _seenNames[_seenNameCount++] = name;
1540 }
1541 _parsingContext.setCurrentName(name);
1542 }
1543 return JsonToken.FIELD_NAME;
1544 case 3: // short Unicode
1545 // all valid, except for 0xFF
1546 ch &= 0x3F;
1547 {
1548 if (ch > 0x37) {
1549 if (ch == 0x3B) {
1550 if (!_parsingContext.inObject()) {
1551 _reportMismatchedEndMarker('}', ']');
1552 }
1553 _parsingContext = _parsingContext.getParent();
1554 return JsonToken.END_OBJECT;
1555 }
1556 } else {
1557 final int len = ch + 2; // values from 2 to 57...
1558 String name = _findDecodedFromSymbols(len);
1559 if (name != null) {
1560 _inputPtr += len;
1561 } else {
1562 name = _decodeShortUnicodeName(len);
1563 name = _addDecodedToSymbols(len, name);
1564 }
1565 if (_seenNames != null) {
1566 if (_seenNameCount >= _seenNames.length) {
1567 _seenNames = _expandSeenNames(_seenNames);
1568 }
1569 _seenNames[_seenNameCount++] = name;
1570 }
1571 _parsingContext.setCurrentName(name);
1572 return JsonToken.FIELD_NAME;
1573 }
1574 }
1575 break;
1576 }
1577 // Other byte values are illegal
1578 _reportError("Invalid type marker byte 0x"+Integer.toHexString(_inputBuffer[_inputPtr-1])
1579 +" for expected field name (or END_OBJECT marker)");
1580 return null;
1581 }
1582
1583 /**
1584 * Method called to try to expand shared name area to fit one more potentially
1585 * shared String. If area is already at its biggest size, will just clear
1586 * the area (by setting next-offset to 0)
1587 */
1588 private final String[] _expandSeenNames(String[] oldShared)
1589 {
1590 int len = oldShared.length;
1591 String[] newShared;
1592 if (len == 0) {
1593 newShared = _smileBufferRecycler.allocSeenNamesBuffer();
1594 if (newShared == null) {
1595 newShared = new String[SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH];
1596 }
1597 } else if (len == SmileConstants.MAX_SHARED_NAMES) { // too many? Just flush...
1598 newShared = oldShared;
1599 _seenNameCount = 0; // could also clear, but let's not yet bother
1600 } else {
1601 int newSize = (len == SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH) ? 256 : SmileConstants.MAX_SHARED_NAMES;
1602 newShared = new String[newSize];
1603 System.arraycopy(oldShared, 0, newShared, 0, oldShared.length);
1604 }
1605 return newShared;
1606 }
1607
1608 private int _quad1, _quad2;
1609
1610
1611 private final String _addDecodedToSymbols(int len, String name)
1612 {
1613 if (len < 5) {
1614 return _symbols.addName(name, _quad1, 0);
1615 }
1616 if (len < 9) {
1617 return _symbols.addName(name, _quad1, _quad2);
1618 }
1619 int qlen = (len + 3) >> 2;
1620 return _symbols.addName(name, _quadBuffer, qlen);
1621 }
1622
1623 private final String _decodeShortAsciiName(int len)
1624 throws IOException, JsonParseException
1625 {
1626 // note: caller ensures we have enough bytes available
1627 char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
1628 int outPtr = 0;
1629 final byte[] inBuf = _inputBuffer;
1630 int inPtr = _inputPtr;
1631
1632 // loop unrolling seems to help here:
1633 for (int inEnd = inPtr + len - 3; inPtr < inEnd; ) {
1634 outBuf[outPtr++] = (char) inBuf[inPtr++];
1635 outBuf[outPtr++] = (char) inBuf[inPtr++];
1636 outBuf[outPtr++] = (char) inBuf[inPtr++];
1637 outBuf[outPtr++] = (char) inBuf[inPtr++];
1638 }
1639 int left = (len & 3);
1640 if (left > 0) {
1641 outBuf[outPtr++] = (char) inBuf[inPtr++];
1642 if (left > 1) {
1643 outBuf[outPtr++] = (char) inBuf[inPtr++];
1644 if (left > 2) {
1645 outBuf[outPtr++] = (char) inBuf[inPtr++];
1646 }
1647 }
1648 }
1649 _inputPtr = inPtr;
1650 _textBuffer.setCurrentLength(len);
1651 return _textBuffer.contentsAsString();
1652 }
1653
1654 /**
1655 * Helper method used to decode short Unicode string, length for which actual
1656 * length (in bytes) is known
1657 *
1658 * @param len Length between 1 and 64
1659 */
1660 private final String _decodeShortUnicodeName(int len) throws IOException
1661 {
1662 // note: caller ensures we have enough bytes available
1663 int outPtr = 0;
1664 char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
1665 int inPtr = _inputPtr;
1666 _inputPtr += len;
1667 final int[] codes = SmileConstants.sUtf8UnitLengths;
1668 final byte[] inBuf = _inputBuffer;
1669 for (int end = inPtr + len; inPtr < end; ) {
1670 int i = inBuf[inPtr++] & 0xFF;
1671 int code = codes[i];
1672 if (code != 0) {
1673 // trickiest one, need surrogate handling
1674 switch (code) {
1675 case 1:
1676 i = ((i & 0x1F) << 6) | (inBuf[inPtr++] & 0x3F);
1677 break;
1678 case 2:
1679 i = ((i & 0x0F) << 12)
1680 | ((inBuf[inPtr++] & 0x3F) << 6)
1681 | (inBuf[inPtr++] & 0x3F);
1682 break;
1683 case 3:
1684 i = ((i & 0x07) << 18)
1685 | ((inBuf[inPtr++] & 0x3F) << 12)
1686 | ((inBuf[inPtr++] & 0x3F) << 6)
1687 | (inBuf[inPtr++] & 0x3F);
1688 // note: this is the codepoint value; need to split, too
1689 i -= 0x10000;
1690 outBuf[outPtr++] = (char) (0xD800 | (i >> 10));
1691 i = 0xDC00 | (i & 0x3FF);
1692 break;
1693 default: // invalid
1694 _reportError("Invalid byte "+Integer.toHexString(i)+" in short Unicode text block");
1695 }
1696 }
1697 outBuf[outPtr++] = (char) i;
1698 }
1699 _textBuffer.setCurrentLength(outPtr);
1700 return _textBuffer.contentsAsString();
1701 }
1702
1703 // note: slightly edited copy of UTF8StreamParser.addName()
1704 private final String _decodeLongUnicodeName(int[] quads, int byteLen, int quadLen) throws IOException
1705 {
1706 int lastQuadBytes = byteLen & 3;
1707 // Ok: must decode UTF-8 chars. No other validation SHOULD be needed (except bounds checks?)
1708 /* Note: last quad is not correctly aligned (leading zero bytes instead
1709 * need to shift a bit, instead of trailing). Only need to shift it
1710 * for UTF-8 decoding; need revert for storage (since key will not
1711 * be aligned, to optimize lookup speed)
1712 */
1713 int lastQuad;
1714
1715 if (lastQuadBytes < 4) {
1716 lastQuad = quads[quadLen-1];
1717 // 8/16/24 bit left shift
1718 quads[quadLen-1] = (lastQuad << ((4 - lastQuadBytes) << 3));
1719 } else {
1720 lastQuad = 0;
1721 }
1722
1723 char[] cbuf = _textBuffer.emptyAndGetCurrentSegment();
1724 int cix = 0;
1725
1726 for (int ix = 0; ix < byteLen; ) {
1727 int ch = quads[ix >> 2]; // current quad, need to shift+mask
1728 int byteIx = (ix & 3);
1729 ch = (ch >> ((3 - byteIx) << 3)) & 0xFF;
1730 ++ix;
1731
1732 if (ch > 127) { // multi-byte
1733 int needed;
1734 if ((ch & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF)
1735 ch &= 0x1F;
1736 needed = 1;
1737 } else if ((ch & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF)
1738 ch &= 0x0F;
1739 needed = 2;
1740 } else if ((ch & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all...
1741 ch &= 0x07;
1742 needed = 3;
1743 } else { // 5- and 6-byte chars not valid chars
1744 _reportInvalidInitial(ch);
1745 needed = ch = 1; // never really gets this far
1746 }
1747 if ((ix + needed) > byteLen) {
1748 _reportInvalidEOF(" in long field name");
1749 }
1750
1751 // Ok, always need at least one more:
1752 int ch2 = quads[ix >> 2]; // current quad, need to shift+mask
1753 byteIx = (ix & 3);
1754 ch2 = (ch2 >> ((3 - byteIx) << 3));
1755 ++ix;
1756
1757 if ((ch2 & 0xC0) != 0x080) {
1758 _reportInvalidOther(ch2);
1759 }
1760 ch = (ch << 6) | (ch2 & 0x3F);
1761 if (needed > 1) {
1762 ch2 = quads[ix >> 2];
1763 byteIx = (ix & 3);
1764 ch2 = (ch2 >> ((3 - byteIx) << 3));
1765 ++ix;
1766
1767 if ((ch2 & 0xC0) != 0x080) {
1768 _reportInvalidOther(ch2);
1769 }
1770 ch = (ch << 6) | (ch2 & 0x3F);
1771 if (needed > 2) { // 4 bytes? (need surrogates on output)
1772 ch2 = quads[ix >> 2];
1773 byteIx = (ix & 3);
1774 ch2 = (ch2 >> ((3 - byteIx) << 3));
1775 ++ix;
1776 if ((ch2 & 0xC0) != 0x080) {
1777 _reportInvalidOther(ch2 & 0xFF);
1778 }
1779 ch = (ch << 6) | (ch2 & 0x3F);
1780 }
1781 }
1782 if (needed > 2) { // surrogate pair? once again, let's output one here, one later on
1783 ch -= 0x10000; // to normalize it starting with 0x0
1784 if (cix >= cbuf.length) {
1785 cbuf = _textBuffer.expandCurrentSegment();
1786 }
1787 cbuf[cix++] = (char) (0xD800 + (ch >> 10));
1788 ch = 0xDC00 | (ch & 0x03FF);
1789 }
1790 }
1791 if (cix >= cbuf.length) {
1792 cbuf = _textBuffer.expandCurrentSegment();
1793 }
1794 cbuf[cix++] = (char) ch;
1795 }
1796
1797 // Ok. Now we have the character array, and can construct the String
1798 String baseName = new String(cbuf, 0, cix);
1799 // And finally, un-align if necessary
1800 if (lastQuadBytes < 4) {
1801 quads[quadLen-1] = lastQuad;
1802 }
1803 return _symbols.addName(baseName, quads, quadLen);
1804 }
1805
1806 private final void _handleLongFieldName() throws IOException, JsonParseException
1807 {
1808 // First: gather quads we need, looking for end marker
1809 final byte[] inBuf = _inputBuffer;
1810 int quads = 0;
1811 int bytes = 0;
1812 int q = 0;
1813
1814 while (true) {
1815 if (_inputPtr >= _inputEnd) {
1816 loadMoreGuaranteed();
1817 }
1818 byte b = inBuf[_inputPtr++];
1819 if (BYTE_MARKER_END_OF_STRING == b) {
1820 bytes = 0;
1821 break;
1822 }
1823 q = ((int) b) & 0xFF;
1824 if (_inputPtr >= _inputEnd) {
1825 loadMoreGuaranteed();
1826 }
1827 b = inBuf[_inputPtr++];
1828 if (BYTE_MARKER_END_OF_STRING == b) {
1829 bytes = 1;
1830 break;
1831 }
1832 q = (q << 8) | (b & 0xFF);
1833 if (_inputPtr >= _inputEnd) {
1834 loadMoreGuaranteed();
1835 }
1836 b = inBuf[_inputPtr++];
1837 if (BYTE_MARKER_END_OF_STRING == b) {
1838 bytes = 2;
1839 break;
1840 }
1841 q = (q << 8) | (b & 0xFF);
1842 if (_inputPtr >= _inputEnd) {
1843 loadMoreGuaranteed();
1844 }
1845 b = inBuf[_inputPtr++];
1846 if (BYTE_MARKER_END_OF_STRING == b) {
1847 bytes = 3;
1848 break;
1849 }
1850 q = (q << 8) | (b & 0xFF);
1851 if (quads >= _quadBuffer.length) {
1852 _quadBuffer = _growArrayTo(_quadBuffer, _quadBuffer.length + 256); // grow by 1k
1853 }
1854 _quadBuffer[quads++] = q;
1855 }
1856 // and if we have more bytes, append those too
1857 int byteLen = (quads << 2);
1858 if (bytes > 0) {
1859 if (quads >= _quadBuffer.length) {
1860 _quadBuffer = _growArrayTo(_quadBuffer, _quadBuffer.length + 256);
1861 }
1862 _quadBuffer[quads++] = q;
1863 byteLen += bytes;
1864 }
1865
1866 // Know this name already?
1867 String name = _symbols.findName(_quadBuffer, quads);
1868 if (name == null) {
1869 name = _decodeLongUnicodeName(_quadBuffer, byteLen, quads);
1870 }
1871 if (_seenNames != null) {
1872 if (_seenNameCount >= _seenNames.length) {
1873 _seenNames = _expandSeenNames(_seenNames);
1874 }
1875 _seenNames[_seenNameCount++] = name;
1876 }
1877 _parsingContext.setCurrentName(name);
1878 }
1879
1880 /**
1881 * Helper method for trying to find specified encoded UTF-8 byte sequence
1882 * from symbol table; if successful avoids actual decoding to String
1883 */
1884 private final String _findDecodedFromSymbols(int len) throws IOException
1885 {
1886 if ((_inputEnd - _inputPtr) < len) {
1887 _loadToHaveAtLeast(len);
1888 }
1889 // First: maybe we already have this name decoded?
1890 if (len < 5) {
1891 int inPtr = _inputPtr;
1892 final byte[] inBuf = _inputBuffer;
1893 int q = inBuf[inPtr] & 0xFF;
1894 if (--len > 0) {
1895 q = (q << 8) + (inBuf[++inPtr] & 0xFF);
1896 if (--len > 0) {
1897 q = (q << 8) + (inBuf[++inPtr] & 0xFF);
1898 if (--len > 0) {
1899 q = (q << 8) + (inBuf[++inPtr] & 0xFF);
1900 }
1901 }
1902 }
1903 _quad1 = q;
1904 return _symbols.findName(q);
1905 }
1906 if (len < 9) {
1907 int inPtr = _inputPtr;
1908 final byte[] inBuf = _inputBuffer;
1909 // First quadbyte is easy
1910 int q1 = (inBuf[inPtr] & 0xFF) << 8;
1911 q1 += (inBuf[++inPtr] & 0xFF);
1912 q1 <<= 8;
1913 q1 += (inBuf[++inPtr] & 0xFF);
1914 q1 <<= 8;
1915 q1 += (inBuf[++inPtr] & 0xFF);
1916 int q2 = (inBuf[++inPtr] & 0xFF);
1917 len -= 5;
1918 if (len > 0) {
1919 q2 = (q2 << 8) + (inBuf[++inPtr] & 0xFF);
1920 if (--len > 0) {
1921 q2 = (q2 << 8) + (inBuf[++inPtr] & 0xFF);
1922 if (--len > 0) {
1923 q2 = (q2 << 8) + (inBuf[++inPtr] & 0xFF);
1924 }
1925 }
1926 }
1927 _quad1 = q1;
1928 _quad2 = q2;
1929 return _symbols.findName(q1, q2);
1930 }
1931 return _findDecodedMedium(len);
1932 }
1933
1934 /**
1935 * Method for locating names longer than 8 bytes (in UTF-8)
1936 */
1937 private final String _findDecodedMedium(int len)
1938 throws IOException, JsonParseException
1939 {
1940 // first, need enough buffer to store bytes as ints:
1941 {
1942 int bufLen = (len + 3) >> 2;
1943 if (bufLen > _quadBuffer.length) {
1944 _quadBuffer = _growArrayTo(_quadBuffer, bufLen);
1945 }
1946 }
1947 // then decode, full quads first
1948 int offset = 0;
1949 int inPtr = _inputPtr;
1950 final byte[] inBuf = _inputBuffer;
1951 do {
1952 int q = (inBuf[inPtr++] & 0xFF) << 8;
1953 q |= inBuf[inPtr++] & 0xFF;
1954 q <<= 8;
1955 q |= inBuf[inPtr++] & 0xFF;
1956 q <<= 8;
1957 q |= inBuf[inPtr++] & 0xFF;
1958 _quadBuffer[offset++] = q;
1959 } while ((len -= 4) > 3);
1960 // and then leftovers
1961 if (len > 0) {
1962 int q = inBuf[inPtr] & 0xFF;
1963 if (--len > 0) {
1964 q = (q << 8) + (inBuf[++inPtr] & 0xFF);
1965 if (--len > 0) {
1966 q = (q << 8) + (inBuf[++inPtr] & 0xFF);
1967 }
1968 }
1969 _quadBuffer[offset++] = q;
1970 }
1971 return _symbols.findName(_quadBuffer, offset);
1972 }
1973
1974 private static int[] _growArrayTo(int[] arr, int minSize) {
1975 final int size = minSize+4;
1976 if (arr == null) {
1977 return new int[size];
1978 }
1979 return Arrays.copyOf(arr, size);
1980 }
1981
1982 /*
1983 /**********************************************************************
1984 /* Internal methods, secondary parsing
1985 /**********************************************************************
1986 */
1987
1988 @Override
1989 protected void _parseNumericValue(int expType) throws IOException
1990 {
1991 if (_tokenIncomplete) {
1992 _reportError("No current token available, can not call accessors");
1993 }
1994 }
1995
1996 /**
1997 * Method called to finish parsing of a token, given partial decoded
1998 * state.
1999 */
2000 protected final JsonToken _finishToken()
2001 throws IOException, JsonParseException
2002 {
2003 if (_inputPtr >= _inputEnd) {
2004 return JsonToken.NOT_AVAILABLE;
2005 }
2006 byte b = _inputBuffer[_inputPtr++];
2007
2008 // first need to handle possible header, since that is usually not
2009 // exposed as an event (expect when it implies document boundary)
2010 if (_state == STATE_INITIAL) { // just need to see if we see something like header:
2011 if (b == SmileConstants.HEADER_BYTE_1) {
2012 if (!_handleHeader(0)) {
2013 return JsonToken.NOT_AVAILABLE;
2014 }
2015 // if handled, get next byte to code (if available)
2016 if (_inputPtr >= _inputEnd) {
2017 return JsonToken.NOT_AVAILABLE;
2018 }
2019 b = _inputBuffer[_inputPtr++];
2020 } else {
2021 // nope, not header marker.
2022 // header mandatory? not good...
2023 if (_cfgRequireHeader) {
2024 String msg;
2025 if (b == '{' || b == '[') {
2026 msg = "Input does not start with Smile format header (first byte = 0x"
2027 +Integer.toHexString(b & 0xFF)+") -- rather, it starts with '"+((char) b)
2028 +"' (plain JSON input?) -- can not parse";
2029 } else {
2030 msg = "Input does not start with Smile format header (first byte = 0x"
2031 +Integer.toHexString(b & 0xFF)+") and parser has REQUIRE_HEADER enabled: can not parse";
2032 }
2033 throw new JsonParseException(this, msg);
2034 }
2035 }
2036 // otherwise, fall through, with byte (_handleHeader has set _state)
2037 } else if (_state == STATE_HEADER) { // in-stream header
2038 if (!_handleHeader(_substate)) {
2039 return JsonToken.NOT_AVAILABLE;
2040 }
2041 // is it enough to leave '_tokenIncomplete' false here?
2042 if (_inputPtr >= _inputEnd) {
2043 return JsonToken.NOT_AVAILABLE;
2044 }
2045 b = _inputBuffer[_inputPtr++];
2046 // fall through
2047 }
2048
2049 switch (_state) {
2050 case STATE_NUMBER_INT:
2051 return _nextInt(_substate, _pendingInt);
2052 case STATE_NUMBER_LONG:
2053 return _nextLong(_substate, _pendingLong);
2054 case STATE_NUMBER_BIGINT:
2055 return _nextBigInt(_substate);
2056 case STATE_NUMBER_FLOAT:
2057 return _nextFloat(_substate, _pendingInt) ;
2058 case STATE_NUMBER_DOUBLE:
2059 return _nextDouble(_substate, _pendingLong);
2060 case STATE_NUMBER_BIGDEC:
2061 return _nextBigDecimal(_substate);
2062 }
2063 _throwInvalidState("Illegal state when trying to complete token: ");
2064 return null;
2065 }
2066
2067 /*
2068 /**********************************************************************
2069 /* Internal methods, UTF8 decoding
2070 /**********************************************************************
2071 */
2072
2073 /*
2074 private final int _decodeUtf8_2(int c)
2075 throws IOException, JsonParseException
2076 {
2077 if (_inputPtr >= _inputEnd) {
2078 loadMoreGuaranteed();
2079 }
2080 int d = (int) _inputBuffer[_inputPtr++];
2081 if ((d & 0xC0) != 0x080) {
2082 _reportInvalidOther(d & 0xFF, _inputPtr);
2083 }
2084 return ((c & 0x1F) << 6) | (d & 0x3F);
2085 }
2086
2087 private final int _decodeUtf8_3(int c1)
2088 throws IOException, JsonParseException
2089 {
2090 if (_inputPtr >= _inputEnd) {
2091 loadMoreGuaranteed();
2092 }
2093 c1 &= 0x0F;
2094 int d = (int) _inputBuffer[_inputPtr++];
2095 if ((d & 0xC0) != 0x080) {
2096 _reportInvalidOther(d & 0xFF, _inputPtr);
2097 }
2098 int c = (c1 << 6) | (d & 0x3F);
2099 if (_inputPtr >= _inputEnd) {
2100 loadMoreGuaranteed();
2101 }
2102 d = (int) _inputBuffer[_inputPtr++];
2103 if ((d & 0xC0) != 0x080) {
2104 _reportInvalidOther(d & 0xFF, _inputPtr);
2105 }
2106 c = (c << 6) | (d & 0x3F);
2107 return c;
2108 }
2109
2110 private final int _decodeUtf8_3fast(int c1)
2111 throws IOException, JsonParseException
2112 {
2113 c1 &= 0x0F;
2114 int d = (int) _inputBuffer[_inputPtr++];
2115 if ((d & 0xC0) != 0x080) {
2116 _reportInvalidOther(d & 0xFF, _inputPtr);
2117 }
2118 int c = (c1 << 6) | (d & 0x3F);
2119 d = (int) _inputBuffer[_inputPtr++];
2120 if ((d & 0xC0) != 0x080) {
2121 _reportInvalidOther(d & 0xFF, _inputPtr);
2122 }
2123 c = (c << 6) | (d & 0x3F);
2124 return c;
2125 }
2126
2127 // @return Character value <b>minus 0x10000</c>; this so that caller
2128 // can readily expand it to actual surrogates
2129 private final int _decodeUtf8_4(int c)
2130 throws IOException, JsonParseException
2131 {
2132 if (_inputPtr >= _inputEnd) {
2133 loadMoreGuaranteed();
2134 }
2135 int d = (int) _inputBuffer[_inputPtr++];
2136 if ((d & 0xC0) != 0x080) {
2137 _reportInvalidOther(d & 0xFF, _inputPtr);
2138 }
2139 c = ((c & 0x07) << 6) | (d & 0x3F);
2140
2141 if (_inputPtr >= _inputEnd) {
2142 loadMoreGuaranteed();
2143 }
2144 d = (int) _inputBuffer[_inputPtr++];
2145 if ((d & 0xC0) != 0x080) {
2146 _reportInvalidOther(d & 0xFF, _inputPtr);
2147 }
2148 c = (c << 6) | (d & 0x3F);
2149 if (_inputPtr >= _inputEnd) {
2150 loadMoreGuaranteed();
2151 }
2152 d = (int) _inputBuffer[_inputPtr++];
2153 if ((d & 0xC0) != 0x080) {
2154 _reportInvalidOther(d & 0xFF, _inputPtr);
2155 }
2156
2157 // note: won't change it to negative here, since caller
2158 // already knows it'll need a surrogate
2159 return ((c << 6) | (d & 0x3F)) - 0x10000;
2160 }
2161 */
2162
2163 /*
2164 /**********************************************************************
2165 /* Internal methods, error reporting
2166 /**********************************************************************
2167 */
2168
2169 protected void _reportInvalidSharedName(int index) throws IOException
2170 {
2171 if (_seenNames == null) {
2172 _reportError("Encountered shared name reference, even though document header explicitly declared no shared name references are included");
2173 }
2174 _reportError("Invalid shared name reference "+index+"; only got "+_seenNameCount+" names in buffer (invalid content)");
2175 }
2176
2177 protected void _reportInvalidSharedStringValue(int index) throws IOException
2178 {
2179 if (_seenStringValues == null) {
2180 _reportError("Encountered shared text value reference, even though document header did not declared shared text value references may be included");
2181 }
2182 _reportError("Invalid shared text value reference "+index+"; only got "+_seenStringValueCount+" names in buffer (invalid content)");
2183 }
2184
2185 protected void _reportInvalidChar(int c) throws JsonParseException
2186 {
2187 // Either invalid WS or illegal UTF-8 start char
2188 if (c < ' ') {
2189 _throwInvalidSpace(c);
2190 }
2191 _reportInvalidInitial(c);
2192 }
2193
2194 protected void _reportInvalidInitial(int mask)
2195 throws JsonParseException
2196 {
2197 _reportError("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask));
2198 }
2199
2200 protected void _reportInvalidOther(int mask)
2201 throws JsonParseException
2202 {
2203 _reportError("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask));
2204 }
2205
2206 protected void _reportInvalidOther(int mask, int ptr)
2207 throws JsonParseException
2208 {
2209 _inputPtr = ptr;
2210 _reportInvalidOther(mask);
2211 }
2212
2213 protected void _throwInvalidState(String desc)
2214 {
2215 throw new IllegalStateException(desc+": state="+_state);
2216 }
2217 }