-
-
Notifications
You must be signed in to change notification settings - Fork 128
/
SmileGenerator.java
2801 lines (2592 loc) · 103 KB
/
SmileGenerator.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.smile;
import java.io.*;
import java.lang.ref.SoftReference;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.*;
import com.fasterxml.jackson.core.json.DupDetector;
import com.fasterxml.jackson.core.util.JacksonFeatureSet;
import com.fasterxml.jackson.core.base.GeneratorBase;
import static com.fasterxml.jackson.dataformat.smile.SmileConstants.*;
/**
* {@link JsonGenerator} implementation for Smile-encoded content
* (see <a href="http://wiki.fasterxml.com/SmileFormatSpec">Smile Format Specification</a>)
*/
public class SmileGenerator
extends GeneratorBase
{
/**
* Enumeration that defines all togglable features for Smile generators.
*/
public enum Feature
implements FormatFeature // since 2.7
{
/**
* Whether to write 4-byte header sequence when starting output or not.
* If disabled, no header is written; this may be useful in embedded cases
* where context is enough to know that content is encoded using this format.
* Note, however, that omitting header means that default settings for
* shared names/string values can not be changed.
*<p>
* Default setting is true, meaning that header will be written.
*/
WRITE_HEADER(true),
/**
* Whether write byte marker that signifies end of logical content segment
* ({@link SmileConstants#BYTE_MARKER_END_OF_CONTENT}) when
* {@link #close} is called or not. This can be useful when outputting
* multiple adjacent logical content segments (documents) into single
* physical output unit (file).
*<p>
* Default setting is false meaning that such marker is not written.
*/
WRITE_END_MARKER(false),
/**
* Whether to use simple 7-bit per byte encoding for binary content when output.
* This is necessary ensure that byte 0xFF will never be included in content output.
* For other data types this limitation is handled automatically. This setting is enabled
* by default, however, overhead for binary data (14% size expansion, processing overhead)
* is non-negligible. If no binary data is output, feature has no effect.
*<p>
* Default setting is true, indicating that binary data is quoted as 7-bit bytes
* instead of written raw.
*/
ENCODE_BINARY_AS_7BIT(true),
/**
* Whether generator should check if it can "share" field names during generating
* content or not. If enabled, can replace repeating field names with back references,
* which are more compact and should faster to decode. Downside is that there is some
* overhead for writing (need to track existing values, check), as well as decoding.
*<p>
* Since field names tend to repeat quite often, this setting is enabled by default.
*/
CHECK_SHARED_NAMES(true),
/**
* Whether generator should check if it can "share" short (at most 64 bytes encoded)
* String value during generating
* content or not. If enabled, can replace repeating Short String values with back references,
* which are more compact and should faster to decode. Downside is that there is some
* overhead for writing (need to track existing values, check), as well as decoding.
*<p>
* Since efficiency of this option depends a lot on type of content being produced,
* this option is disabled by default, and should only be enabled if it is likely that
* same values repeat relatively often.
*/
CHECK_SHARED_STRING_VALUES(false),
/**
* Feature that determines if an invalid surrogate encoding found in the
* incoming String should fail with an exception or silently be output
* as the Unicode 'REPLACEMENT CHARACTER' (U+FFFD) or not; if not,
* an exception will be thrown to indicate invalid content.
*<p>
* Default value is {@code false} (for backwards compatibility) meaning that
* an invalid surrogate will result in exception ({@link IllegalArgumentException}
*
* @since 2.13
*/
LENIENT_UTF_ENCODING(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 int getMask() { return _mask; }
@Override public boolean enabledIn(int flags) { return (flags & _mask) != 0; }
}
/**
* Helper class used for keeping track of possibly shareable String
* references (for field names and/or short String values)
*/
protected final static class SharedStringNode
{
public final String value;
public final int index;
public SharedStringNode next;
public SharedStringNode(String value, int index, SharedStringNode next)
{
this.value = value;
this.index = index;
this.next = next;
}
}
/**
* 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;
protected final static byte TOKEN_BYTE_LONG_STRING_ASCII = TOKEN_MISC_LONG_TEXT_ASCII;
protected final static byte TOKEN_BYTE_INT_32 = (byte) (SmileConstants.TOKEN_PREFIX_INTEGER + TOKEN_MISC_INTEGER_32);
protected final static byte TOKEN_BYTE_INT_64 = (byte) (SmileConstants.TOKEN_PREFIX_INTEGER + TOKEN_MISC_INTEGER_64);
protected final static byte TOKEN_BYTE_BIG_INTEGER = (byte) (SmileConstants.TOKEN_PREFIX_INTEGER + TOKEN_MISC_INTEGER_BIG);
protected final static byte TOKEN_BYTE_FLOAT_32 = (byte) (SmileConstants.TOKEN_PREFIX_FP | TOKEN_MISC_FLOAT_32);
protected final static byte TOKEN_BYTE_FLOAT_64 = (byte) (SmileConstants.TOKEN_PREFIX_FP | TOKEN_MISC_FLOAT_64);
protected final static byte TOKEN_BYTE_BIG_DECIMAL = (byte) (SmileConstants.TOKEN_PREFIX_FP | TOKEN_MISC_FLOAT_BIG);
protected final static long MIN_INT_AS_LONG = (long) Integer.MIN_VALUE;
protected final static long MAX_INT_AS_LONG = (long) Integer.MAX_VALUE;
/**
* The replacement character to use to fix invalid Unicode sequences
* (mismatched surrogate pair).
*
* @since 2.13
*/
protected final static int REPLACEMENT_CHAR = 0xfffd;
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
protected final IOContext _ioContext;
protected final OutputStream _out;
/**
* Bit flag composed of bits that indicate which
* {@link com.fasterxml.jackson.dataformat.smile.SmileGenerator.Feature}s
* are enabled.
*/
protected int _formatFeatures;
/**
* Helper object used for low-level recycling of Smile-generator
* specific buffers.
*/
protected final SmileBufferRecycler<SharedStringNode> _smileBufferRecycler;
/*
/**********************************************************
/* Output state
/**********************************************************
*/
// @since 2.10 (named _smileContext before 2.13)
protected SmileWriteContext _streamWriteContext;
/*
/**********************************************************
/* 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;
/**
* 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;
/*
/**********************************************************
/* Shared String detection
/**********************************************************
*/
/**
* Raw data structure used for checking whether field name to
* write can be output using back reference or not.
*/
protected SharedStringNode[] _seenNames;
/**
* Number of entries in {@link #_seenNames}; -1 if no shared name
* detection is enabled
*/
protected int _seenNameCount;
/**
* Raw data structure used for checking whether String value to
* write can be output using back reference or not.
*/
protected SharedStringNode[] _seenStringValues;
/**
* Number of entries in {@link #_seenStringValues}; -1 if no shared text value
* detection is enabled
*/
protected int _seenStringValueCount;
/**
* 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;
/*
/**********************************************************
/* Thread-local recycling
/**********************************************************
*/
/**
* This <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference}
* to a buffer recycler used to provide a low-cost
* buffer recycling for Smile-specific buffers.
*/
final protected static ThreadLocal<SoftReference<SmileBufferRecycler<SharedStringNode>>> _smileRecyclerRef
= new ThreadLocal<SoftReference<SmileBufferRecycler<SharedStringNode>>>();
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
public SmileGenerator(IOContext ctxt, int stdFeatures, int smileFeatures,
ObjectCodec codec, OutputStream out)
{
super(stdFeatures, codec, /*WriteContext*/ null);
DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)
? DupDetector.rootDetector(this)
: null;
// NOTE: we passed `null` for default write context
_streamWriteContext = SmileWriteContext.createRootContext(dups);
_formatFeatures = smileFeatures;
_ioContext = ctxt;
_smileBufferRecycler = _smileBufferRecycler();
_out = out;
_bufferRecyclable = true;
_outputBuffer = ctxt.allocWriteEncodingBuffer();
_outputEnd = _outputBuffer.length;
// let's just sanity check to prevent nasty odd errors
if (_outputEnd < MIN_BUFFER_LENGTH) {
throw new IllegalStateException(String.format(
"Internal encoding buffer length (%d) too short, must be at least %d",
_outputEnd, MIN_BUFFER_LENGTH));
}
if (!Feature.CHECK_SHARED_NAMES.enabledIn(smileFeatures)) {
_seenNames = null;
_seenNameCount = -1;
} else {
_seenNames = _smileBufferRecycler.allocSeenNamesBuffer();
if (_seenNames == null) {
_seenNames = new SharedStringNode[SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH];
}
_seenNameCount = 0;
}
if (!Feature.CHECK_SHARED_STRING_VALUES.enabledIn(smileFeatures)) {
_seenStringValues = null;
_seenStringValueCount = -1;
} else {
_seenStringValues = _smileBufferRecycler.allocSeenStringValuesBuffer();
if (_seenStringValues == null) {
_seenStringValues = new SharedStringNode[SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH];
}
_seenStringValueCount = 0;
}
}
public SmileGenerator(IOContext ctxt, int stdFeatures, int smileFeatures,
ObjectCodec codec, OutputStream out, byte[] outputBuffer, int offset,
boolean bufferRecyclable)
{
super(stdFeatures, codec, null);
DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)
? DupDetector.rootDetector(this)
: null;
// NOTE: we passed `null` for default write context
_streamWriteContext = SmileWriteContext.createRootContext(dups);
_formatFeatures = smileFeatures;
_ioContext = ctxt;
_smileBufferRecycler = _smileBufferRecycler();
_out = out;
_bufferRecyclable = bufferRecyclable;
_outputTail = offset;
_outputBuffer = outputBuffer;
_outputEnd = _outputBuffer.length;
// let's just sanity check to prevent nasty odd errors
if (_outputEnd < MIN_BUFFER_LENGTH) {
throw new IllegalStateException(String.format(
"Internal encoding buffer length (%d) too short, must be at least %d",
_outputEnd, MIN_BUFFER_LENGTH));
}
if (!Feature.CHECK_SHARED_NAMES.enabledIn(smileFeatures)) {
_seenNames = null;
_seenNameCount = -1;
} else {
_seenNames = _smileBufferRecycler.allocSeenNamesBuffer();
if (_seenNames == null) {
_seenNames = new SharedStringNode[SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH];
}
_seenNameCount = 0;
}
if (!Feature.CHECK_SHARED_STRING_VALUES.enabledIn(smileFeatures)) {
_seenStringValues = null;
_seenStringValueCount = -1;
} else {
_seenStringValues = _smileBufferRecycler.allocSeenStringValuesBuffer();
if (_seenStringValues == null) {
_seenStringValues = new SharedStringNode[SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH];
}
_seenStringValueCount = 0;
}
}
/**
* Method that can be called to explicitly write Smile document header.
* Note that usually you do not need to call this for first document to output,
* but rather only if you intend to write multiple root-level documents
* with same generator (and even in that case this is optional thing to do).
* As a result usually only {@link SmileFactory} calls this method.
*/
public void writeHeader() throws IOException
{
int last = HEADER_BYTE_4;
if (Feature.CHECK_SHARED_NAMES.enabledIn(_formatFeatures)) {
last |= SmileConstants.HEADER_BIT_HAS_SHARED_NAMES;
}
if (Feature.CHECK_SHARED_STRING_VALUES.enabledIn(_formatFeatures)) {
last |= SmileConstants.HEADER_BIT_HAS_SHARED_STRING_VALUES;
}
if (!Feature.ENCODE_BINARY_AS_7BIT.enabledIn(_formatFeatures)) {
last |= SmileConstants.HEADER_BIT_HAS_RAW_BINARY;
}
_writeBytes(HEADER_BYTE_1, HEADER_BYTE_2, HEADER_BYTE_3, (byte) last);
}
protected final static SmileBufferRecycler<SharedStringNode> _smileBufferRecycler()
{
SoftReference<SmileBufferRecycler<SharedStringNode>> ref = _smileRecyclerRef.get();
SmileBufferRecycler<SharedStringNode> br = (ref == null) ? null : ref.get();
if (br == null) {
br = new SmileBufferRecycler<SharedStringNode>();
_smileRecyclerRef.set(new SoftReference<SmileBufferRecycler<SharedStringNode>>(br));
}
return br;
}
/*
/**********************************************************
/* Versioned
/**********************************************************
*/
@Override
public Version version() {
return PackageVersion.VERSION;
}
/*
/**********************************************************
/* Capability introspection
/**********************************************************
*/
@Override
public boolean canWriteBinaryNatively() {
return true;
}
@Override // @since 2.12
public JacksonFeatureSet<StreamWriteCapability> getWriteCapabilities() {
return DEFAULT_BINARY_WRITE_CAPABILITIES;
}
/*
/**********************************************************
/* 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 overrideFormatFeatures(int values, int mask) {
_formatFeatures = (_formatFeatures & ~mask) | (values & mask);
return this;
}
/*
/**********************************************************
/* Overridden methods, output context (and related)
/**********************************************************
*/
@Override // since 2.13
public Object currentValue() {
return _streamWriteContext.getCurrentValue();
}
@Override
public Object getCurrentValue() {
return _streamWriteContext.getCurrentValue();
}
@Override // since 2.13
public void assignCurrentValue(Object v) {
_streamWriteContext.setCurrentValue(v);
}
@Override
public void setCurrentValue(Object v) {
_streamWriteContext.setCurrentValue(v);
}
@Override
public JsonStreamContext getOutputContext() {
return _streamWriteContext;
}
/*
/**********************************************************
/* Overridden methods, write methods
/**********************************************************
*/
/* And then methods overridden to make final, streamline some
* aspects...
*/
@Override
public final void writeFieldName(String name) throws IOException
{
if (!_streamWriteContext.writeFieldName(name)) {
_reportError("Can not write a field name, expecting a value");
}
_writeFieldName(name);
}
@Override
public final void writeFieldName(SerializableString name)
throws IOException
{
// Object is a value, need to verify it's allowed
if (!_streamWriteContext.writeFieldName(name.getValue())) {
_reportError("Can not write a field name, expecting a value");
}
_writeFieldName(name);
}
/*
/**********************************************************
/* Extended API, configuration
/**********************************************************
*/
public SmileGenerator enable(Feature f) {
_formatFeatures |= f.getMask();
return this;
}
public SmileGenerator disable(Feature f) {
_formatFeatures &= ~f.getMask();
return this;
}
public final boolean isEnabled(Feature f) {
return (_formatFeatures & f.getMask()) != 0;
}
public SmileGenerator configure(Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
/*
/**********************************************************
/* Extended API, other
/**********************************************************
*/
/**
* Method for directly inserting specified byte in output at
* current position.
*<p>
* NOTE: only use this method if you really know what you are doing.
*/
public void writeRaw(byte b) throws IOException
{
/* 08-Jan-2014, tatu: Should we just rather throw an exception? For now,
* allow... maybe have a feature to cause an exception.
*/
_writeByte(b);
}
/**
* Method for directly inserting specified bytes in output at
* current position.
*<p>
* NOTE: only use this method if you really know what you are doing.
*/
public void writeBytes(byte[] data, int offset, int len) throws IOException
{
_writeBytes(data, offset, len);
}
/*
/**********************************************************
/* Output method implementations, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_verifyValueWrite("start an array");
_streamWriteContext = _streamWriteContext.createChildArrayContext(null);
_writeByte(TOKEN_LITERAL_START_ARRAY);
}
@Override // since 2.12
public final void writeStartArray(Object forValue) throws IOException
{
_verifyValueWrite("start an array");
_streamWriteContext = _streamWriteContext.createChildArrayContext(forValue);
_writeByte(TOKEN_LITERAL_START_ARRAY);
}
@Override // since 2.12
public final void writeStartArray(Object forValue, int elementsToWrite) throws IOException
{
_verifyValueWrite("start an array");
_streamWriteContext = _streamWriteContext.createChildArrayContext(forValue);
_writeByte(TOKEN_LITERAL_START_ARRAY);
}
@Deprecated // since 2.12
@Override
public final void writeStartArray(int size) throws IOException
{
_verifyValueWrite("start an array");
_streamWriteContext = _streamWriteContext.createChildArrayContext(null);
_writeByte(TOKEN_LITERAL_START_ARRAY);
}
@Override
public final void writeEndArray() throws IOException
{
if (!_streamWriteContext.inArray()) {
_reportError("Current context not Array but "+_streamWriteContext.typeDesc());
}
_writeByte(TOKEN_LITERAL_END_ARRAY);
_streamWriteContext = _streamWriteContext.getParent();
}
@Override
public final void writeStartObject() throws IOException
{
_verifyValueWrite("start an object");
_streamWriteContext = _streamWriteContext.createChildObjectContext(null);
_writeByte(TOKEN_LITERAL_START_OBJECT);
}
@Override // since 2.8
public final void writeStartObject(Object forValue) throws IOException
{
_verifyValueWrite("start an object");
SmileWriteContext ctxt = _streamWriteContext.createChildObjectContext(forValue);
_streamWriteContext = ctxt;
_writeByte(TOKEN_LITERAL_START_OBJECT);
}
@Override
public final void writeEndObject() throws IOException
{
if (!_streamWriteContext.inObject()) {
_reportError("Current context not Object but "+_streamWriteContext.typeDesc());
}
_streamWriteContext = _streamWriteContext.getParent();
_writeByte(TOKEN_LITERAL_END_OBJECT);
}
@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");
_writeByte(TOKEN_LITERAL_START_ARRAY);
int ptr = _outputTail;
final int outputEnd = _outputEnd;
for (int i = offset, end = offset+length; i < end; ++i) {
// TODO: optimize boundary checks for common case
if ((ptr + 6) >= outputEnd) { // at most 6 bytes per element
_outputTail = ptr;
_flushBuffer();
ptr = _outputTail;
}
ptr = _writeNumberNoChecks(ptr, array[i]);
}
_outputTail = ptr;
_writeByte(TOKEN_LITERAL_END_ARRAY);
}
@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");
_writeByte(TOKEN_LITERAL_START_ARRAY);
int ptr = _outputTail;
final int outputEnd = _outputEnd;
for (int i = offset, end = offset+length; i < end; ++i) {
if ((ptr + 11) >= outputEnd) { // at most 11 bytes per element
_outputTail = ptr;
_flushBuffer();
ptr = _outputTail;
}
ptr = _writeNumberNoChecks(ptr, array[i]);
}
_outputTail = ptr;
_writeByte(TOKEN_LITERAL_END_ARRAY);
}
@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");
_writeByte(TOKEN_LITERAL_START_ARRAY);
int ptr = _outputTail;
final int outputEnd = _outputEnd;
for (int i = offset, end = offset+length; i < end; ++i) {
if ((ptr + 10) >= outputEnd) { // at most 11 bytes per element
_outputTail = ptr;
_flushBuffer();
ptr = _outputTail;
}
ptr = _writeNumberNoChecks(ptr, array[i]);
}
_outputTail = ptr;
_writeByte(TOKEN_LITERAL_END_ARRAY);
}
private final void _writeFieldName(String name) throws IOException
{
int len = name.length();
if (len == 0) {
_writeByte(TOKEN_KEY_EMPTY_STRING);
return;
}
// First: is it something we can share?
if (_seenNameCount >= 0) {
int ix = _findSeenName(name);
if (ix >= 0) {
_writeSharedNameReference(ix);
return;
}
}
if (len > MAX_SHORT_NAME_ANY_BYTES) { // can not be a 'short' String; off-line (rare case)
_writeNonShortFieldName(name, len);
return;
}
// first: ensure we have enough space
if ((_outputTail + MIN_BUFFER_FOR_POSSIBLE_SHORT_STRING) >= _outputEnd) {
_flushBuffer();
}
// then let's copy String chars to char buffer, faster than using getChar (measured, profiled)
int origOffset = _outputTail;
++_outputTail; // to reserve space for type token
int byteLen = _shortUTF8Encode(name, 0, len);
byte typeToken;
// ASCII?
if (byteLen == len) {
if (byteLen <= MAX_SHORT_NAME_ASCII_BYTES) { // yes, is short indeed
typeToken = (byte) ((TOKEN_PREFIX_KEY_ASCII - 1) + byteLen);
} else { // longer albeit ASCII
typeToken = TOKEN_KEY_LONG_STRING;
// and we will need String end marker byte
_outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
}
} else { // not all ASCII
if (byteLen <= MAX_SHORT_NAME_UNICODE_BYTES) { // yes, is short indeed
// note: since 2 is smaller allowed length, offset differs from one used for
typeToken = (byte) ((TOKEN_PREFIX_KEY_UNICODE - 2) + byteLen);
} else { // nope, longer non-ASCII Strings
typeToken = TOKEN_KEY_LONG_STRING;
// and we will need String end marker byte
_outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
}
}
// and then sneak in type token now that know the details
_outputBuffer[origOffset] = typeToken;
// Also, keep track if we can use back-references (shared names)
if (_seenNameCount >= 0) {
_addSeenName(name);
}
}
private final void _writeNonShortFieldName(final String name, final int len) throws IOException
{
_writeByte(TOKEN_KEY_LONG_STRING);
// can we still make a temp copy?
// but will encoded version fit in buffer?
int maxLen = len + len + len;
if (maxLen <= _outputBuffer.length) { // yes indeed
if ((_outputTail + maxLen) >= _outputEnd) {
_flushBuffer();
}
_shortUTF8Encode(name, 0, len);
} else { // nope, need bit slower variant
_mediumUTF8Encode(name, 0, len);
}
if (_seenNameCount >= 0) {
_addSeenName(name);
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
}
protected final void _writeFieldName(SerializableString name) throws IOException
{
final int charLen = name.charLength();
if (charLen == 0) {
_writeByte(TOKEN_KEY_EMPTY_STRING);
return;
}
// Then: is it something we can share?
if (_seenNameCount >= 0) {
int ix = _findSeenName(name.getValue());
if (ix >= 0) {
_writeSharedNameReference(ix);
return;
}
}
final byte[] bytes = name.asUnquotedUTF8();
final int byteLen = bytes.length;
if (byteLen != charLen) {
_writeFieldNameUnicode(name, bytes);
return;
}
// Common case: short ASCII name that fits in buffer as is
if (byteLen <= MAX_SHORT_NAME_ASCII_BYTES) {
// output buffer is bigger than what we need, always, so
if ((_outputTail + byteLen) >= _outputEnd) { // need marker byte and actual bytes
_flushBuffer();
}
_outputBuffer[_outputTail++] = (byte) ((TOKEN_PREFIX_KEY_ASCII - 1) + byteLen);
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
_outputTail += byteLen;
} else {
_writeLongAsciiFieldName(bytes);
}
// Also, keep track if we can use back-references (shared names)
if (_seenNameCount >= 0) {
_addSeenName(name.getValue());
}
}
private final void _writeLongAsciiFieldName(byte[] bytes)
throws IOException
{
final int byteLen = bytes.length;
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = TOKEN_KEY_LONG_STRING;
// Ok. Enough room?
if ((_outputTail + byteLen + 1) < _outputEnd) {
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
_outputTail += byteLen;
} else {
_flushBuffer();
// either way, do intermediate copy if name is relatively short
// Need to copy?
if (byteLen < MIN_BUFFER_LENGTH) {
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
_outputTail += byteLen;
} else {
// otherwise, just write as is
if (_outputTail > 0) {
_flushBuffer();
}
_out.write(bytes, 0, byteLen);
}
}
_outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
}
protected final void _writeFieldNameUnicode(SerializableString name, byte[] bytes)
throws IOException
{
final int byteLen = bytes.length;
// Common case: short Unicode name that fits in output buffer
if (byteLen <= MAX_SHORT_NAME_UNICODE_BYTES) {
if ((_outputTail + byteLen) >= _outputEnd) { // need marker byte and actual bytes
_flushBuffer();
}
// note: since 2 is smaller allowed length, offset differs from one used for
_outputBuffer[_outputTail++] = (byte) ((TOKEN_PREFIX_KEY_UNICODE - 2) + byteLen);
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
_outputTail += byteLen;
// Also, keep track if we can use back-references (shared names)
if (_seenNameCount >= 0) {
_addSeenName(name.getValue());
}
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = TOKEN_KEY_LONG_STRING;
// Ok. Enough room?
if ((_outputTail + byteLen + 1) < _outputEnd) {
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
_outputTail += byteLen;
} else {
_flushBuffer();
// either way, do intermediate copy if name is relatively short
// Need to copy?
if (byteLen < MIN_BUFFER_LENGTH) {
System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
_outputTail += byteLen;
} else {
// otherwise, just write as is
if (_outputTail > 0) {
_flushBuffer();
}
_out.write(bytes, 0, byteLen);
}
}
_outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
// Also, keep track if we can use back-references (shared names)
if (_seenNameCount >= 0) {
_addSeenName(name.getValue());
}
}
private final void _writeSharedNameReference(int ix)
throws IOException
{
// 03-Mar-2011, tatu: Related to [JACKSON-525], let's add a sanity check here
if (ix >= _seenNameCount) {
throw new IllegalArgumentException("Internal error: trying to write shared name with index "+ix
+"; but have only seen "+_seenNameCount+" so far!");
}
if (ix < 64) {
_writeByte((byte) (TOKEN_PREFIX_KEY_SHARED_SHORT + ix));
} else {
_writeBytes(((byte) (TOKEN_PREFIX_KEY_SHARED_LONG + (ix >> 8))), (byte) ix);
}
}
/*
/**********************************************************
/* Output method implementations, textual
/**********************************************************
*/
@Override
public void writeString(String text) throws IOException
{
if (text == null) {
writeNull();
return;
}
_verifyValueWrite("write String value");
int len = text.length();
if (len == 0) {
_writeByte(TOKEN_LITERAL_EMPTY_STRING);
return;
}
// Longer string handling off-lined