/
MessageUnpacker.java
1797 lines (1699 loc) · 61.7 KB
/
MessageUnpacker.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
//
// MessagePack for Java
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.msgpack.core;
import org.msgpack.core.MessagePack.Code;
import org.msgpack.core.buffer.MessageBuffer;
import org.msgpack.core.buffer.MessageBufferInput;
import org.msgpack.value.ImmutableValue;
import org.msgpack.value.Value;
import org.msgpack.value.ValueFactory;
import org.msgpack.value.Variable;
import java.io.Closeable;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.time.Instant;
import static org.msgpack.core.MessagePack.Code.EXT_TIMESTAMP;
import static org.msgpack.core.Preconditions.checkNotNull;
/**
* MessagePack deserializer that converts binary into objects.
* You can use factory methods of {@link MessagePack} class or {@link MessagePack.UnpackerConfig} class to create
* an instance.
* To read values as statically-typed Java objects, there are two typical use cases.
* <p>
* One use case is to read objects as {@link Value} using {@link #unpackValue} method. A {@link Value} object
* contains type of the deserialized value as well as the value itself so that you can inspect type of the
* deserialized values later. You can repeat {@link #unpackValue} until {@link #hasNext()} method returns false so
* that you can deserialize sequence of MessagePack values.
* <p>
* The other use case is to use {@link #getNextFormat()} and {@link MessageFormat#getValueType()} methods followed
* by unpackXxx methods corresponding to returned type. Following code snipet is a typical application code:
* <pre><code>
* MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(...);
* while(unpacker.hasNext()) {
* MessageFormat format = unpacker.getNextFormat();
* ValueType type = format.getValueType();
* int length;
* ExtensionTypeHeader extension;
* switch(type) {
* case NIL:
* unpacker.unpackNil();
* break;
* case BOOLEAN:
* unpacker.unpackBoolean();
* break;
* case INTEGER:
* switch (format) {
* case UINT64:
* unpacker.unpackBigInteger();
* break;
* case INT64:
* case UINT32:
* unpacker.unpackLong();
* break;
* default:
* unpacker.unpackInt();
* break;
* }
* break;
* case FLOAT:
* unpacker.unpackDouble();
* break;
* case STRING:
* unpacker.unpackString();
* break;
* case BINARY:
* length = unpacker.unpackBinaryHeader();
* unpacker.readPayload(new byte[length]);
* break;
* case ARRAY:
* length = unpacker.unpackArrayHeader();
* for (int i = 0; i < length; i++) {
* readRecursively(unpacker);
* }
* break;
* case MAP:
* length = unpacker.unpackMapHeader();
* for (int i = 0; i < length; i++) {
* readRecursively(unpacker); // key
* readRecursively(unpacker); // value
* }
* break;
* case EXTENSION:
* extension = unpacker.unpackExtensionTypeHeader();
* unpacker.readPayload(new byte[extension.getLength()]);
* break;
* }
* }
* }
*
* <p>
* Following methods correspond to the MessagePack types:
*
* <table>
* <tr><th>MessagePack type</th><th>Unpacker method</th><th>Java type</th></tr>
* <tr><td>Nil</td><td>{@link #unpackNil()}</td><td>null</td></tr>
* <tr><td>Boolean</td><td>{@link #unpackBoolean()}</td><td>boolean</td></tr>
* <tr><td>Integer</td><td>{@link #unpackByte()}</td><td>byte</td></tr>
* <tr><td>Integer</td><td>{@link #unpackShort()}</td><td>short</td></tr>
* <tr><td>Integer</td><td>{@link #unpackInt()}</td><td>int</td></tr>
* <tr><td>Integer</td><td>{@link #unpackLong()}</td><td>long</td></tr>
* <tr><td>Integer</td><td>{@link #unpackBigInteger()}</td><td>BigInteger</td></tr>
* <tr><td>Float</td><td>{@link #unpackFloat()}</td><td>float</td></tr>
* <tr><td>Float</td><td>{@link #unpackDouble()}</td><td>double</td></tr>
* <tr><td>Binary</td><td>{@link #unpackBinaryHeader()}</td><td>byte array</td></tr>
* <tr><td>String</td><td>{@link #unpackRawStringHeader()}</td><td>String</td></tr>
* <tr><td>String</td><td>{@link #unpackString()}</td><td>String</td></tr>
* <tr><td>Array</td><td>{@link #unpackArrayHeader()}</td><td>Array</td></tr>
* <tr><td>Map</td><td>{@link #unpackMapHeader()}</td><td>Map</td></tr>
* <tr><td>Extension</td><td>{@link #unpackExtensionTypeHeader()}</td><td>{@link ExtensionTypeHeader}</td></tr>
* </table>
*
* <p>
* To read a byte array, first call {@link #unpackBinaryHeader} method to get length of the byte array. Then,
* call {@link #readPayload(int)} or {@link #readPayloadAsReference(int)} method to read the the contents.
*
* <p>
* To read an Array type, first call {@link #unpackArrayHeader()} method to get number of elements. Then,
* call unpacker methods for each element.
*
* <p>
* To read a Map, first call {@link #unpackMapHeader()} method to get number of pairs of the map. Then,
* for each pair, call unpacker methods for key first, and then value. will call unpacker methods twice
* as many time as the returned count.
*
*/
public class MessageUnpacker
implements Closeable
{
private static final MessageBuffer EMPTY_BUFFER = MessageBuffer.wrap(new byte[0]);
private final boolean allowReadingStringAsBinary;
private final boolean allowReadingBinaryAsString;
private final CodingErrorAction actionOnMalformedString;
private final CodingErrorAction actionOnUnmappableString;
private final int stringSizeLimit;
private final int stringDecoderBufferSize;
private MessageBufferInput in;
/**
* Points to the current buffer to read
*/
private MessageBuffer buffer = EMPTY_BUFFER;
/**
* Cursor position in the current buffer
*/
private int position;
/**
* Total read byte size
*/
private long totalReadBytes;
/**
* An extra buffer for reading a small number value across the input buffer boundary.
* At most 8-byte buffer (for readLong used by uint 64 and UTF-8 character decoding) is required.
*/
private final MessageBuffer numberBuffer = MessageBuffer.allocate(8);
/**
* After calling prepareNumberBuffer(), the caller should use this variable to read from the returned MessageBuffer.
*/
private int nextReadPosition;
/**
* For decoding String in unpackString.
*/
private StringBuilder decodeStringBuffer;
/**
* For decoding String in unpackString.
*/
private CharsetDecoder decoder;
/**
* Buffer for decoding strings
*/
private CharBuffer decodeBuffer;
/**
* Create an MessageUnpacker that reads data from the given MessageBufferInput.
* This method is available for subclasses to override. Use MessagePack.UnpackerConfig.newUnpacker method to instantiate this implementation.
*
* @param in
*/
protected MessageUnpacker(MessageBufferInput in, MessagePack.UnpackerConfig config)
{
this.in = checkNotNull(in, "MessageBufferInput is null");
this.allowReadingStringAsBinary = config.getAllowReadingStringAsBinary();
this.allowReadingBinaryAsString = config.getAllowReadingBinaryAsString();
this.actionOnMalformedString = config.getActionOnMalformedString();
this.actionOnUnmappableString = config.getActionOnUnmappableString();
this.stringSizeLimit = config.getStringSizeLimit();
this.stringDecoderBufferSize = config.getStringDecoderBufferSize();
}
/**
* Replaces underlying input.
* <p>
* This method clears internal buffer, swaps the underlying input with the new given input, then returns
* the old input.
*
* <p>
* This method doesn't close the old input.
*
* @param in new input
* @return the old input
* @throws IOException never happens unless a subclass overrides this method
* @throws NullPointerException the given input is null
*/
public MessageBufferInput reset(MessageBufferInput in)
throws IOException
{
MessageBufferInput newIn = checkNotNull(in, "MessageBufferInput is null");
// Reset the internal states
MessageBufferInput old = this.in;
this.in = newIn;
this.buffer = EMPTY_BUFFER;
this.position = 0;
this.totalReadBytes = 0;
// No need to initialize the already allocated string decoder here since we can reuse it.
return old;
}
/**
* Returns total number of read bytes.
* <p>
* This method returns total of amount of data consumed from the underlying input minus size of data
* remained still unused in the current internal buffer.
*
* <p>
* Calling {@link #reset(MessageBufferInput)} resets this number to 0.
*/
public long getTotalReadBytes()
{
return totalReadBytes + position;
}
/**
* Get the next buffer without changing the position
*
* @return
* @throws IOException
*/
private MessageBuffer getNextBuffer()
throws IOException
{
MessageBuffer next = in.next();
if (next == null) {
throw new MessageInsufficientBufferException();
}
assert (buffer != null);
totalReadBytes += buffer.size();
return next;
}
private void nextBuffer()
throws IOException
{
buffer = getNextBuffer();
position = 0;
}
/**
* Returns a short size buffer (upto 8 bytes) to read a number value
*
* @param readLength
* @return
* @throws IOException
* @throws MessageInsufficientBufferException If no more buffer can be acquired from the input source for reading the specified data length
*/
private MessageBuffer prepareNumberBuffer(int readLength)
throws IOException
{
int remaining = buffer.size() - position;
if (remaining >= readLength) {
// When the data is contained inside the default buffer
nextReadPosition = position;
position += readLength; // here assumes following buffer.getXxx never throws exception
return buffer; // Return the default buffer
}
else {
// When the default buffer doesn't contain the whole length,
// fill the temporary buffer from the current data fragment and
// next fragment(s).
int off = 0;
if (remaining > 0) {
numberBuffer.putMessageBuffer(0, buffer, position, remaining);
readLength -= remaining;
off += remaining;
}
while (true) {
nextBuffer();
int nextSize = buffer.size();
if (nextSize >= readLength) {
numberBuffer.putMessageBuffer(off, buffer, 0, readLength);
position = readLength;
break;
}
else {
numberBuffer.putMessageBuffer(off, buffer, 0, nextSize);
readLength -= nextSize;
off += nextSize;
}
}
nextReadPosition = 0;
return numberBuffer;
}
}
private static int utf8MultibyteCharacterSize(byte firstByte)
{
return Integer.numberOfLeadingZeros(~(firstByte & 0xff) << 24);
}
/**
* Returns true if this unpacker has more elements.
* When this returns true, subsequent call to {@link #getNextFormat()} returns an
* MessageFormat instance. If false, next {@link #getNextFormat()} call will throw an MessageInsufficientBufferException.
*
* @return true if this unpacker has more elements to read
*/
public boolean hasNext()
throws IOException
{
return ensureBuffer();
}
private boolean ensureBuffer()
throws IOException
{
while (buffer.size() <= position) {
MessageBuffer next = in.next();
if (next == null) {
return false;
}
totalReadBytes += buffer.size();
buffer = next;
position = 0;
}
return true;
}
/**
* Returns format of the next value.
*
* <p>
* Note that this method doesn't consume data from the internal buffer unlike the other unpack methods.
* Calling this method twice will return the same value.
*
* <p>
* To not throw {@link MessageInsufficientBufferException}, this method should be called only when
* {@link #hasNext()} returns true.
*
* @return the next MessageFormat
* @throws IOException when underlying input throws IOException
* @throws MessageInsufficientBufferException when the end of file reached, i.e. {@link #hasNext()} == false.
*/
public MessageFormat getNextFormat()
throws IOException
{
// makes sure that buffer has at least 1 byte
if (!ensureBuffer()) {
throw new MessageInsufficientBufferException();
}
byte b = buffer.getByte(position);
return MessageFormat.valueOf(b);
}
/**
* Read a byte value at the cursor and proceed the cursor.
*
* @return
* @throws IOException
*/
private byte readByte()
throws IOException
{
if (buffer.size() > position) {
byte b = buffer.getByte(position);
position++;
return b;
}
else {
nextBuffer();
if (buffer.size() > 0) {
byte b = buffer.getByte(0);
position = 1;
return b;
}
return readByte();
}
}
private short readShort()
throws IOException
{
MessageBuffer numberBuffer = prepareNumberBuffer(2);
return numberBuffer.getShort(nextReadPosition);
}
private int readInt()
throws IOException
{
MessageBuffer numberBuffer = prepareNumberBuffer(4);
return numberBuffer.getInt(nextReadPosition);
}
private long readLong()
throws IOException
{
MessageBuffer numberBuffer = prepareNumberBuffer(8);
return numberBuffer.getLong(nextReadPosition);
}
private float readFloat()
throws IOException
{
MessageBuffer numberBuffer = prepareNumberBuffer(4);
return numberBuffer.getFloat(nextReadPosition);
}
private double readDouble()
throws IOException
{
MessageBuffer numberBuffer = prepareNumberBuffer(8);
return numberBuffer.getDouble(nextReadPosition);
}
/**
* Skip the next value, then move the cursor at the end of the value
*
* @throws IOException
*/
public void skipValue()
throws IOException
{
skipValue(1);
}
/**
* Skip next values, then move the cursor at the end of the value
*
* @param count number of values to skip
* @throws IOException
*/
public void skipValue(int count)
throws IOException
{
while (count > 0) {
byte b = readByte();
MessageFormat f = MessageFormat.valueOf(b);
switch (f) {
case POSFIXINT:
case NEGFIXINT:
case BOOLEAN:
case NIL:
break;
case FIXMAP: {
int mapLen = b & 0x0f;
count += mapLen * 2;
break;
}
case FIXARRAY: {
int arrayLen = b & 0x0f;
count += arrayLen;
break;
}
case FIXSTR: {
int strLen = b & 0x1f;
skipPayload(strLen);
break;
}
case INT8:
case UINT8:
skipPayload(1);
break;
case INT16:
case UINT16:
skipPayload(2);
break;
case INT32:
case UINT32:
case FLOAT32:
skipPayload(4);
break;
case INT64:
case UINT64:
case FLOAT64:
skipPayload(8);
break;
case BIN8:
case STR8:
skipPayload(readNextLength8());
break;
case BIN16:
case STR16:
skipPayload(readNextLength16());
break;
case BIN32:
case STR32:
skipPayload(readNextLength32());
break;
case FIXEXT1:
skipPayload(2);
break;
case FIXEXT2:
skipPayload(3);
break;
case FIXEXT4:
skipPayload(5);
break;
case FIXEXT8:
skipPayload(9);
break;
case FIXEXT16:
skipPayload(17);
break;
case EXT8:
skipPayload(readNextLength8() + 1);
break;
case EXT16:
skipPayload(readNextLength16() + 1);
break;
case EXT32:
int extLen = readNextLength32();
// Skip the first ext type header (1-byte) first in case ext length is Integer.MAX_VALUE
skipPayload(1);
skipPayload(extLen);
break;
case ARRAY16:
count += readNextLength16();
break;
case ARRAY32:
count += readNextLength32();
break;
case MAP16:
count += readNextLength16() * 2;
break;
case MAP32:
count += readNextLength32() * 2; // TODO check int overflow
break;
case NEVER_USED:
throw new MessageNeverUsedFormatException("Encountered 0xC1 \"NEVER_USED\" byte");
}
count--;
}
}
/**
* Create an exception for the case when an unexpected byte value is read
*
* @param expected
* @param b
* @return
* @throws MessageFormatException
*/
private static MessagePackException unexpected(String expected, byte b)
{
MessageFormat format = MessageFormat.valueOf(b);
if (format == MessageFormat.NEVER_USED) {
return new MessageNeverUsedFormatException(String.format("Expected %s, but encountered 0xC1 \"NEVER_USED\" byte", expected));
}
else {
String name = format.getValueType().name();
String typeName = name.substring(0, 1) + name.substring(1).toLowerCase();
return new MessageTypeException(String.format("Expected %s, but got %s (%02x)", expected, typeName, b));
}
}
private static MessagePackException unexpectedExtension(String expected, int expectedType, int actualType)
{
return new MessageTypeException(String.format("Expected extension type %s (%d), but got extension type %d",
expected, expectedType, actualType));
}
public ImmutableValue unpackValue()
throws IOException
{
MessageFormat mf = getNextFormat();
switch (mf.getValueType()) {
case NIL:
readByte();
return ValueFactory.newNil();
case BOOLEAN:
return ValueFactory.newBoolean(unpackBoolean());
case INTEGER:
if (mf == MessageFormat.UINT64) {
return ValueFactory.newInteger(unpackBigInteger());
}
else {
return ValueFactory.newInteger(unpackLong());
}
case FLOAT:
return ValueFactory.newFloat(unpackDouble());
case STRING: {
int length = unpackRawStringHeader();
if (length > stringSizeLimit) {
throw new MessageSizeException(String.format("cannot unpack a String of size larger than %,d: %,d", stringSizeLimit, length), length);
}
return ValueFactory.newString(readPayload(length), true);
}
case BINARY: {
int length = unpackBinaryHeader();
return ValueFactory.newBinary(readPayload(length), true);
}
case ARRAY: {
int size = unpackArrayHeader();
Value[] array = new Value[size];
for (int i = 0; i < size; i++) {
array[i] = unpackValue();
}
return ValueFactory.newArray(array, true);
}
case MAP: {
int size = unpackMapHeader();
Value[] kvs = new Value[size * 2];
for (int i = 0; i < size * 2; ) {
kvs[i] = unpackValue();
i++;
kvs[i] = unpackValue();
i++;
}
return ValueFactory.newMap(kvs, true);
}
case EXTENSION: {
ExtensionTypeHeader extHeader = unpackExtensionTypeHeader();
switch (extHeader.getType()) {
case EXT_TIMESTAMP:
return ValueFactory.newTimestamp(unpackTimestamp(extHeader));
default:
return ValueFactory.newExtension(extHeader.getType(), readPayload(extHeader.getLength()));
}
}
default:
throw new MessageNeverUsedFormatException("Unknown value type");
}
}
public Variable unpackValue(Variable var)
throws IOException
{
MessageFormat mf = getNextFormat();
switch (mf.getValueType()) {
case NIL:
readByte();
var.setNilValue();
return var;
case BOOLEAN:
var.setBooleanValue(unpackBoolean());
return var;
case INTEGER:
switch (mf) {
case UINT64:
var.setIntegerValue(unpackBigInteger());
return var;
default:
var.setIntegerValue(unpackLong());
return var;
}
case FLOAT:
var.setFloatValue(unpackDouble());
return var;
case STRING: {
int length = unpackRawStringHeader();
if (length > stringSizeLimit) {
throw new MessageSizeException(String.format("cannot unpack a String of size larger than %,d: %,d", stringSizeLimit, length), length);
}
var.setStringValue(readPayload(length));
return var;
}
case BINARY: {
int length = unpackBinaryHeader();
var.setBinaryValue(readPayload(length));
return var;
}
case ARRAY: {
int size = unpackArrayHeader();
Value[] kvs = new Value[size];
for (int i = 0; i < size; i++) {
kvs[i] = unpackValue();
}
var.setArrayValue(kvs);
return var;
}
case MAP: {
int size = unpackMapHeader();
Value[] kvs = new Value[size * 2];
for (int i = 0; i < size * 2; ) {
kvs[i] = unpackValue();
i++;
kvs[i] = unpackValue();
i++;
}
var.setMapValue(kvs);
return var;
}
case EXTENSION: {
ExtensionTypeHeader extHeader = unpackExtensionTypeHeader();
switch (extHeader.getType()) {
case EXT_TIMESTAMP:
var.setTimestampValue(unpackTimestamp(extHeader));
break;
default:
var.setExtensionValue(extHeader.getType(), readPayload(extHeader.getLength()));
}
return var;
}
default:
throw new MessageFormatException("Unknown value type");
}
}
/**
* Reads a Nil byte.
*
* @throws MessageTypeException when value is not MessagePack Nil type
* @throws IOException when underlying input throws IOException
*/
public void unpackNil()
throws IOException
{
byte b = readByte();
if (b == Code.NIL) {
return;
}
throw unexpected("Nil", b);
}
/**
* Peeks a Nil byte and reads it if next byte is a nil value.
*
* The difference from {@link #unpackNil()} is that unpackNil throws an exception if the next byte is not nil value
* while this tryUnpackNil method returns false without changing position.
*
* @return true if a nil value is read
* @throws MessageInsufficientBufferException when the end of file reached
* @throws IOException when underlying input throws IOException
*/
public boolean tryUnpackNil()
throws IOException
{
// makes sure that buffer has at least 1 byte
if (!ensureBuffer()) {
throw new MessageInsufficientBufferException();
}
byte b = buffer.getByte(position);
if (b == Code.NIL) {
readByte();
return true;
}
return false;
}
/**
* Reads true or false.
*
* @return the read value
* @throws MessageTypeException when value is not MessagePack Boolean type
* @throws IOException when underlying input throws IOException
*/
public boolean unpackBoolean()
throws IOException
{
byte b = readByte();
if (b == Code.FALSE) {
return false;
}
else if (b == Code.TRUE) {
return true;
}
throw unexpected("boolean", b);
}
/**
* Reads a byte.
*
* This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of byte. This may happen when {@link #getNextFormat()} returns UINT8, INT16, or larger integer formats.
*
* @return the read value
* @throws MessageIntegerOverflowException when value doesn't fit in the range of byte
* @throws MessageTypeException when value is not MessagePack Integer type
* @throws IOException when underlying input throws IOException
*/
public byte unpackByte()
throws IOException
{
byte b = readByte();
if (Code.isFixInt(b)) {
return b;
}
switch (b) {
case Code.UINT8: // unsigned int 8
byte u8 = readByte();
if (u8 < (byte) 0) {
throw overflowU8(u8);
}
return u8;
case Code.UINT16: // unsigned int 16
short u16 = readShort();
if (u16 < 0 || u16 > Byte.MAX_VALUE) {
throw overflowU16(u16);
}
return (byte) u16;
case Code.UINT32: // unsigned int 32
int u32 = readInt();
if (u32 < 0 || u32 > Byte.MAX_VALUE) {
throw overflowU32(u32);
}
return (byte) u32;
case Code.UINT64: // unsigned int 64
long u64 = readLong();
if (u64 < 0L || u64 > Byte.MAX_VALUE) {
throw overflowU64(u64);
}
return (byte) u64;
case Code.INT8: // signed int 8
byte i8 = readByte();
return i8;
case Code.INT16: // signed int 16
short i16 = readShort();
if (i16 < Byte.MIN_VALUE || i16 > Byte.MAX_VALUE) {
throw overflowI16(i16);
}
return (byte) i16;
case Code.INT32: // signed int 32
int i32 = readInt();
if (i32 < Byte.MIN_VALUE || i32 > Byte.MAX_VALUE) {
throw overflowI32(i32);
}
return (byte) i32;
case Code.INT64: // signed int 64
long i64 = readLong();
if (i64 < Byte.MIN_VALUE || i64 > Byte.MAX_VALUE) {
throw overflowI64(i64);
}
return (byte) i64;
}
throw unexpected("Integer", b);
}
/**
* Reads a short.
*
* This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of short. This may happen when {@link #getNextFormat()} returns UINT16, INT32, or larger integer formats.
*
* @return the read value
* @throws MessageIntegerOverflowException when value doesn't fit in the range of short
* @throws MessageTypeException when value is not MessagePack Integer type
* @throws IOException when underlying input throws IOException
*/
public short unpackShort()
throws IOException
{
byte b = readByte();
if (Code.isFixInt(b)) {
return (short) b;
}
switch (b) {
case Code.UINT8: // unsigned int 8
byte u8 = readByte();
return (short) (u8 & 0xff);
case Code.UINT16: // unsigned int 16
short u16 = readShort();
if (u16 < (short) 0) {
throw overflowU16(u16);
}
return u16;
case Code.UINT32: // unsigned int 32
int u32 = readInt();
if (u32 < 0 || u32 > Short.MAX_VALUE) {
throw overflowU32(u32);
}
return (short) u32;
case Code.UINT64: // unsigned int 64
long u64 = readLong();
if (u64 < 0L || u64 > Short.MAX_VALUE) {
throw overflowU64(u64);
}
return (short) u64;
case Code.INT8: // signed int 8
byte i8 = readByte();
return (short) i8;
case Code.INT16: // signed int 16
short i16 = readShort();
return i16;
case Code.INT32: // signed int 32
int i32 = readInt();
if (i32 < Short.MIN_VALUE || i32 > Short.MAX_VALUE) {
throw overflowI32(i32);
}
return (short) i32;
case Code.INT64: // signed int 64
long i64 = readLong();
if (i64 < Short.MIN_VALUE || i64 > Short.MAX_VALUE) {
throw overflowI64(i64);
}
return (short) i64;
}
throw unexpected("Integer", b);
}
/**
* Reads a int.
*
* This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of int. This may happen when {@link #getNextFormat()} returns UINT32, INT64, or larger integer formats.
*
* @return the read value
* @throws MessageIntegerOverflowException when value doesn't fit in the range of int
* @throws MessageTypeException when value is not MessagePack Integer type
* @throws IOException when underlying input throws IOException
*/
public int unpackInt()
throws IOException
{
byte b = readByte();
if (Code.isFixInt(b)) {
return (int) b;
}
switch (b) {
case Code.UINT8: // unsigned int 8
byte u8 = readByte();
return u8 & 0xff;
case Code.UINT16: // unsigned int 16
short u16 = readShort();
return u16 & 0xffff;
case Code.UINT32: // unsigned int 32
int u32 = readInt();
if (u32 < 0) {
throw overflowU32(u32);
}
return u32;
case Code.UINT64: // unsigned int 64
long u64 = readLong();
if (u64 < 0L || u64 > (long) Integer.MAX_VALUE) {
throw overflowU64(u64);
}
return (int) u64;
case Code.INT8: // signed int 8
byte i8 = readByte();
return i8;
case Code.INT16: // signed int 16
short i16 = readShort();
return i16;
case Code.INT32: // signed int 32
int i32 = readInt();
return i32;
case Code.INT64: // signed int 64
long i64 = readLong();
if (i64 < (long) Integer.MIN_VALUE || i64 > (long) Integer.MAX_VALUE) {
throw overflowI64(i64);
}
return (int) i64;
}
throw unexpected("Integer", b);
}
/**
* Reads a long.
*
* This method throws {@link MessageIntegerOverflowException} if the value doesn't fit in the range of long. This may happen when {@link #getNextFormat()} returns UINT64.
*
* @return the read value
* @throws MessageIntegerOverflowException when value doesn't fit in the range of long
* @throws MessageTypeException when value is not MessagePack Integer type
* @throws IOException when underlying input throws IOException
*/
public long unpackLong()
throws IOException
{
byte b = readByte();