-
-
Notifications
You must be signed in to change notification settings - Fork 128
/
CBORGenerator.java
1754 lines (1581 loc) · 59.4 KB
/
CBORGenerator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.fasterxml.jackson.dataformat.cbor;
import java.util.Arrays;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.GeneratorBase;
import com.fasterxml.jackson.core.io.IOContext;
import com.fasterxml.jackson.core.json.DupDetector;
import static com.fasterxml.jackson.dataformat.cbor.CBORConstants.*;
/**
* {@link JsonGenerator} implementation that writes CBOR encoded content.
*
* @author Tatu Saloranta
*/
public class CBORGenerator extends GeneratorBase
{
private final static int[] NO_INTS = new int[0];
/**
* Let's ensure that we have big enough output buffer because of safety
* margins we need for UTF-8 encoding.
*/
final static int BYTE_BUFFER_FOR_OUTPUT = 16000;
/**
* Longest char chunk we will output is chosen so that it is guaranteed to
* fit in an empty buffer even if everything encoded in 3-byte sequences;
* but also fit two full chunks in case of single-byte (ascii) output.
*/
private final static int MAX_LONG_STRING_CHARS = (BYTE_BUFFER_FOR_OUTPUT / 4) - 4;
/**
* This is the worst case length (in bytes) of maximum chunk we ever write.
*/
private final static int MAX_LONG_STRING_BYTES = (MAX_LONG_STRING_CHARS * 3) + 3;
/**
* Enumeration that defines all togglable features for CBOR generator.
*/
public enum Feature implements FormatFeature {
/**
* Feature that determines whether generator should try to use smallest
* (size-wise) integer representation: if true, will use smallest
* representation that is enough to retain value; if false, will use
* length indicated by argument type (4-byte for <code>int</code>,
* 8-byte for <code>long</code> and so on).
*/
WRITE_MINIMAL_INTS(true),
/**
* Feature that determines whether CBOR "Self-Describe Tag" (value
* 55799, encoded as 3-byte sequence of <code>0xD9, 0xD9, 0xF7</code>)
* should be written at the beginning of document or not.
* <p>
* Default value is <code>false</code> meaning that type tag will not be
* written at the beginning of a new document.
*
* @since 2.5
*/
WRITE_TYPE_HEADER(false), ;
protected final boolean _defaultState;
protected final int _mask;
/**
* Method that calculates bit set (flags) of all features that are
* enabled by default.
*/
public static int collectDefaults() {
int flags = 0;
for (Feature f : values()) {
if (f.enabledByDefault()) {
flags |= f.getMask();
}
}
return flags;
}
private Feature(boolean defaultState) {
_defaultState = defaultState;
_mask = (1 << ordinal());
}
@Override
public boolean enabledByDefault() {
return _defaultState;
}
@Override
public boolean enabledIn(int flags) {
return (flags & getMask()) != 0;
}
@Override
public int getMask() {
return _mask;
}
}
/**
* To simplify certain operations, we require output buffer length to allow
* outputting of contiguous 256 character UTF-8 encoded String value. Length
* of the longest UTF-8 code point (from Java char) is 3 bytes, and we need
* both initial token byte and single-byte end marker so we get following
* value.
* <p>
* Note: actually we could live with shorter one; absolute minimum would be
* for encoding 64-character Strings.
*/
private final static int MIN_BUFFER_LENGTH = (3 * 256) + 2;
/**
* Special value that is use to keep tracks of arrays and maps opened with infinite length
*/
private final static int INDEFINITE_LENGTH = -2; // just to allow -1 as marker for "one too many"
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
final protected IOContext _ioContext;
final protected OutputStream _out;
/**
* Bit flag composed of bits that indicate which
* {@link CBORGenerator.Feature}s are enabled.
*/
protected int _formatFeatures;
protected boolean _cfgMinimalInts;
/*
/**********************************************************
/* Output state
/**********************************************************
*/
/**
* @since 2.10
*/
protected CBORWriteContext _cborContext;
/*
/**********************************************************
/* Output buffering
/**********************************************************
*/
/**
* Intermediate buffer in which contents are buffered before being written
* using {@link #_out}.
*/
protected byte[] _outputBuffer;
/**
* Pointer to the next available byte in {@link #_outputBuffer}
*/
protected int _outputTail = 0;
/**
* Offset to index after the last valid index in {@link #_outputBuffer}.
* Typically same as length of the buffer.
*/
protected final int _outputEnd;
/**
* Intermediate buffer in which characters of a String are copied before
* being encoded.
*/
protected char[] _charBuffer;
protected final int _charBufferLength;
/**
* Let's keep track of how many bytes have been output, may prove useful
* when debugging. This does <b>not</b> include bytes buffered in the output
* buffer, just bytes that have been written using underlying stream writer.
*/
protected int _bytesWritten;
/*
/**********************************************************
/* Tracking of remaining elements to write
/**********************************************************
*/
protected int[] _elementCounts = NO_INTS;
protected int _elementCountsPtr;
/**
* Number of elements remaining in the current complex structure (if any),
* when writing defined-length Arrays, Objects; marker {@link #INDEFINITE_LENGTH}
* otherwise.
*/
protected int _currentRemainingElements = INDEFINITE_LENGTH;
/*
/**********************************************************
/* Shared String detection
/**********************************************************
*/
/**
* Flag that indicates whether the output buffer is recycable (and needs to
* be returned to recycler once we are done) or not.
*/
protected boolean _bufferRecyclable;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures,
ObjectCodec codec, OutputStream out) {
super(stdFeatures, codec, /* Write Context */ null);
DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)
? DupDetector.rootDetector(this)
: null;
// NOTE: we passed `null` for default write context
_cborContext = CBORWriteContext.createRootContext(dups);
_formatFeatures = formatFeatures;
_cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures);
_ioContext = ctxt;
_out = out;
_bufferRecyclable = true;
_outputBuffer = ctxt.allocWriteEncodingBuffer(BYTE_BUFFER_FOR_OUTPUT);
_outputEnd = _outputBuffer.length;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
// let's just sanity check to prevent nasty odd errors
if (_outputEnd < MIN_BUFFER_LENGTH) {
throw new IllegalStateException("Internal encoding buffer length ("
+ _outputEnd + ") too short, must be at least "
+ MIN_BUFFER_LENGTH);
}
}
/**
* Alternative constructor that may be used to feed partially initialized content.
*
* @param outputBuffer
* Buffer to use for output before flushing to the underlying stream
* @param offset
* Offset pointing past already buffered content; that is, number
* of bytes of valid content to output, within buffer.
*/
public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures,
ObjectCodec codec, OutputStream out, byte[] outputBuffer,
int offset, boolean bufferRecyclable) {
super(stdFeatures, codec, /* Write Context */ null);
DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)
? DupDetector.rootDetector(this)
: null;
// NOTE: we passed `null` for default write context
_cborContext = CBORWriteContext.createRootContext(dups);
_formatFeatures = formatFeatures;
_cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures);
_ioContext = ctxt;
_out = out;
_bufferRecyclable = bufferRecyclable;
_outputTail = offset;
_outputBuffer = outputBuffer;
_outputEnd = _outputBuffer.length;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
// let's just sanity check to prevent nasty odd errors
if (_outputEnd < MIN_BUFFER_LENGTH) {
throw new IllegalStateException("Internal encoding buffer length ("
+ _outputEnd + ") too short, must be at least "
+ MIN_BUFFER_LENGTH);
}
}
/*
/**********************************************************
/* Versioned
/**********************************************************
*/
@Override
public Version version() {
return PackageVersion.VERSION;
}
/*
/**********************************************************
/* Capability introspection
/**********************************************************
*/
@Override
public boolean canWriteBinaryNatively() {
return true;
}
/*
/**********************************************************
/* Overridden methods, configuration
/**********************************************************
*/
/**
* No way (or need) to indent anything, so let's block any attempts. (should
* we throw an exception instead?)
*/
@Override
public JsonGenerator useDefaultPrettyPrinter() {
return this;
}
/**
* No way (or need) to indent anything, so let's block any attempts. (should
* we throw an exception instead?)
*/
@Override
public JsonGenerator setPrettyPrinter(PrettyPrinter pp) {
return this;
}
@Override
public Object getOutputTarget() {
return _out;
}
@Override
public int getOutputBuffered() {
return _outputTail;
}
// public JsonParser overrideStdFeatures(int values, int mask)
@Override
public int getFormatFeatures() {
return _formatFeatures;
}
@Override
public JsonGenerator overrideStdFeatures(int values, int mask) {
int oldState = _features;
int newState = (oldState & ~mask) | (values & mask);
if (oldState != newState) {
_features = newState;
}
return this;
}
@Override
public JsonGenerator overrideFormatFeatures(int values, int mask) {
int oldState = _formatFeatures;
int newState = (_formatFeatures & ~mask) | (values & mask);
if (oldState != newState) {
_formatFeatures = newState;
_cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(newState);
}
return this;
}
/*
/**********************************************************
/* Overridden methods, output context (and related)
/**********************************************************
*/
@Override
public Object getCurrentValue() {
return _cborContext.getCurrentValue();
}
@Override
public void setCurrentValue(Object v) {
_cborContext.setCurrentValue(v);
}
@Override
public JsonStreamContext getOutputContext() {
return _cborContext;
}
/*
/**********************************************************
/* Extended API, configuration
/**********************************************************
*/
public CBORGenerator enable(Feature f) {
_formatFeatures |= f.getMask();
if (f == Feature.WRITE_MINIMAL_INTS) {
_cfgMinimalInts = true;
}
return this;
}
public CBORGenerator disable(Feature f) {
_formatFeatures &= ~f.getMask();
if (f == Feature.WRITE_MINIMAL_INTS) {
_cfgMinimalInts = false;
}
return this;
}
public final boolean isEnabled(Feature f) {
return (_formatFeatures & f.getMask()) != 0;
}
public CBORGenerator configure(Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
/*
/**********************************************************
/* Overridden methods, write methods
/**********************************************************
*/
/*
* And then methods overridden to make final, streamline some aspects...
*/
@Override
public final void writeFieldName(String name) throws IOException {
if (!_cborContext.writeFieldName(name)) {
_reportError("Can not write a field name, expecting a value");
}
_writeString(name);
}
@Override
public final void writeFieldName(SerializableString name)
throws IOException {
// Object is a value, need to verify it's allowed
if (!_cborContext.writeFieldName(name.getValue())) {
_reportError("Can not write a field name, expecting a value");
}
byte[] raw = name.asUnquotedUTF8();
final int len = raw.length;
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeLengthMarker(PREFIX_TYPE_TEXT, len);
_writeBytes(raw, 0, len);
}
@Override // since 2.8
public final void writeFieldId(long id) throws IOException {
if (!_cborContext.writeFieldId(id)) {
_reportError("Can not write a field id, expecting a value");
}
_writeLongNoCheck(id);
}
/*
/**********************************************************
/* Overridden methods, copying with tag-awareness
/**********************************************************
*/
/**
* Specialize {@link JsonGenerator#copyCurrentEvent} to handle tags.
*/
@Override
public void copyCurrentEvent(JsonParser p) throws IOException {
maybeCopyTag(p);
super.copyCurrentEvent(p);
}
/**
* Specialize {@link JsonGenerator#copyCurrentStructure} to handle tags.
*/
@Override
public void copyCurrentStructure(JsonParser p) throws IOException {
maybeCopyTag(p);
super.copyCurrentStructure(p);
}
protected void maybeCopyTag(JsonParser p) throws IOException {
if (p instanceof CBORParser) {
if (p.hasCurrentToken()) {
final int currentTag = ((CBORParser) p).getCurrentTag();
if (currentTag != -1) {
writeTag(currentTag);
}
}
}
}
/*
/**********************************************************
/* Output method implementations, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException {
_verifyValueWrite("start an array");
_cborContext = _cborContext.createChildArrayContext(null);
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_ARRAY_INDEFINITE);
}
/*
* Unlike with JSON, this method is using slightly optimized version since
* CBOR has a variant that allows embedding length in array start marker.
*/
@Override
public void writeStartArray(int elementsToWrite) throws IOException {
_verifyValueWrite("start an array");
_cborContext = _cborContext.createChildArrayContext(null);
_pushRemainingElements();
_currentRemainingElements = elementsToWrite;
_writeLengthMarker(PREFIX_TYPE_ARRAY, elementsToWrite);
}
@Override
public final void writeEndArray() throws IOException {
if (!_cborContext.inArray()) {
_reportError("Current context not Array but "+_cborContext.typeDesc());
}
closeComplexElement();
_cborContext = _cborContext.getParent();
}
@Override
public final void writeStartObject() throws IOException {
_verifyValueWrite("start an object");
_cborContext = _cborContext.createChildObjectContext(null);
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_OBJECT_INDEFINITE);
}
@Override
// since 2.8
public final void writeStartObject(Object forValue) throws IOException {
_verifyValueWrite("start an object");
CBORWriteContext ctxt = _cborContext.createChildObjectContext(forValue);
_cborContext = ctxt;
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_OBJECT_INDEFINITE);
}
public final void writeStartObject(int elementsToWrite) throws IOException {
_verifyValueWrite("start an object");
_cborContext = _cborContext.createChildObjectContext(null);
_pushRemainingElements();
_currentRemainingElements = elementsToWrite;
_writeLengthMarker(PREFIX_TYPE_OBJECT, elementsToWrite);
}
@Override
public final void writeEndObject() throws IOException {
if (!_cborContext.inObject()) {
_reportError("Current context not Object but "+ _cborContext.typeDesc());
}
closeComplexElement();
_cborContext = _cborContext.getParent();
}
@Override // since 2.8
public void writeArray(int[] array, int offset, int length) throws IOException
{
_verifyOffsets(array.length, offset, length);
// short-cut, do not create child array context etc
_verifyValueWrite("write int array");
_writeLengthMarker(PREFIX_TYPE_ARRAY, length);
for (int i = offset, end = offset+length; i < end; ++i) {
_writeIntNoCheck(array[i]);
}
}
@Override // since 2.8
public void writeArray(long[] array, int offset, int length) throws IOException
{
_verifyOffsets(array.length, offset, length);
// short-cut, do not create child array context etc
_verifyValueWrite("write int array");
_writeLengthMarker(PREFIX_TYPE_ARRAY, length);
for (int i = offset, end = offset+length; i < end; ++i) {
_writeLongNoCheck(array[i]);
}
}
@Override // since 2.8
public void writeArray(double[] array, int offset, int length) throws IOException
{
_verifyOffsets(array.length, offset, length);
// short-cut, do not create child array context etc
_verifyValueWrite("write int array");
_writeLengthMarker(PREFIX_TYPE_ARRAY, length);
for (int i = offset, end = offset+length; i < end; ++i) {
_writeDoubleNoCheck(array[i]);
}
}
// @since 2.8.8
private final void _pushRemainingElements() {
if (_elementCounts.length == _elementCountsPtr) { // initially, as well as if full
_elementCounts = Arrays.copyOf(_elementCounts, _elementCounts.length+10);
}
_elementCounts[_elementCountsPtr++] = _currentRemainingElements;
}
private final void _writeIntNoCheck(int i) throws IOException {
int marker;
if (i < 0) {
i = -i - 1;
marker = PREFIX_TYPE_INT_NEG;
} else {
marker = PREFIX_TYPE_INT_POS;
}
// if ((_outputTail + needed) >= _outputEnd) { _flushBuffer(); }
_ensureRoomForOutput(5);
byte b0;
if (_cfgMinimalInts) {
if (i < 24) {
_outputBuffer[_outputTail++] = (byte) (marker + i);
return;
}
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT8_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
return;
}
b0 = (byte) i;
i >>= 8;
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT16_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
return;
}
} else {
b0 = (byte) i;
i >>= 8;
}
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
}
private final void _writeIntMinimal(int markerBase, int i) throws IOException
{
_ensureRoomForOutput(5);
byte b0;
if (i >= 0) {
if (i < 24) {
_outputBuffer[_outputTail++] = (byte) (markerBase + i);
return;
}
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT8_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
return;
}
b0 = (byte) i;
i >>= 8;
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT16_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
return;
}
} else {
b0 = (byte) i;
i >>= 8;
}
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
}
private final void _writeLongNoCheck(long l) throws IOException {
if (_cfgMinimalInts) {
if (l >= 0) {
if (l <= 0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_POS, (int) l);
return;
}
} else if (l >= -0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_NEG, (int) (-l - 1));
return;
}
}
_ensureRoomForOutput(9);
if (l < 0L) {
l += 1;
l = -l;
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS);
} else {
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS);
}
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
private final void _writeDoubleNoCheck(double d) throws IOException {
_ensureRoomForOutput(11);
// 17-Apr-2010, tatu: could also use 'doubleToIntBits', but it seems
// more accurate to use exact representation; and possibly faster.
// However, if there are cases where collapsing of NaN was needed (for
// non-Java clients), this can be changed
long l = Double.doubleToRawLongBits(d);
_outputBuffer[_outputTail++] = BYTE_FLOAT64;
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
/*
/***********************************************************
/* Output method implementations, textual
/***********************************************************
*/
@Override
public void writeString(String text) throws IOException {
if (text == null) {
writeNull();
return;
}
_verifyValueWrite("write String value");
_writeString(text);
}
@Override
public final void writeString(SerializableString sstr) throws IOException {
_verifyValueWrite("write String value");
byte[] raw = sstr.asUnquotedUTF8();
final int len = raw.length;
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeLengthMarker(PREFIX_TYPE_TEXT, len);
_writeBytes(raw, 0, len);
}
@Override
public void writeString(char[] text, int offset, int len)
throws IOException {
_verifyValueWrite("write String value");
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeString(text, offset, len);
}
@Override
public void writeRawUTF8String(byte[] raw, int offset, int len)
throws IOException
{
_verifyValueWrite("write String value");
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeLengthMarker(PREFIX_TYPE_TEXT, len);
_writeBytes(raw, 0, len);
}
@Override
public final void writeUTF8String(byte[] text, int offset, int len)
throws IOException {
// Since no escaping is needed, same as 'writeRawUTF8String'
writeRawUTF8String(text, offset, len);
}
/*
/**********************************************************
/* Output method implementations, unprocessed ("raw")
/**********************************************************
*/
@Override
public void writeRaw(String text) throws IOException {
throw _notSupported();
}
@Override
public void writeRaw(String text, int offset, int len) throws IOException {
throw _notSupported();
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException {
throw _notSupported();
}
@Override
public void writeRaw(char c) throws IOException {
throw _notSupported();
}
@Override
public void writeRawValue(String text) throws IOException {
throw _notSupported();
}
@Override
public void writeRawValue(String text, int offset, int len)
throws IOException {
throw _notSupported();
}
@Override
public void writeRawValue(char[] text, int offset, int len)
throws IOException {
throw _notSupported();
}
/*
* /********************************************************** /* Output
* method implementations, base64-encoded binary
* /**********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant, byte[] data, int offset,
int len) throws IOException {
if (data == null) {
writeNull();
return;
}
_verifyValueWrite("write Binary value");
_writeLengthMarker(PREFIX_TYPE_BYTES, len);
_writeBytes(data, offset, len);
}
@Override
public int writeBinary(InputStream data, int dataLength) throws IOException {
/*
* 28-Mar-2014, tatu: Theoretically we could implement encoder that uses
* chunking to output binary content of unknown (a priori) length. But
* for no let's require knowledge of length, for simplicity: may be
* revisited in future.
*/
if (dataLength < 0) {
throw new UnsupportedOperationException(
"Must pass actual length for CBOR encoded data");
}
_verifyValueWrite("write Binary value");
int missing;
_writeLengthMarker(PREFIX_TYPE_BYTES, dataLength);
missing = _writeBytes(data, dataLength);
if (missing > 0) {
_reportError("Too few bytes available: missing " + missing
+ " bytes (out of " + dataLength + ")");
}
return dataLength;
}
@Override
public int writeBinary(Base64Variant b64variant, InputStream data,
int dataLength) throws IOException {
return writeBinary(data, dataLength);
}
/*
/**********************************************************
/* Output method implementations, primitive
/**********************************************************
*/
@Override
public void writeBoolean(boolean state) throws IOException {
_verifyValueWrite("write boolean value");
if (state) {
_writeByte(BYTE_TRUE);
} else {
_writeByte(BYTE_FALSE);
}
}
@Override
public void writeNull() throws IOException {
_verifyValueWrite("write null value");
_writeByte(BYTE_NULL);
}
@Override
public void writeNumber(int i) throws IOException {
_verifyValueWrite("write number");
int marker;
if (i < 0) {
i = -i - 1;
marker = PREFIX_TYPE_INT_NEG;
} else {
marker = PREFIX_TYPE_INT_POS;
}
_ensureRoomForOutput(5);
byte b0;
if (_cfgMinimalInts) {
if (i < 24) {
_outputBuffer[_outputTail++] = (byte) (marker + i);
return;
}
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT8_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
return;
}
b0 = (byte) i;
i >>= 8;
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT16_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
return;
}
} else {
b0 = (byte) i;
i >>= 8;
}
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
}
@Override
public void writeNumber(long l) throws IOException {
_verifyValueWrite("write number");
if (_cfgMinimalInts) { // maybe 32 bits is enough?
if (l >= 0) {
if (l <= 0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_POS, (int) l);
return;
}
} else if (l >= -0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_NEG, (int) (-l - 1));
return;
}
}
_ensureRoomForOutput(9);
if (l < 0L) {
l += 1;
l = -l;
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS);
} else {
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS);
}
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);