Debian Codegraph @

src/main/java/com/fasterxml/jackson/dataformat/smile/SmileGenerator.java

raw
1 package com.fasterxml.jackson.dataformat.smile;
2
3 import java.io.*;
4 import java.lang.ref.SoftReference;
5 import java.math.BigDecimal;
6 import java.math.BigInteger;
7 import java.util.Arrays;
8
9 import com.fasterxml.jackson.core.*;
10 import com.fasterxml.jackson.core.io.*;
11 import com.fasterxml.jackson.core.json.JsonWriteContext;
12 import com.fasterxml.jackson.core.base.GeneratorBase;
13
14 import static com.fasterxml.jackson.dataformat.smile.SmileConstants.*;
15
16 /**
17 * {@link JsonGenerator} implementation for Smile-encoded content
18 * (see <a href="http://wiki.fasterxml.com/SmileFormatSpec">Smile Format Specification</a>)
19 *
20 * @author tatu
21 */
22 public class SmileGenerator
23 extends GeneratorBase
24 {
25 /**
26 * Enumeration that defines all togglable features for Smile generators.
27 */
28 public enum Feature
29 implements FormatFeature // since 2.7
30 {
31 /**
32 * Whether to write 4-byte header sequence when starting output or not.
33 * If disabled, no header is written; this may be useful in embedded cases
34 * where context is enough to know that content is encoded using this format.
35 * Note, however, that omitting header means that default settings for
36 * shared names/string values can not be changed.
37 *<p>
38 * Default setting is true, meaning that header will be written.
39 */
40 WRITE_HEADER(true),
41
42 /**
43 * Whether write byte marker that signifies end of logical content segment
44 * ({@link SmileConstants#BYTE_MARKER_END_OF_CONTENT}) when
45 * {@link #close} is called or not. This can be useful when outputting
46 * multiple adjacent logical content segments (documents) into single
47 * physical output unit (file).
48 *<p>
49 * Default setting is false meaning that such marker is not written.
50 */
51 WRITE_END_MARKER(false),
52
53 /**
54 * Whether to use simple 7-bit per byte encoding for binary content when output.
55 * This is necessary ensure that byte 0xFF will never be included in content output.
56 * For other data types this limitation is handled automatically. This setting is enabled
57 * by default, however, overhead for binary data (14% size expansion, processing overhead)
58 * is non-negligible. If no binary data is output, feature has no effect.
59 *<p>
60 * Default setting is true, indicating that binary data is quoted as 7-bit bytes
61 * instead of written raw.
62 */
63 ENCODE_BINARY_AS_7BIT(true),
64
65 /**
66 * Whether generator should check if it can "share" field names during generating
67 * content or not. If enabled, can replace repeating field names with back references,
68 * which are more compact and should faster to decode. Downside is that there is some
69 * overhead for writing (need to track existing values, check), as well as decoding.
70 *<p>
71 * Since field names tend to repeat quite often, this setting is enabled by default.
72 */
73 CHECK_SHARED_NAMES(true),
74
75 /**
76 * Whether generator should check if it can "share" short (at most 64 bytes encoded)
77 * String value during generating
78 * content or not. If enabled, can replace repeating Short String values with back references,
79 * which are more compact and should faster to decode. Downside is that there is some
80 * overhead for writing (need to track existing values, check), as well as decoding.
81 *<p>
82 * Since efficiency of this option depends a lot on type of content being produced,
83 * this option is disabled by default, and should only be enabled if it is likely that
84 * same values repeat relatively often.
85 */
86 CHECK_SHARED_STRING_VALUES(false)
87 ;
88
89 protected final boolean _defaultState;
90 protected final int _mask;
91
92 /**
93 * Method that calculates bit set (flags) of all features that
94 * are enabled by default.
95 */
96 public static int collectDefaults()
97 {
98 int flags = 0;
99 for (Feature f : values()) {
100 if (f.enabledByDefault()) {
101 flags |= f.getMask();
102 }
103 }
104 return flags;
105 }
106
107 private Feature(boolean defaultState) {
108 _defaultState = defaultState;
109 _mask = (1 << ordinal());
110 }
111
112 @Override public boolean enabledByDefault() { return _defaultState; }
113 @Override public int getMask() { return _mask; }
114 @Override public boolean enabledIn(int flags) { return (flags & _mask) != 0; }
115 }
116
117 /**
118 * Helper class used for keeping track of possibly shareable String
119 * references (for field names and/or short String values)
120 */
121 protected final static class SharedStringNode
122 {
123 public final String value;
124 public final int index;
125 public SharedStringNode next;
126
127 public SharedStringNode(String value, int index, SharedStringNode next)
128 {
129 this.value = value;
130 this.index = index;
131 this.next = next;
132 }
133 }
134
135 /**
136 * To simplify certain operations, we require output buffer length
137 * to allow outputting of contiguous 256 character UTF-8 encoded String
138 * value. Length of the longest UTF-8 code point (from Java char) is 3 bytes,
139 * and we need both initial token byte and single-byte end marker
140 * so we get following value.
141 *<p>
142 * Note: actually we could live with shorter one; absolute minimum would
143 * be for encoding 64-character Strings.
144 */
145 private final static int MIN_BUFFER_LENGTH = (3 * 256) + 2;
146
147 protected final static byte TOKEN_BYTE_LONG_STRING_ASCII = TOKEN_MISC_LONG_TEXT_ASCII;
148
149 protected final static byte TOKEN_BYTE_INT_32 = (byte) (SmileConstants.TOKEN_PREFIX_INTEGER + TOKEN_MISC_INTEGER_32);
150 protected final static byte TOKEN_BYTE_INT_64 = (byte) (SmileConstants.TOKEN_PREFIX_INTEGER + TOKEN_MISC_INTEGER_64);
151 protected final static byte TOKEN_BYTE_BIG_INTEGER = (byte) (SmileConstants.TOKEN_PREFIX_INTEGER + TOKEN_MISC_INTEGER_BIG);
152
153 protected final static byte TOKEN_BYTE_FLOAT_32 = (byte) (SmileConstants.TOKEN_PREFIX_FP | TOKEN_MISC_FLOAT_32);
154 protected final static byte TOKEN_BYTE_FLOAT_64 = (byte) (SmileConstants.TOKEN_PREFIX_FP | TOKEN_MISC_FLOAT_64);
155 protected final static byte TOKEN_BYTE_BIG_DECIMAL = (byte) (SmileConstants.TOKEN_PREFIX_FP | TOKEN_MISC_FLOAT_BIG);
156
157 protected final static long MIN_INT_AS_LONG = (long) Integer.MIN_VALUE;
158 protected final static long MAX_INT_AS_LONG = (long) Integer.MAX_VALUE;
159
160 /*
161 /**********************************************************
162 /* Configuration
163 /**********************************************************
164 */
165
166 final protected IOContext _ioContext;
167
168 final protected OutputStream _out;
169
170 /**
171 * Bit flag composed of bits that indicate which
172 * {@link com.fasterxml.jackson.dataformat.smile.SmileGenerator.Feature}s
173 * are enabled.
174 */
175 protected int _formatFeatures;
176
177 /**
178 * Helper object used for low-level recycling of Smile-generator
179 * specific buffers.
180 */
181 final protected SmileBufferRecycler<SharedStringNode> _smileBufferRecycler;
182
183 /*
184 /**********************************************************
185 /* Output buffering
186 /**********************************************************
187 */
188
189 /**
190 * Intermediate buffer in which contents are buffered before
191 * being written using {@link #_out}.
192 */
193 protected byte[] _outputBuffer;
194
195 /**
196 * Pointer to the next available byte in {@link #_outputBuffer}
197 */
198 protected int _outputTail = 0;
199
200 /**
201 * Offset to index after the last valid index in {@link #_outputBuffer}.
202 * Typically same as length of the buffer.
203 */
204 protected final int _outputEnd;
205
206 /**
207 * Let's keep track of how many bytes have been output, may prove useful
208 * when debugging. This does <b>not</b> include bytes buffered in
209 * the output buffer, just bytes that have been written using underlying
210 * stream writer.
211 */
212 protected int _bytesWritten;
213
214 /*
215 /**********************************************************
216 /* Shared String detection
217 /**********************************************************
218 */
219
220 /**
221 * Raw data structure used for checking whether field name to
222 * write can be output using back reference or not.
223 */
224 protected SharedStringNode[] _seenNames;
225
226 /**
227 * Number of entries in {@link #_seenNames}; -1 if no shared name
228 * detection is enabled
229 */
230 protected int _seenNameCount;
231
232 /**
233 * Raw data structure used for checking whether String value to
234 * write can be output using back reference or not.
235 */
236 protected SharedStringNode[] _seenStringValues;
237
238 /**
239 * Number of entries in {@link #_seenStringValues}; -1 if no shared text value
240 * detection is enabled
241 */
242 protected int _seenStringValueCount;
243
244 /**
245 * Flag that indicates whether the output buffer is recycable (and
246 * needs to be returned to recycler once we are done) or not.
247 */
248 protected boolean _bufferRecyclable;
249
250 /*
251 /**********************************************************
252 /* Thread-local recycling
253 /**********************************************************
254 */
255
256 /**
257 * This <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference}
258 * to a buffer recycler used to provide a low-cost
259 * buffer recycling for Smile-specific buffers.
260 */
261 final protected static ThreadLocal<SoftReference<SmileBufferRecycler<SharedStringNode>>> _smileRecyclerRef
262 = new ThreadLocal<SoftReference<SmileBufferRecycler<SharedStringNode>>>();
263
264 /*
265 /**********************************************************
266 /* Life-cycle
267 /**********************************************************
268 */
269
270 public SmileGenerator(IOContext ctxt, int jsonFeatures, int smileFeatures,
271 ObjectCodec codec, OutputStream out)
272 {
273 super(jsonFeatures, codec);
274 _formatFeatures = smileFeatures;
275 _ioContext = ctxt;
276 _smileBufferRecycler = _smileBufferRecycler();
277 _out = out;
278 _bufferRecyclable = true;
279 _outputBuffer = ctxt.allocWriteEncodingBuffer();
280 _outputEnd = _outputBuffer.length;
281 // let's just sanity check to prevent nasty odd errors
282 if (_outputEnd < MIN_BUFFER_LENGTH) {
283 throw new IllegalStateException("Internal encoding buffer length ("+_outputEnd
284 +") too short, must be at least "+MIN_BUFFER_LENGTH);
285 }
286 if ((smileFeatures & Feature.CHECK_SHARED_NAMES.getMask()) == 0) {
287 _seenNames = null;
288 _seenNameCount = -1;
289 } else {
290 _seenNames = _smileBufferRecycler.allocSeenNamesBuffer();
291 if (_seenNames == null) {
292 _seenNames = new SharedStringNode[SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH];
293 }
294 _seenNameCount = 0;
295 }
296
297 if ((smileFeatures & Feature.CHECK_SHARED_STRING_VALUES.getMask()) == 0) {
298 _seenStringValues = null;
299 _seenStringValueCount = -1;
300 } else {
301 _seenStringValues = _smileBufferRecycler.allocSeenStringValuesBuffer();
302 if (_seenStringValues == null) {
303 _seenStringValues = new SharedStringNode[SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH];
304 }
305 _seenStringValueCount = 0;
306 }
307 }
308
309 public SmileGenerator(IOContext ctxt, int jsonFeatures, int smileFeatures,
310 ObjectCodec codec, OutputStream out, byte[] outputBuffer, int offset, boolean bufferRecyclable)
311 {
312 super(jsonFeatures, codec);
313 _formatFeatures = smileFeatures;
314 _ioContext = ctxt;
315 _smileBufferRecycler = _smileBufferRecycler();
316 _out = out;
317 _bufferRecyclable = bufferRecyclable;
318 _outputTail = offset;
319 _outputBuffer = outputBuffer;
320 _outputEnd = _outputBuffer.length;
321 // let's just sanity check to prevent nasty odd errors
322 if (_outputEnd < MIN_BUFFER_LENGTH) {
323 throw new IllegalStateException("Internal encoding buffer length ("+_outputEnd
324 +") too short, must be at least "+MIN_BUFFER_LENGTH);
325 }
326 if ((smileFeatures & Feature.CHECK_SHARED_NAMES.getMask()) == 0) {
327 _seenNames = null;
328 _seenNameCount = -1;
329 } else {
330 _seenNames = _smileBufferRecycler.allocSeenNamesBuffer();
331 if (_seenNames == null) {
332 _seenNames = new SharedStringNode[SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH];
333 }
334 _seenNameCount = 0;
335 }
336
337 if ((smileFeatures & Feature.CHECK_SHARED_STRING_VALUES.getMask()) == 0) {
338 _seenStringValues = null;
339 _seenStringValueCount = -1;
340 } else {
341 _seenStringValues = _smileBufferRecycler.allocSeenStringValuesBuffer();
342 if (_seenStringValues == null) {
343 _seenStringValues = new SharedStringNode[SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH];
344 }
345 _seenStringValueCount = 0;
346 }
347 }
348
349 /**
350 * Method that can be called to explicitly write Smile document header.
351 * Note that usually you do not need to call this for first document to output,
352 * but rather only if you intend to write multiple root-level documents
353 * with same generator (and even in that case this is optional thing to do).
354 * As a result usually only {@link SmileFactory} calls this method.
355 */
356 public void writeHeader() throws IOException
357 {
358 int last = HEADER_BYTE_4;
359 if (Feature.CHECK_SHARED_NAMES.enabledIn(_formatFeatures)) {
360 last |= SmileConstants.HEADER_BIT_HAS_SHARED_NAMES;
361 }
362 if (Feature.CHECK_SHARED_STRING_VALUES.enabledIn(_formatFeatures)) {
363 last |= SmileConstants.HEADER_BIT_HAS_SHARED_STRING_VALUES;
364 }
365 if (!Feature.ENCODE_BINARY_AS_7BIT.enabledIn(_formatFeatures)) {
366 last |= SmileConstants.HEADER_BIT_HAS_RAW_BINARY;
367 }
368 _writeBytes(HEADER_BYTE_1, HEADER_BYTE_2, HEADER_BYTE_3, (byte) last);
369 }
370
371 protected final static SmileBufferRecycler<SharedStringNode> _smileBufferRecycler()
372 {
373 SoftReference<SmileBufferRecycler<SharedStringNode>> ref = _smileRecyclerRef.get();
374 SmileBufferRecycler<SharedStringNode> br = (ref == null) ? null : ref.get();
375
376 if (br == null) {
377 br = new SmileBufferRecycler<SharedStringNode>();
378 _smileRecyclerRef.set(new SoftReference<SmileBufferRecycler<SharedStringNode>>(br));
379 }
380 return br;
381 }
382
383 /*
384 /**********************************************************
385 /* Versioned
386 /**********************************************************
387 */
388
389 @Override
390 public Version version() {
391 return PackageVersion.VERSION;
392 }
393
394 /*
395 /**********************************************************
396 /* Capability introspection
397 /**********************************************************
398 */
399
400 @Override
401 public boolean canWriteBinaryNatively() {
402 return true;
403 }
404
405 /*
406 /**********************************************************
407 /* Overridden methods, configuration
408 /**********************************************************
409 */
410
411 /**
412 * No way (or need) to indent anything, so let's block any attempts.
413 * (should we throw an exception instead?)
414 */
415 @Override
416 public JsonGenerator useDefaultPrettyPrinter()
417 {
418 return this;
419 }
420
421 /**
422 * No way (or need) to indent anything, so let's block any attempts.
423 * (should we throw an exception instead?)
424 */
425 @Override
426 public JsonGenerator setPrettyPrinter(PrettyPrinter pp) {
427 return this;
428 }
429
430 @Override
431 public Object getOutputTarget() {
432 return _out;
433 }
434
435 @Override
436 public int getOutputBuffered() {
437 return _outputTail;
438 }
439
440 // public JsonParser overrideStdFeatures(int values, int mask)
441
442 @Override
443 public int getFormatFeatures() {
444 return _formatFeatures;
445 }
446
447 @Override
448 public JsonGenerator overrideFormatFeatures(int values, int mask) {
449 _formatFeatures = (_formatFeatures & ~mask) | (values & mask);
450 return this;
451 }
452
453 /*
454 /**********************************************************
455 /* Overridden methods, write methods
456 /**********************************************************
457 */
458
459 /* And then methods overridden to make final, streamline some
460 * aspects...
461 */
462
463 @Override
464 public final void writeFieldName(String name) throws IOException, JsonGenerationException
465 {
466 if (_writeContext.writeFieldName(name) == JsonWriteContext.STATUS_EXPECT_VALUE) {
467 _reportError("Can not write a field name, expecting a value");
468 }
469 _writeFieldName(name);
470 }
471
472 @Override
473 public final void writeFieldName(SerializableString name)
474 throws IOException, JsonGenerationException
475 {
476 // Object is a value, need to verify it's allowed
477 if (_writeContext.writeFieldName(name.getValue()) == JsonWriteContext.STATUS_EXPECT_VALUE) {
478 _reportError("Can not write a field name, expecting a value");
479 }
480 _writeFieldName(name);
481 }
482
483 @Override
484 public final void writeStringField(String fieldName, String value)
485 throws IOException, JsonGenerationException
486 {
487 if (_writeContext.writeFieldName(fieldName) == JsonWriteContext.STATUS_EXPECT_VALUE) {
488 _reportError("Can not write a field name, expecting a value");
489 }
490 _writeFieldName(fieldName);
491 writeString(value);
492 }
493
494 /*
495 /**********************************************************
496 /* Extended API, configuration
497 /**********************************************************
498 */
499
500 public SmileGenerator enable(Feature f) {
501 _formatFeatures |= f.getMask();
502 return this;
503 }
504
505 public SmileGenerator disable(Feature f) {
506 _formatFeatures &= ~f.getMask();
507 return this;
508 }
509
510 public final boolean isEnabled(Feature f) {
511 return (_formatFeatures & f.getMask()) != 0;
512 }
513
514 public SmileGenerator configure(Feature f, boolean state) {
515 if (state) {
516 enable(f);
517 } else {
518 disable(f);
519 }
520 return this;
521 }
522
523 /*
524 /**********************************************************
525 /* Extended API, other
526 /**********************************************************
527 */
528
529 /**
530 * Method for directly inserting specified byte in output at
531 * current position.
532 *<p>
533 * NOTE: only use this method if you really know what you are doing.
534 */
535 public void writeRaw(byte b) throws IOException, JsonGenerationException
536 {
537 /* 08-Jan-2014, tatu: Should we just rather throw an exception? For now,
538 * allow... maybe have a feature to cause an exception.
539 */
540 _writeByte(b);
541 }
542
543 /**
544 * Method for directly inserting specified bytes in output at
545 * current position.
546 *<p>
547 * NOTE: only use this method if you really know what you are doing.
548 */
549 public void writeBytes(byte[] data, int offset, int len) throws IOException
550 {
551 _writeBytes(data, offset, len);
552 }
553
554 /*
555 /**********************************************************
556 /* Output method implementations, structural
557 /**********************************************************
558 */
559
560 @Override
561 public final void writeStartArray() throws IOException, JsonGenerationException
562 {
563 _verifyValueWrite("start an array");
564 _writeContext = _writeContext.createChildArrayContext();
565 _writeByte(TOKEN_LITERAL_START_ARRAY);
566 }
567
568 @Override // defined since 2.6.3
569 public final void writeStartArray(int size) throws IOException, JsonGenerationException
570 {
571 _verifyValueWrite("start an array");
572 _writeContext = _writeContext.createChildArrayContext();
573 _writeByte(TOKEN_LITERAL_START_ARRAY);
574 }
575
576 @Override
577 public final void writeEndArray() throws IOException, JsonGenerationException
578 {
579 if (!_writeContext.inArray()) {
580 _reportError("Current context not an ARRAY but "+_writeContext.getTypeDesc());
581 }
582 _writeByte(TOKEN_LITERAL_END_ARRAY);
583 _writeContext = _writeContext.getParent();
584 }
585
586 @Override
587 public final void writeStartObject() throws IOException, JsonGenerationException
588 {
589 _verifyValueWrite("start an object");
590 _writeContext = _writeContext.createChildObjectContext();
591 _writeByte(TOKEN_LITERAL_START_OBJECT);
592 }
593
594 @Override
595 public final void writeEndObject() throws IOException, JsonGenerationException
596 {
597 if (!_writeContext.inObject()) {
598 _reportError("Current context not an object but "+_writeContext.getTypeDesc());
599 }
600 _writeContext = _writeContext.getParent();
601 _writeByte(TOKEN_LITERAL_END_OBJECT);
602 }
603
604 private final void _writeFieldName(String name) throws IOException
605 {
606 int len = name.length();
607 if (len == 0) {
608 _writeByte(TOKEN_KEY_EMPTY_STRING);
609 return;
610 }
611 // First: is it something we can share?
612 if (_seenNameCount >= 0) {
613 int ix = _findSeenName(name);
614 if (ix >= 0) {
615 _writeSharedNameReference(ix);
616 return;
617 }
618 }
619 if (len > MAX_SHORT_NAME_ANY_BYTES) { // can not be a 'short' String; off-line (rare case)
620 _writeNonShortFieldName(name, len);
621 return;
622 }
623
624 // first: ensure we have enough space
625 if ((_outputTail + MIN_BUFFER_FOR_POSSIBLE_SHORT_STRING) >= _outputEnd) {
626 _flushBuffer();
627 }
628 // then let's copy String chars to char buffer, faster than using getChar (measured, profiled)
629 int origOffset = _outputTail;
630 ++_outputTail; // to reserve space for type token
631 int byteLen = _shortUTF8Encode(name, 0, len);
632 byte typeToken;
633
634 // ASCII?
635 if (byteLen == len) {
636 if (byteLen <= MAX_SHORT_NAME_ASCII_BYTES) { // yes, is short indeed
637 typeToken = (byte) ((TOKEN_PREFIX_KEY_ASCII - 1) + byteLen);
638 } else { // longer albeit ASCII
639 typeToken = TOKEN_KEY_LONG_STRING;
640 // and we will need String end marker byte
641 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
642 }
643 } else { // not all ASCII
644 if (byteLen <= MAX_SHORT_NAME_UNICODE_BYTES) { // yes, is short indeed
645 // note: since 2 is smaller allowed length, offset differs from one used for
646 typeToken = (byte) ((TOKEN_PREFIX_KEY_UNICODE - 2) + byteLen);
647 } else { // nope, longer non-ASCII Strings
648 typeToken = TOKEN_KEY_LONG_STRING;
649 // and we will need String end marker byte
650 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
651 }
652 }
653 // and then sneak in type token now that know the details
654 _outputBuffer[origOffset] = typeToken;
655 // Also, keep track if we can use back-references (shared names)
656 if (_seenNameCount >= 0) {
657 _addSeenName(name);
658 }
659 }
660
661 private final void _writeNonShortFieldName(final String name, final int len) throws IOException
662 {
663 _writeByte(TOKEN_KEY_LONG_STRING);
664 // can we still make a temp copy?
665 // but will encoded version fit in buffer?
666 int maxLen = len + len + len;
667 if (maxLen <= _outputBuffer.length) { // yes indeed
668 if ((_outputTail + maxLen) >= _outputEnd) {
669 _flushBuffer();
670 }
671 _shortUTF8Encode(name, 0, len);
672 } else { // nope, need bit slower variant
673 _mediumUTF8Encode(name, 0, len);
674 }
675 if (_seenNameCount >= 0) {
676 _addSeenName(name);
677 }
678 if (_outputTail >= _outputEnd) {
679 _flushBuffer();
680 }
681 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
682 }
683
684 protected final void _writeFieldName(SerializableString name) throws IOException
685 {
686 final int charLen = name.charLength();
687 if (charLen == 0) {
688 _writeByte(TOKEN_KEY_EMPTY_STRING);
689 return;
690 }
691 // Then: is it something we can share?
692 if (_seenNameCount >= 0) {
693 int ix = _findSeenName(name.getValue());
694 if (ix >= 0) {
695 _writeSharedNameReference(ix);
696 return;
697 }
698 }
699 final byte[] bytes = name.asUnquotedUTF8();
700 final int byteLen = bytes.length;
701 if (byteLen != charLen) {
702 _writeFieldNameUnicode(name, bytes);
703 return;
704 }
705 // Common case: short ASCII name that fits in buffer as is
706 if (byteLen <= MAX_SHORT_NAME_ASCII_BYTES) {
707 // output buffer is bigger than what we need, always, so
708 if ((_outputTail + byteLen) >= _outputEnd) { // need marker byte and actual bytes
709 _flushBuffer();
710 }
711 _outputBuffer[_outputTail++] = (byte) ((TOKEN_PREFIX_KEY_ASCII - 1) + byteLen);
712 System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
713 _outputTail += byteLen;
714 } else {
715 _writeLongAsciiFieldName(bytes);
716 }
717 // Also, keep track if we can use back-references (shared names)
718 if (_seenNameCount >= 0) {
719 _addSeenName(name.getValue());
720 }
721 }
722
723 private final void _writeLongAsciiFieldName(byte[] bytes)
724 throws IOException, JsonGenerationException
725 {
726 final int byteLen = bytes.length;
727 if (_outputTail >= _outputEnd) {
728 _flushBuffer();
729 }
730 _outputBuffer[_outputTail++] = TOKEN_KEY_LONG_STRING;
731 // Ok. Enough room?
732 if ((_outputTail + byteLen + 1) < _outputEnd) {
733 System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
734 _outputTail += byteLen;
735 } else {
736 _flushBuffer();
737 // either way, do intermediate copy if name is relatively short
738 // Need to copy?
739 if (byteLen < MIN_BUFFER_LENGTH) {
740 System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
741 _outputTail += byteLen;
742 } else {
743 // otherwise, just write as is
744 if (_outputTail > 0) {
745 _flushBuffer();
746 }
747 _out.write(bytes, 0, byteLen);
748 }
749 }
750 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
751 }
752
753 protected final void _writeFieldNameUnicode(SerializableString name, byte[] bytes)
754 throws IOException
755 {
756 final int byteLen = bytes.length;
757
758 // Common case: short Unicode name that fits in output buffer
759 if (byteLen <= MAX_SHORT_NAME_UNICODE_BYTES) {
760 if ((_outputTail + byteLen) >= _outputEnd) { // need marker byte and actual bytes
761 _flushBuffer();
762 }
763 // note: since 2 is smaller allowed length, offset differs from one used for
764 _outputBuffer[_outputTail++] = (byte) ((TOKEN_PREFIX_KEY_UNICODE - 2) + byteLen);
765
766 System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
767 _outputTail += byteLen;
768 // Also, keep track if we can use back-references (shared names)
769 if (_seenNameCount >= 0) {
770 _addSeenName(name.getValue());
771 }
772 return;
773 }
774 if (_outputTail >= _outputEnd) {
775 _flushBuffer();
776 }
777 _outputBuffer[_outputTail++] = TOKEN_KEY_LONG_STRING;
778 // Ok. Enough room?
779 if ((_outputTail + byteLen + 1) < _outputEnd) {
780 System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
781 _outputTail += byteLen;
782 } else {
783 _flushBuffer();
784 // either way, do intermediate copy if name is relatively short
785 // Need to copy?
786 if (byteLen < MIN_BUFFER_LENGTH) {
787 System.arraycopy(bytes, 0, _outputBuffer, _outputTail, byteLen);
788 _outputTail += byteLen;
789 } else {
790 // otherwise, just write as is
791 if (_outputTail > 0) {
792 _flushBuffer();
793 }
794 _out.write(bytes, 0, byteLen);
795 }
796 }
797 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
798 // Also, keep track if we can use back-references (shared names)
799 if (_seenNameCount >= 0) {
800 _addSeenName(name.getValue());
801 }
802 }
803
804 private final void _writeSharedNameReference(int ix)
805 throws IOException
806 {
807 // 03-Mar-2011, tatu: Related to [JACKSON-525], let's add a sanity check here
808 if (ix >= _seenNameCount) {
809 throw new IllegalArgumentException("Internal error: trying to write shared name with index "+ix
810 +"; but have only seen "+_seenNameCount+" so far!");
811 }
812 if (ix < 64) {
813 _writeByte((byte) (TOKEN_PREFIX_KEY_SHARED_SHORT + ix));
814 } else {
815 _writeBytes(((byte) (TOKEN_PREFIX_KEY_SHARED_LONG + (ix >> 8))), (byte) ix);
816 }
817 }
818
819 /*
820 /**********************************************************
821 /* Output method implementations, textual
822 /**********************************************************
823 */
824
825 @Override
826 public void writeString(String text) throws IOException
827 {
828 if (text == null) {
829 writeNull();
830 return;
831 }
832 _verifyValueWrite("write String value");
833 int len = text.length();
834 if (len == 0) {
835 _writeByte(TOKEN_LITERAL_EMPTY_STRING);
836 return;
837 }
838 // Longer string handling off-lined
839 if (len > MAX_SHARED_STRING_LENGTH_BYTES) {
840 _writeNonSharedString(text, len);
841 return;
842 }
843 // Then: is it something we can share?
844 if (_seenStringValueCount >= 0) {
845 int ix = _findSeenStringValue(text);
846 if (ix >= 0) {
847 _writeSharedStringValueReference(ix);
848 return;
849 }
850 }
851
852 // possibly short string (but not necessarily)
853 // first: ensure we have enough space
854 if ((_outputTail + MIN_BUFFER_FOR_POSSIBLE_SHORT_STRING) >= _outputEnd) {
855 _flushBuffer();
856 }
857 // then let's copy String chars to char buffer, faster than using getChar (measured, profiled)
858 int origOffset = _outputTail;
859 ++_outputTail; // to leave room for type token
860 int byteLen = _shortUTF8Encode(text, 0, len);
861 if (byteLen <= MAX_SHORT_VALUE_STRING_BYTES) { // yes, is short indeed
862 // plus keep reference, if it could be shared:
863 if (_seenStringValueCount >= 0) {
864 _addSeenStringValue(text);
865 }
866 if (byteLen == len) { // and all ASCII
867 _outputBuffer[origOffset] = (byte) ((TOKEN_PREFIX_TINY_ASCII - 1) + byteLen);
868 } else { // not just ASCII
869 // note: since length 1 can not be used here, value range is offset by 2, not 1
870 _outputBuffer[origOffset] = (byte) ((TOKEN_PREFIX_TINY_UNICODE - 2) + byteLen);
871 }
872 } else { // nope, longer String
873 _outputBuffer[origOffset] = (byteLen == len) ? TOKEN_BYTE_LONG_STRING_ASCII
874 : SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE;
875 // and we will need String end marker byte
876 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
877 }
878 }
879
880 private final void _writeSharedStringValueReference(int ix) throws IOException
881 {
882 // 03-Mar-2011, tatu: Related to [JACKSON-525], let's add a sanity check here
883 if (ix >= _seenStringValueCount) {
884 throw new IllegalArgumentException("Internal error: trying to write shared String value with index "+ix
885 +"; but have only seen "+_seenStringValueCount+" so far!");
886 }
887 if (ix < 31) { // add 1, as byte 0 is omitted
888 _writeByte((byte) (TOKEN_PREFIX_SHARED_STRING_SHORT + 1 + ix));
889 } else {
890 _writeBytes(((byte) (TOKEN_PREFIX_SHARED_STRING_LONG + (ix >> 8))), (byte) ix);
891 }
892 }
893
894 /**
895 * Helper method called to handle cases where String value to write is known
896 * to be long enough not to be shareable.
897 */
898 private final void _writeNonSharedString(final String text, final int len) throws IOException
899 {
900 // Expansion can be 3x for Unicode; and then there's type byte and end marker, so:
901 int maxLen = len + len + len + 2;
902 // Next: does it always fit within output buffer?
903 if (maxLen > _outputBuffer.length) { // nope
904 // can't rewrite type buffer, so can't speculate it might be all-ASCII
905 _writeByte(SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE);
906 _mediumUTF8Encode(text, 0, len);
907 _writeByte(BYTE_MARKER_END_OF_STRING);
908 return;
909 }
910
911 if ((_outputTail + maxLen) >= _outputEnd) {
912 _flushBuffer();
913 }
914 int origOffset = _outputTail;
915 // can't say for sure if it's ASCII or Unicode, so:
916 _writeByte(TOKEN_BYTE_LONG_STRING_ASCII);
917 int byteLen = _shortUTF8Encode(text, 0, len);
918 // If not ASCII, fix type:
919 if (byteLen > len) {
920 _outputBuffer[origOffset] = SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE;
921 }
922 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
923 }
924
925 @Override
926 public void writeString(char[] text, int offset, int len) throws IOException, JsonGenerationException
927 {
928 // Shared strings are tricky; easiest to just construct String, call the other method
929 if (len <= MAX_SHARED_STRING_LENGTH_BYTES && _seenStringValueCount >= 0 && len > 0) {
930 writeString(new String(text, offset, len));
931 return;
932 }
933 _verifyValueWrite("write String value");
934 if (len == 0) {
935 _writeByte(TOKEN_LITERAL_EMPTY_STRING);
936 return;
937 }
938 if (len <= MAX_SHORT_VALUE_STRING_BYTES) { // possibly short strings (not necessarily)
939 // first: ensure we have enough space
940 if ((_outputTail + MIN_BUFFER_FOR_POSSIBLE_SHORT_STRING) >= _outputEnd) {
941 _flushBuffer();
942 }
943 int origOffset = _outputTail;
944 ++_outputTail; // to leave room for type token
945 int byteLen = _shortUTF8Encode(text, offset, offset+len);
946 byte typeToken;
947 if (byteLen <= MAX_SHORT_VALUE_STRING_BYTES) { // yes, is short indeed
948 if (byteLen == len) { // and all ASCII
949 typeToken = (byte) ((TOKEN_PREFIX_TINY_ASCII - 1) + byteLen);
950 } else { // not just ASCII
951 typeToken = (byte) ((TOKEN_PREFIX_TINY_UNICODE - 2) + byteLen);
952 }
953 } else { // nope, longer non-ASCII Strings
954 typeToken = SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE;
955 // and we will need String end marker byte
956 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
957 }
958 // and then sneak in type token now that know the details
959 _outputBuffer[origOffset] = typeToken;
960 } else { // "long" String, never shared
961 // but might still fit within buffer?
962 int maxLen = len + len + len + 2;
963 if (maxLen <= _outputBuffer.length) { // yes indeed
964 if ((_outputTail + maxLen) >= _outputEnd) {
965 _flushBuffer();
966 }
967 int origOffset = _outputTail;
968 _writeByte(SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE);
969 int byteLen = _shortUTF8Encode(text, offset, offset+len);
970 // if it's ASCII, let's revise our type determination (to help decoder optimize)
971 if (byteLen == len) {
972 _outputBuffer[origOffset] = TOKEN_BYTE_LONG_STRING_ASCII;
973 }
974 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
975 } else {
976 _writeByte(SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE);
977 _mediumUTF8Encode(text, offset, offset+len);
978 _writeByte(BYTE_MARKER_END_OF_STRING);
979 }
980 }
981 }
982
983 @Override
984 public final void writeString(SerializableString sstr)
985 throws IOException, JsonGenerationException
986 {
987 _verifyValueWrite("write String value");
988 // First: is it empty?
989 String str = sstr.getValue();
990 int len = str.length();
991 if (len == 0) {
992 _writeByte(TOKEN_LITERAL_EMPTY_STRING);
993 return;
994 }
995 // Second: something we can share?
996 if (len <= MAX_SHARED_STRING_LENGTH_BYTES && _seenStringValueCount >= 0) {
997 int ix = _findSeenStringValue(str);
998 if (ix >= 0) {
999 _writeSharedStringValueReference(ix);
1000 return;
1001 }
1002 }
1003 // If not, use pre-encoded version
1004 byte[] raw = sstr.asUnquotedUTF8();
1005 final int byteLen = raw.length;
1006
1007 if (byteLen <= MAX_SHORT_VALUE_STRING_BYTES) { // short string
1008 // first: ensure we have enough space
1009 if ((_outputTail + byteLen + 1) >= _outputEnd) {
1010 _flushBuffer();
1011 }
1012 // ASCII or Unicode?
1013 int typeToken = (byteLen == len)
1014 ? ((TOKEN_PREFIX_TINY_ASCII - 1) + byteLen)
1015 : ((TOKEN_PREFIX_TINY_UNICODE - 2) + byteLen)
1016 ;
1017 _outputBuffer[_outputTail++] = (byte) typeToken;
1018 System.arraycopy(raw, 0, _outputBuffer, _outputTail, byteLen);
1019 _outputTail += byteLen;
1020 // plus keep reference, if it could be shared:
1021 if (_seenStringValueCount >= 0) {
1022 _addSeenStringValue(sstr.getValue());
1023 }
1024 } else { // "long" String, never shared
1025 // but might still fit within buffer?
1026 byte typeToken = (byteLen == len) ? TOKEN_BYTE_LONG_STRING_ASCII
1027 : SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE;
1028 _writeByte(typeToken);
1029 _writeBytes(raw, 0, raw.length);
1030 _writeByte(BYTE_MARKER_END_OF_STRING);
1031 }
1032 }
1033
1034 @Override
1035 public void writeRawUTF8String(byte[] text, int offset, int len)
1036 throws IOException, JsonGenerationException
1037 {
1038 _verifyValueWrite("write String value");
1039 // first: is it empty String?
1040 if (len == 0) {
1041 _writeByte(TOKEN_LITERAL_EMPTY_STRING);
1042 return;
1043 }
1044 // Sanity check: shared-strings incompatible with raw String writing
1045 if (_seenStringValueCount >= 0) {
1046 throw new UnsupportedOperationException("Can not use direct UTF-8 write methods when 'Feature.CHECK_SHARED_STRING_VALUES' enabled");
1047 }
1048 /* Other practical limitation is that we do not really know if it might be
1049 * ASCII or not; and figuring it out is rather slow. So, best we can do is
1050 * to declare we do not know it is ASCII (i.e. "is Unicode").
1051 */
1052 if (len <= MAX_SHARED_STRING_LENGTH_BYTES) { // up to 65 Unicode bytes
1053 // first: ensure we have enough space
1054 if ((_outputTail + len) >= _outputEnd) { // bytes, plus one for type indicator
1055 _flushBuffer();
1056 }
1057 /* 11-Feb-2011, tatu: As per [JACKSON-492], mininum length for "Unicode"
1058 * String is 2; 1 byte length must be ASCII.
1059 */
1060 if (len == 1) {
1061 _outputBuffer[_outputTail++] = TOKEN_PREFIX_TINY_ASCII; // length of 1 cancels out (len-1)
1062 _outputBuffer[_outputTail++] = text[offset];
1063 } else {
1064 _outputBuffer[_outputTail++] = (byte) ((TOKEN_PREFIX_TINY_UNICODE - 2) + len);
1065 System.arraycopy(text, offset, _outputBuffer, _outputTail, len);
1066 _outputTail += len;
1067 }
1068 } else { // "long" String
1069 // but might still fit within buffer?
1070 int maxLen = len + len + len + 2;
1071 if (maxLen <= _outputBuffer.length) { // yes indeed
1072 if ((_outputTail + maxLen) >= _outputEnd) {
1073 _flushBuffer();
1074 }
1075 _outputBuffer[_outputTail++] = SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE;
1076 System.arraycopy(text, offset, _outputBuffer, _outputTail, len);
1077 _outputTail += len;
1078 _outputBuffer[_outputTail++] = BYTE_MARKER_END_OF_STRING;
1079 } else {
1080 _writeByte(SmileConstants.TOKEN_MISC_LONG_TEXT_UNICODE);
1081 _writeBytes(text, offset, len);
1082 _writeByte(BYTE_MARKER_END_OF_STRING);
1083 }
1084 }
1085 }
1086
1087 @Override
1088 public final void writeUTF8String(byte[] text, int offset, int len)
1089 throws IOException, JsonGenerationException
1090 {
1091 // Since no escaping is needed, same as 'writeRawUTF8String'
1092 writeRawUTF8String(text, offset, len);
1093 }
1094
1095 /*
1096 /**********************************************************
1097 /* Output method implementations, unprocessed ("raw")
1098 /**********************************************************
1099 */
1100
1101 @Override
1102 public void writeRaw(String text) throws IOException, JsonGenerationException {
1103 throw _notSupported();
1104 }
1105
1106 @Override
1107 public void writeRaw(String text, int offset, int len) throws IOException, JsonGenerationException {
1108 throw _notSupported();
1109 }
1110
1111 @Override
1112 public void writeRaw(char[] text, int offset, int len) throws IOException, JsonGenerationException {
1113 throw _notSupported();
1114 }
1115
1116 @Override
1117 public void writeRaw(char c) throws IOException, JsonGenerationException {
1118 throw _notSupported();
1119 }
1120
1121 @Override
1122 public void writeRawValue(String text) throws IOException, JsonGenerationException {
1123 throw _notSupported();
1124 }
1125
1126 @Override
1127 public void writeRawValue(String text, int offset, int len) throws IOException, JsonGenerationException {
1128 throw _notSupported();
1129 }
1130
1131 @Override
1132 public void writeRawValue(char[] text, int offset, int len) throws IOException, JsonGenerationException {
1133 throw _notSupported();
1134 }
1135
1136 /*
1137 /**********************************************************
1138 /* Output method implementations, base64-encoded binary
1139 /**********************************************************
1140 */
1141
1142 @Override
1143 public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException, JsonGenerationException
1144 {
1145 if (data == null) {
1146 writeNull();
1147 return;
1148 }
1149 _verifyValueWrite("write Binary value");
1150 if (isEnabled(Feature.ENCODE_BINARY_AS_7BIT)) {
1151 _writeByte(TOKEN_MISC_BINARY_7BIT);
1152 _write7BitBinaryWithLength(data, offset, len);
1153 } else {
1154 _writeByte(TOKEN_MISC_BINARY_RAW);
1155 _writePositiveVInt(len);
1156 // raw is dead simple of course:
1157 _writeBytes(data, offset, len);
1158 }
1159 }
1160
1161 @Override
1162 public int writeBinary(InputStream data, int dataLength)
1163 throws IOException, JsonGenerationException
1164 {
1165 // Smile requires knowledge of length in advance, since binary is length-prefixed
1166 if (dataLength < 0) {
1167 throw new UnsupportedOperationException("Must pass actual length for Smile encoded data");
1168 }
1169 _verifyValueWrite("write Binary value");
1170 int missing;
1171 if (isEnabled(Feature.ENCODE_BINARY_AS_7BIT)) {
1172 _writeByte(TOKEN_MISC_BINARY_7BIT);
1173 byte[] encodingBuffer = _ioContext.allocBase64Buffer();
1174 try {
1175 missing = _write7BitBinaryWithLength(data, dataLength, encodingBuffer);
1176 } finally {
1177 _ioContext.releaseBase64Buffer(encodingBuffer);
1178 }
1179 } else {
1180 _writeByte(TOKEN_MISC_BINARY_RAW );
1181 _writePositiveVInt(dataLength);
1182 // raw is dead simple of course:
1183 missing = _writeBytes(data, dataLength);
1184 }
1185 if (missing > 0) {
1186 _reportError("Too few bytes available: missing "+missing+" bytes (out of "+dataLength+")");
1187 }
1188 return dataLength;
1189 }
1190
1191 @Override
1192 public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength)
1193 throws IOException, JsonGenerationException
1194 {
1195 return writeBinary(data, dataLength);
1196 }
1197
1198 /*
1199 /**********************************************************
1200 /* Output method implementations, primitive
1201 /**********************************************************
1202 */
1203
1204 @Override
1205 public void writeBoolean(boolean state) throws IOException, JsonGenerationException
1206 {
1207 _verifyValueWrite("write boolean value");
1208 if (state) {
1209 _writeByte(TOKEN_LITERAL_TRUE);
1210 } else {
1211 _writeByte(TOKEN_LITERAL_FALSE);
1212 }
1213 }
1214
1215 @Override
1216 public void writeNull() throws IOException, JsonGenerationException
1217 {
1218 _verifyValueWrite("write null value");
1219 _writeByte(TOKEN_LITERAL_NULL);
1220 }
1221
1222 @Override
1223 public void writeNumber(int i) throws IOException, JsonGenerationException
1224 {
1225 _verifyValueWrite("write number");
1226 // First things first: let's zigzag encode number
1227 i = SmileUtil.zigzagEncode(i);
1228 // tiny (single byte) or small (type + 6-bit value) number?
1229 if (i <= 0x3F && i >= 0) {
1230 if (i <= 0x1F) { // tiny
1231 _writeByte((byte) (TOKEN_PREFIX_SMALL_INT + i));
1232 return;
1233 }
1234 // nope, just small, 2 bytes (type, 1-byte zigzag value) for 6 bit value
1235 _writeBytes(TOKEN_BYTE_INT_32, (byte) (0x80 + i));
1236 return;
1237 }
1238 // Ok: let's find minimal representation then
1239 byte b0 = (byte) (0x80 + (i & 0x3F));
1240 i >>>= 6;
1241 if (i <= 0x7F) { // 13 bits is enough (== 3 byte total encoding)
1242 _writeBytes(TOKEN_BYTE_INT_32, (byte) i, b0);
1243 return;
1244 }
1245 byte b1 = (byte) (i & 0x7F);
1246 i >>= 7;
1247 if (i <= 0x7F) {
1248 _writeBytes(TOKEN_BYTE_INT_32, (byte) i, b1, b0);
1249 return;
1250 }
1251 byte b2 = (byte) (i & 0x7F);
1252 i >>= 7;
1253 if (i <= 0x7F) {
1254 _writeBytes(TOKEN_BYTE_INT_32, (byte) i, b2, b1, b0);
1255 return;
1256 }
1257 // no, need all 5 bytes
1258 byte b3 = (byte) (i & 0x7F);
1259 _writeBytes(TOKEN_BYTE_INT_32, (byte) (i >> 7), b3, b2, b1, b0);
1260 }
1261
1262 @Override
1263 public void writeNumber(long l) throws IOException, JsonGenerationException
1264 {
1265 // First: maybe 32 bits is enough?
1266 if (l <= MAX_INT_AS_LONG && l >= MIN_INT_AS_LONG) {
1267 writeNumber((int) l);
1268 return;
1269 }
1270 _verifyValueWrite("write number");
1271 // Then let's zigzag encode it
1272
1273 l = SmileUtil.zigzagEncode(l);
1274 // Ok, well, we do know that 5 lowest-significant bytes are needed
1275 int i = (int) l;
1276 // 4 can be extracted from lower int
1277 byte b0 = (byte) (0x80 + (i & 0x3F)); // sign bit set in the last byte
1278 byte b1 = (byte) ((i >> 6) & 0x7F);
1279 byte b2 = (byte) ((i >> 13) & 0x7F);
1280 byte b3 = (byte) ((i >> 20) & 0x7F);
1281 // fifth one is split between ints:
1282 l >>>= 27;
1283 byte b4 = (byte) (((int) l) & 0x7F);
1284
1285 // which may be enough?
1286 i = (int) (l >> 7);
1287 if (i == 0) {
1288 _writeBytes(TOKEN_BYTE_INT_64, b4, b3, b2, b1, b0);
1289 return;
1290 }
1291
1292 if (i <= 0x7F) {
1293 _writeBytes(TOKEN_BYTE_INT_64, (byte) i);
1294 _writeBytes(b4, b3, b2, b1, b0);
1295 return;
1296 }
1297 byte b5 = (byte) (i & 0x7F);
1298 i >>= 7;
1299 if (i <= 0x7F) {
1300 _writeBytes(TOKEN_BYTE_INT_64, (byte) i);
1301 _writeBytes(b5, b4, b3, b2, b1, b0);
1302 return;
1303 }
1304 byte b6 = (byte) (i & 0x7F);
1305 i >>= 7;
1306 if (i <= 0x7F) {
1307 _writeBytes(TOKEN_BYTE_INT_64, (byte) i, b6);
1308 _writeBytes(b5, b4, b3, b2, b1, b0);
1309 return;
1310 }
1311 byte b7 = (byte) (i & 0x7F);
1312 i >>= 7;
1313 if (i <= 0x7F) {
1314 _writeBytes(TOKEN_BYTE_INT_64, (byte) i, b7, b6);
1315 _writeBytes(b5, b4, b3, b2, b1, b0);
1316 return;
1317 }
1318 byte b8 = (byte) (i & 0x7F);
1319 i >>= 7;
1320 // must be done, with 10 bytes! (9 * 7 + 6 == 69 bits; only need 63)
1321 _writeBytes(TOKEN_BYTE_INT_64, (byte) i, b8, b7, b6);
1322 _writeBytes(b5, b4, b3, b2, b1, b0);
1323 }
1324
1325 @Override
1326 public void writeNumber(BigInteger v) throws IOException, JsonGenerationException
1327 {
1328 if (v == null) {
1329 writeNull();
1330 return;
1331 }
1332 _verifyValueWrite("write number");
1333 // quite simple: type, and then VInt-len prefixed 7-bit encoded binary data:
1334 _writeByte(TOKEN_BYTE_BIG_INTEGER);
1335 byte[] data = v.toByteArray();
1336 _write7BitBinaryWithLength(data, 0, data.length);
1337 }
1338
1339 @Override
1340 public void writeNumber(double d) throws IOException, JsonGenerationException
1341 {
1342 // Ok, now, we needed token type byte plus 10 data bytes (7 bits each)
1343 _ensureRoomForOutput(11);
1344 _verifyValueWrite("write number");
1345 /* 17-Apr-2010, tatu: could also use 'doubleToIntBits', but it seems more accurate to use
1346 * exact representation; and possibly faster. However, if there are cases
1347 * where collapsing of NaN was needed (for non-Java clients), this can
1348 * be changed
1349 */
1350 long l = Double.doubleToRawLongBits(d);
1351 _outputBuffer[_outputTail++] = TOKEN_BYTE_FLOAT_64;
1352 // Handle first 29 bits (single bit first, then 4 x 7 bits)
1353 int hi5 = (int) (l >>> 35);
1354 _outputBuffer[_outputTail+4] = (byte) (hi5 & 0x7F);
1355 hi5 >>= 7;
1356 _outputBuffer[_outputTail+3] = (byte) (hi5 & 0x7F);
1357 hi5 >>= 7;
1358 _outputBuffer[_outputTail+2] = (byte) (hi5 & 0x7F);
1359 hi5 >>= 7;
1360 _outputBuffer[_outputTail+1] = (byte) (hi5 & 0x7F);
1361 hi5 >>= 7;
1362 _outputBuffer[_outputTail] = (byte) hi5;
1363 _outputTail += 5;
1364 // Then split byte (one that crosses lo/hi int boundary), 7 bits
1365 {
1366 int mid = (int) (l >> 28);
1367 _outputBuffer[_outputTail++] = (byte) (mid & 0x7F);
1368 }
1369 // and then last 4 bytes (28 bits)
1370 int lo4 = (int) l;
1371 _outputBuffer[_outputTail+3] = (byte) (lo4 & 0x7F);
1372 lo4 >>= 7;
1373 _outputBuffer[_outputTail+2] = (byte) (lo4 & 0x7F);
1374 lo4 >>= 7;
1375 _outputBuffer[_outputTail+1] = (byte) (lo4 & 0x7F);
1376 lo4 >>= 7;
1377 _outputBuffer[_outputTail] = (byte) (lo4 & 0x7F);
1378 _outputTail += 4;
1379 }
1380
1381 @Override
1382 public void writeNumber(float f) throws IOException, JsonGenerationException
1383 {
1384 // Ok, now, we needed token type byte plus 5 data bytes (7 bits each)
1385 _ensureRoomForOutput(6);
1386 _verifyValueWrite("write number");
1387
1388 /* 17-Apr-2010, tatu: could also use 'floatToIntBits', but it seems more accurate to use
1389 * exact representation; and possibly faster. However, if there are cases
1390 * where collapsing of NaN was needed (for non-Java clients), this can
1391 * be changed
1392 */
1393 int i = Float.floatToRawIntBits(f);
1394 _outputBuffer[_outputTail++] = TOKEN_BYTE_FLOAT_32;
1395 _outputBuffer[_outputTail+4] = (byte) (i & 0x7F);
1396 i >>= 7;
1397 _outputBuffer[_outputTail+3] = (byte) (i & 0x7F);
1398 i >>= 7;
1399 _outputBuffer[_outputTail+2] = (byte) (i & 0x7F);
1400 i >>= 7;
1401 _outputBuffer[_outputTail+1] = (byte) (i & 0x7F);
1402 i >>= 7;
1403 _outputBuffer[_outputTail] = (byte) (i & 0x7F);
1404 _outputTail += 5;
1405 }
1406
1407 @Override
1408 public void writeNumber(BigDecimal dec) throws IOException, JsonGenerationException
1409 {
1410 if (dec == null) {
1411 writeNull();
1412 return;
1413 }
1414 _verifyValueWrite("write number");
1415 _writeByte(TOKEN_BYTE_BIG_DECIMAL);
1416 int scale = dec.scale();
1417 // Ok, first output scale as VInt
1418 _writeSignedVInt(scale);
1419 BigInteger unscaled = dec.unscaledValue();
1420 byte[] data = unscaled.toByteArray();
1421 // And then binary data in "safe" mode (7-bit values)
1422 _write7BitBinaryWithLength(data, 0, data.length);
1423 }
1424
1425 @Override
1426 public void writeNumber(String encodedValue) throws IOException
1427 {
1428 if (encodedValue == null) {
1429 writeNull();
1430 return;
1431 }
1432
1433 // 28-May-2014, tatu: Let's actually try to support this method; should be doable
1434 final int len = encodedValue.length();
1435 boolean neg = encodedValue.startsWith("-");
1436
1437 // Let's see if it's integral or not
1438 int i = neg ? 1 : 0;
1439 while (true) {
1440 char c = encodedValue.charAt(i);
1441 if (c > '9' || c < '0') {
1442 break;
1443 }
1444 if (++i == len) {
1445 _writeIntegralNumber(encodedValue, neg);
1446 return;
1447 }
1448 }
1449 _writeDecimalNumber(encodedValue);
1450 }
1451
1452 protected void _writeIntegralNumber(String enc, boolean neg) throws IOException
1453 {
1454 int len = enc.length();
1455 if (neg) {
1456 --len;
1457 }
1458 // let's do approximate optimization
1459 try {
1460 if (len <= 9) {
1461 writeNumber(Integer.parseInt(enc));
1462 } else if (len <= 18) {
1463 writeNumber(Long.parseLong(enc));
1464 } else {
1465 writeNumber(new BigInteger(enc));
1466 }
1467 } catch (NumberFormatException e) {
1468 throw new JsonGenerationException("Invalid String representation for Number ('"+enc
1469 +"'); can not write using Smile format");
1470 }
1471 }
1472
1473 protected void _writeDecimalNumber(String enc) throws IOException
1474 {
1475 try {
1476 writeNumber(new BigDecimal(enc));
1477 } catch (NumberFormatException e) {
1478 throw new JsonGenerationException("Invalid String representation for Number ('"+enc
1479 +"'); can not write using Smile format");
1480 }
1481 }
1482
1483 /*
1484 /**********************************************************
1485 /* Implementations for other methods
1486 /**********************************************************
1487 */
1488
1489 @Override
1490 protected final void _verifyValueWrite(String typeMsg)
1491 throws IOException, JsonGenerationException
1492 {
1493 int status = _writeContext.writeValue();
1494 if (status == JsonWriteContext.STATUS_EXPECT_NAME) {
1495 _reportError("Can not "+typeMsg+", expecting field name");
1496 }
1497 }
1498
1499 /*
1500 /**********************************************************
1501 /* Low-level output handling
1502 /**********************************************************
1503 */
1504
1505 @Override
1506 public final void flush() throws IOException
1507 {
1508 _flushBuffer();
1509 if (isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)) {
1510 _out.flush();
1511 }
1512 }
1513
1514 @Override
1515 public void close() throws IOException
1516 {
1517 // First: let's see that we still have buffers...
1518 if (_outputBuffer != null
1519 && isEnabled(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT)) {
1520 while (true) {
1521 /* 28-May-2016, tatu: To work around incompatibility introduced by
1522 * `jackson-core` 2.8 where return type of `getOutputContext()`
1523 * changed, let's do direct access here. Not a good idea generally,
1524 * but where saves us from some binary incompatibility.
1525 */
1526 // JsonStreamContext ctxt = getOutputContext();
1527 JsonStreamContext ctxt = _writeContext;
1528 if (ctxt.inArray()) {
1529 writeEndArray();
1530 } else if (ctxt.inObject()) {
1531 writeEndObject();
1532 } else {
1533 break;
1534 }
1535 }
1536 }
1537 boolean wasClosed = _closed;
1538 super.close();
1539
1540 if (!wasClosed && isEnabled(Feature.WRITE_END_MARKER)) {
1541 _writeByte(BYTE_MARKER_END_OF_CONTENT);
1542 }
1543 _flushBuffer();
1544
1545 if (_ioContext.isResourceManaged() || isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) {
1546 _out.close();
1547 } else {
1548 // If we can't close it, we should at least flush
1549 _out.flush();
1550 }
1551 // Internal buffer(s) generator has can now be released as well
1552 _releaseBuffers();
1553 }
1554
1555 /*
1556 /**********************************************************
1557 /* Internal methods, UTF-8 encoding
1558 /**********************************************************
1559 */
1560
1561 /**
1562 * Helper method called when the whole character sequence is known to
1563 * fit in the output buffer regardless of UTF-8 expansion.
1564 */
1565 private final int _shortUTF8Encode(char[] str, int i, int end)
1566 {
1567 // First: let's see if it's all ASCII: that's rather fast
1568 int ptr = _outputTail;
1569 final byte[] outBuf = _outputBuffer;
1570 do {
1571 int c = str[i];
1572 if (c > 0x7F) {
1573 return _shortUTF8Encode2(str, i, end, ptr);
1574 }
1575 outBuf[ptr++] = (byte) c;
1576 } while (++i < end);
1577 int codedLen = ptr - _outputTail;
1578 _outputTail = ptr;
1579 return codedLen;
1580 }
1581
1582 /**
1583 * Helper method called when the whole character sequence is known to
1584 * fit in the output buffer, but not all characters are single-byte (ASCII)
1585 * characters.
1586 */
1587 private final int _shortUTF8Encode2(char[] str, int i, int end, int outputPtr)
1588 {
1589 final byte[] outBuf = _outputBuffer;
1590 while (i < end) {
1591 int c = str[i++];
1592 if (c <= 0x7F) {
1593 outBuf[outputPtr++] = (byte) c;
1594 continue;
1595 }
1596 // Nope, multi-byte:
1597 if (c < 0x800) { // 2-byte
1598 outBuf[outputPtr++] = (byte) (0xc0 | (c >> 6));
1599 outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
1600 continue;
1601 }
1602 // 3 or 4 bytes (surrogate)
1603 // Surrogates?
1604 if (c < SURR1_FIRST || c > SURR2_LAST) { // nope, regular 3-byte character
1605 outBuf[outputPtr++] = (byte) (0xe0 | (c >> 12));
1606 outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1607 outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
1608 continue;
1609 }
1610 // Yup, a surrogate pair
1611 if (c > SURR1_LAST) { // must be from first range; second won't do
1612 _throwIllegalSurrogate(c);
1613 }
1614 // ... meaning it must have a pair
1615 if (i >= end) {
1616 _throwIllegalSurrogate(c);
1617 }
1618 c = _convertSurrogate(c, str[i++]);
1619 if (c > 0x10FFFF) { // illegal in JSON as well as in XML
1620 _throwIllegalSurrogate(c);
1621 }
1622 outBuf[outputPtr++] = (byte) (0xf0 | (c >> 18));
1623 outBuf[outputPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f));
1624 outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1625 outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
1626 }
1627 int codedLen = outputPtr - _outputTail;
1628 _outputTail = outputPtr;
1629 return codedLen;
1630 }
1631
1632 private final int _shortUTF8Encode(String str, int i, int end)
1633 {
1634 // First: let's see if it's all ASCII: that's rather fast
1635 int ptr = _outputTail;
1636 final byte[] outBuf = _outputBuffer;
1637 do {
1638 int c = str.charAt(i);
1639 if (c > 0x7F) {
1640 return _shortUTF8Encode2(str, i, end, ptr);
1641 }
1642 outBuf[ptr++] = (byte) c;
1643 } while (++i < end);
1644 int codedLen = ptr - _outputTail;
1645 _outputTail = ptr;
1646 return codedLen;
1647 }
1648
1649 private final int _shortUTF8Encode2(String str, int i, int end, int outputPtr)
1650 {
1651 final byte[] outBuf = _outputBuffer;
1652 while (i < end) {
1653 int c = str.charAt(i++);
1654 if (c <= 0x7F) {
1655 outBuf[outputPtr++] = (byte) c;
1656 continue;
1657 }
1658 // Nope, multi-byte:
1659 if (c < 0x800) { // 2-byte
1660 outBuf[outputPtr++] = (byte) (0xc0 | (c >> 6));
1661 outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
1662 continue;
1663 }
1664 // 3 or 4 bytes (surrogate)
1665 // Surrogates?
1666 if (c < SURR1_FIRST || c > SURR2_LAST) { // nope, regular 3-byte character
1667 outBuf[outputPtr++] = (byte) (0xe0 | (c >> 12));
1668 outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1669 outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
1670 continue;
1671 }
1672 // Yup, a surrogate pair
1673 if (c > SURR1_LAST) { // must be from first range; second won't do
1674 _throwIllegalSurrogate(c);
1675 }
1676 // ... meaning it must have a pair
1677 if (i >= end) {
1678 _throwIllegalSurrogate(c);
1679 }
1680 c = _convertSurrogate(c, str.charAt(i++));
1681 if (c > 0x10FFFF) { // illegal in JSON as well as in XML
1682 _throwIllegalSurrogate(c);
1683 }
1684 outBuf[outputPtr++] = (byte) (0xf0 | (c >> 18));
1685 outBuf[outputPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f));
1686 outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1687 outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
1688 }
1689 int codedLen = outputPtr - _outputTail;
1690 _outputTail = outputPtr;
1691 return codedLen;
1692 }
1693
1694 private void _mediumUTF8Encode(char[] str, int inputPtr, int inputEnd) throws IOException
1695 {
1696 final int bufferEnd = _outputEnd - 4;
1697
1698 output_loop:
1699 while (inputPtr < inputEnd) {
1700 /* First, let's ensure we can output at least 4 bytes
1701 * (longest UTF-8 encoded codepoint):
1702 */
1703 if (_outputTail >= bufferEnd) {
1704 _flushBuffer();
1705 }
1706 int c = str[inputPtr++];
1707 // And then see if we have an ASCII char:
1708 if (c <= 0x7F) { // If so, can do a tight inner loop:
1709 _outputBuffer[_outputTail++] = (byte)c;
1710 // Let's calc how many ASCII chars we can copy at most:
1711 int maxInCount = (inputEnd - inputPtr);
1712 int maxOutCount = (bufferEnd - _outputTail);
1713
1714 if (maxInCount > maxOutCount) {
1715 maxInCount = maxOutCount;
1716 }
1717 maxInCount += inputPtr;
1718 ascii_loop:
1719 while (true) {
1720 if (inputPtr >= maxInCount) { // done with max. ascii seq
1721 continue output_loop;
1722 }
1723 c = str[inputPtr++];
1724 if (c > 0x7F) {
1725 break ascii_loop;
1726 }
1727 _outputBuffer[_outputTail++] = (byte) c;
1728 }
1729 }
1730
1731 // Nope, multi-byte:
1732 if (c < 0x800) { // 2-byte
1733 _outputBuffer[_outputTail++] = (byte) (0xc0 | (c >> 6));
1734 _outputBuffer[_outputTail++] = (byte) (0x80 | (c & 0x3f));
1735 } else { // 3 or 4 bytes
1736 // Surrogates?
1737 if (c < SURR1_FIRST || c > SURR2_LAST) {
1738 _outputBuffer[_outputTail++] = (byte) (0xe0 | (c >> 12));
1739 _outputBuffer[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1740 _outputBuffer[_outputTail++] = (byte) (0x80 | (c & 0x3f));
1741 continue;
1742 }
1743 // Yup, a surrogate:
1744 if (c > SURR1_LAST) { // must be from first range
1745 _throwIllegalSurrogate(c);
1746 }
1747 // and if so, followed by another from next range
1748 if (inputPtr >= inputEnd) {
1749 _throwIllegalSurrogate(c);
1750 }
1751 c = _convertSurrogate(c, str[inputPtr++]);
1752 if (c > 0x10FFFF) { // illegal, as per RFC 4627
1753 _throwIllegalSurrogate(c);
1754 }
1755 _outputBuffer[_outputTail++] = (byte) (0xf0 | (c >> 18));
1756 _outputBuffer[_outputTail++] = (byte) (0x80 | ((c >> 12) & 0x3f));
1757 _outputBuffer[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1758 _outputBuffer[_outputTail++] = (byte) (0x80 | (c & 0x3f));
1759 }
1760 }
1761 }
1762
1763 private void _mediumUTF8Encode(String str, int inputPtr, int inputEnd) throws IOException
1764 {
1765 final int bufferEnd = _outputEnd - 4;
1766
1767 output_loop:
1768 while (inputPtr < inputEnd) {
1769 /* First, let's ensure we can output at least 4 bytes
1770 * (longest UTF-8 encoded codepoint):
1771 */
1772 if (_outputTail >= bufferEnd) {
1773 _flushBuffer();
1774 }
1775 int c = str.charAt(inputPtr++);
1776 // And then see if we have an ASCII char:
1777 if (c <= 0x7F) { // If so, can do a tight inner loop:
1778 _outputBuffer[_outputTail++] = (byte)c;
1779 // Let's calc how many ASCII chars we can copy at most:
1780 int maxInCount = (inputEnd - inputPtr);
1781 int maxOutCount = (bufferEnd - _outputTail);
1782
1783 if (maxInCount > maxOutCount) {
1784 maxInCount = maxOutCount;
1785 }
1786 maxInCount += inputPtr;
1787 ascii_loop:
1788 while (true) {
1789 if (inputPtr >= maxInCount) { // done with max. ascii seq
1790 continue output_loop;
1791 }
1792 c = str.charAt(inputPtr++);
1793 if (c > 0x7F) {
1794 break ascii_loop;
1795 }
1796 _outputBuffer[_outputTail++] = (byte) c;
1797 }
1798 }
1799
1800 // Nope, multi-byte:
1801 if (c < 0x800) { // 2-byte
1802 _outputBuffer[_outputTail++] = (byte) (0xc0 | (c >> 6));
1803 _outputBuffer[_outputTail++] = (byte) (0x80 | (c & 0x3f));
1804 } else { // 3 or 4 bytes
1805 // Surrogates?
1806 if (c < SURR1_FIRST || c > SURR2_LAST) {
1807 _outputBuffer[_outputTail++] = (byte) (0xe0 | (c >> 12));
1808 _outputBuffer[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1809 _outputBuffer[_outputTail++] = (byte) (0x80 | (c & 0x3f));
1810 continue;
1811 }
1812 // Yup, a surrogate:
1813 if (c > SURR1_LAST) { // must be from first range
1814 _throwIllegalSurrogate(c);
1815 }
1816 // and if so, followed by another from next range
1817 if (inputPtr >= inputEnd) {
1818 _throwIllegalSurrogate(c);
1819 }
1820 c = _convertSurrogate(c, str.charAt(inputPtr++));
1821 if (c > 0x10FFFF) { // illegal, as per RFC 4627
1822 _throwIllegalSurrogate(c);
1823 }
1824 _outputBuffer[_outputTail++] = (byte) (0xf0 | (c >> 18));
1825 _outputBuffer[_outputTail++] = (byte) (0x80 | ((c >> 12) & 0x3f));
1826 _outputBuffer[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f));
1827 _outputBuffer[_outputTail++] = (byte) (0x80 | (c & 0x3f));
1828 }
1829 }
1830 }
1831
1832 /**
1833 * Method called to calculate UTF codepoint, from a surrogate pair.
1834 */
1835 private int _convertSurrogate(int firstPart, int secondPart)
1836 {
1837 // Ok, then, is the second part valid?
1838 if (secondPart < SURR2_FIRST || secondPart > SURR2_LAST) {
1839 throw new IllegalArgumentException("Broken surrogate pair: first char 0x"+Integer.toHexString(firstPart)+", second 0x"+Integer.toHexString(secondPart)+"; illegal combination");
1840 }
1841 return 0x10000 + ((firstPart - SURR1_FIRST) << 10) + (secondPart - SURR2_FIRST);
1842 }
1843
1844 private void _throwIllegalSurrogate(int code)
1845 {
1846 if (code > 0x10FFFF) { // over max?
1847 throw new IllegalArgumentException("Illegal character point (0x"+Integer.toHexString(code)+") to output; max is 0x10FFFF as per RFC 4627");
1848 }
1849 if (code >= SURR1_FIRST) {
1850 if (code <= SURR1_LAST) { // Unmatched first part (closing without second part?)
1851 throw new IllegalArgumentException("Unmatched first part of surrogate pair (0x"+Integer.toHexString(code)+")");
1852 }
1853 throw new IllegalArgumentException("Unmatched second part of surrogate pair (0x"+Integer.toHexString(code)+")");
1854 }
1855 // should we ever get this?
1856 throw new IllegalArgumentException("Illegal character point (0x"+Integer.toHexString(code)+") to output");
1857 }
1858
1859 /*
1860 /**********************************************************
1861 /* Internal methods, writing bytes
1862 /**********************************************************
1863 */
1864
1865 private final void _ensureRoomForOutput(int needed) throws IOException
1866 {
1867 if ((_outputTail + needed) >= _outputEnd) {
1868 _flushBuffer();
1869 }
1870 }
1871
1872 private final void _writeByte(byte b) throws IOException
1873 {
1874 if (_outputTail >= _outputEnd) {
1875 _flushBuffer();
1876 }
1877 _outputBuffer[_outputTail++] = b;
1878 }
1879
1880 private final void _writeBytes(byte b1, byte b2) throws IOException
1881 {
1882 if ((_outputTail + 1) >= _outputEnd) {
1883 _flushBuffer();
1884 }
1885 _outputBuffer[_outputTail++] = b1;
1886 _outputBuffer[_outputTail++] = b2;
1887 }
1888
1889 private final void _writeBytes(byte b1, byte b2, byte b3) throws IOException
1890 {
1891 if ((_outputTail + 2) >= _outputEnd) {
1892 _flushBuffer();
1893 }
1894 _outputBuffer[_outputTail++] = b1;
1895 _outputBuffer[_outputTail++] = b2;
1896 _outputBuffer[_outputTail++] = b3;
1897 }
1898
1899 private final void _writeBytes(byte b1, byte b2, byte b3, byte b4) throws IOException
1900 {
1901 if ((_outputTail + 3) >= _outputEnd) {
1902 _flushBuffer();
1903 }
1904 _outputBuffer[_outputTail++] = b1;
1905 _outputBuffer[_outputTail++] = b2;
1906 _outputBuffer[_outputTail++] = b3;
1907 _outputBuffer[_outputTail++] = b4;
1908 }
1909
1910 private final void _writeBytes(byte b1, byte b2, byte b3, byte b4, byte b5) throws IOException
1911 {
1912 if ((_outputTail + 4) >= _outputEnd) {
1913 _flushBuffer();
1914 }
1915 _outputBuffer[_outputTail++] = b1;
1916 _outputBuffer[_outputTail++] = b2;
1917 _outputBuffer[_outputTail++] = b3;
1918 _outputBuffer[_outputTail++] = b4;
1919 _outputBuffer[_outputTail++] = b5;
1920 }
1921
1922 private final void _writeBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6) throws IOException
1923 {
1924 if ((_outputTail + 5) >= _outputEnd) {
1925 _flushBuffer();
1926 }
1927 _outputBuffer[_outputTail++] = b1;
1928 _outputBuffer[_outputTail++] = b2;
1929 _outputBuffer[_outputTail++] = b3;
1930 _outputBuffer[_outputTail++] = b4;
1931 _outputBuffer[_outputTail++] = b5;
1932 _outputBuffer[_outputTail++] = b6;
1933 }
1934
1935 private final void _writeBytes(byte[] data, int offset, int len) throws IOException
1936 {
1937 if (len == 0) {
1938 return;
1939 }
1940 if ((_outputTail + len) >= _outputEnd) {
1941 _writeBytesLong(data, offset, len);
1942 return;
1943 }
1944 // common case, non-empty, fits in just fine:
1945 System.arraycopy(data, offset, _outputBuffer, _outputTail, len);
1946 _outputTail += len;
1947 }
1948
1949 private final int _writeBytes(InputStream in, int bytesLeft) throws IOException
1950 {
1951 while (bytesLeft > 0) {
1952 int room = _outputEnd - _outputTail;
1953 if (room <= 0) {
1954 _flushBuffer();
1955 room = _outputEnd - _outputTail;
1956 }
1957 if (room > bytesLeft) {
1958 room = bytesLeft;
1959 }
1960 int count = in.read(_outputBuffer, _outputTail, room);
1961 if (count < 0) {
1962 break;
1963 }
1964 _outputTail += count;
1965 bytesLeft -= count;
1966 }
1967 return bytesLeft;
1968 }
1969
1970 private final void _writeBytesLong(byte[] data, int offset, int len) throws IOException
1971 {
1972 if (_outputTail >= _outputEnd) {
1973 _flushBuffer();
1974 }
1975 while (true) {
1976 int currLen = Math.min(len, (_outputEnd - _outputTail));
1977 System.arraycopy(data, offset, _outputBuffer, _outputTail, currLen);
1978 _outputTail += currLen;
1979 if ((len -= currLen) == 0) {
1980 break;
1981 }
1982 offset += currLen;
1983 _flushBuffer();
1984 }
1985 }
1986
1987 /**
1988 * Helper method for writing a 32-bit positive (really 31-bit then) value.
1989 * Value is NOT zigzag encoded (since there is no sign bit to worry about)
1990 */
1991 private void _writePositiveVInt(int i) throws IOException
1992 {
1993 // At most 5 bytes (4 * 7 + 6 bits == 34 bits)
1994 _ensureRoomForOutput(5);
1995 byte b0 = (byte) (0x80 + (i & 0x3F));
1996 i >>= 6;
1997 if (i <= 0x7F) { // 6 or 13 bits is enough (== 2 or 3 byte total encoding)
1998 if (i > 0) {
1999 _outputBuffer[_outputTail++] = (byte) i;
2000 }
2001 _outputBuffer[_outputTail++] = b0;
2002 return;
2003 }
2004 byte b1 = (byte) (i & 0x7F);
2005 i >>= 7;
2006 if (i <= 0x7F) {
2007 _outputBuffer[_outputTail++] = (byte) i;
2008 _outputBuffer[_outputTail++] = b1;
2009 _outputBuffer[_outputTail++] = b0;
2010 } else {
2011 byte b2 = (byte) (i & 0x7F);
2012 i >>= 7;
2013 if (i <= 0x7F) {
2014 _outputBuffer[_outputTail++] = (byte) i;
2015 _outputBuffer[_outputTail++] = b2;
2016 _outputBuffer[_outputTail++] = b1;
2017 _outputBuffer[_outputTail++] = b0;
2018 } else {
2019 byte b3 = (byte) (i & 0x7F);
2020 _outputBuffer[_outputTail++] = (byte) (i >> 7);
2021 _outputBuffer[_outputTail++] = b3;
2022 _outputBuffer[_outputTail++] = b2;
2023 _outputBuffer[_outputTail++] = b1;
2024 _outputBuffer[_outputTail++] = b0;
2025 }
2026 }
2027 }
2028
2029 /**
2030 * Helper method for writing 32-bit signed value, using
2031 * "zig zag encoding" (see protocol buffers for explanation -- basically,
2032 * sign bit is moved as LSB, rest of value shifted left by one)
2033 * coupled with basic variable length encoding
2034 */
2035 private void _writeSignedVInt(int input) throws IOException
2036 {
2037 _writePositiveVInt(SmileUtil.zigzagEncode(input));
2038 }
2039
2040 protected void _write7BitBinaryWithLength(byte[] data, int offset, int len) throws IOException
2041 {
2042 _writePositiveVInt(len);
2043 // first, let's handle full 7-byte chunks
2044 while (len >= 7) {
2045 if ((_outputTail + 8) >= _outputEnd) {
2046 _flushBuffer();
2047 }
2048 int i = data[offset++]; // 1st byte
2049 _outputBuffer[_outputTail++] = (byte) ((i >> 1) & 0x7F);
2050 i = (i << 8) | (data[offset++] & 0xFF); // 2nd
2051 _outputBuffer[_outputTail++] = (byte) ((i >> 2) & 0x7F);
2052 i = (i << 8) | (data[offset++] & 0xFF); // 3rd
2053 _outputBuffer[_outputTail++] = (byte) ((i >> 3) & 0x7F);
2054 i = (i << 8) | (data[offset++] & 0xFF); // 4th
2055 _outputBuffer[_outputTail++] = (byte) ((i >> 4) & 0x7F);
2056 i = (i << 8) | (data[offset++] & 0xFF); // 5th
2057 _outputBuffer[_outputTail++] = (byte) ((i >> 5) & 0x7F);
2058 i = (i << 8) | (data[offset++] & 0xFF); // 6th
2059 _outputBuffer[_outputTail++] = (byte) ((i >> 6) & 0x7F);
2060 i = (i << 8) | (data[offset++] & 0xFF); // 7th
2061 _outputBuffer[_outputTail++] = (byte) ((i >> 7) & 0x7F);
2062 _outputBuffer[_outputTail++] = (byte) (i & 0x7F);
2063 len -= 7;
2064 }
2065 // and then partial piece, if any
2066 if (len > 0) {
2067 // up to 6 bytes to output, resulting in at most 7 bytes (which can encode 49 bits)
2068 if ((_outputTail + 7) >= _outputEnd) {
2069 _flushBuffer();
2070 }
2071 int i = data[offset++];
2072 _outputBuffer[_outputTail++] = (byte) ((i >> 1) & 0x7F);
2073 if (len > 1) {
2074 i = ((i & 0x01) << 8) | (data[offset++] & 0xFF); // 2nd
2075 _outputBuffer[_outputTail++] = (byte) ((i >> 2) & 0x7F);
2076 if (len > 2) {
2077 i = ((i & 0x03) << 8) | (data[offset++] & 0xFF); // 3rd
2078 _outputBuffer[_outputTail++] = (byte) ((i >> 3) & 0x7F);
2079 if (len > 3) {
2080 i = ((i & 0x07) << 8) | (data[offset++] & 0xFF); // 4th
2081 _outputBuffer[_outputTail++] = (byte) ((i >> 4) & 0x7F);
2082 if (len > 4) {
2083 i = ((i & 0x0F) << 8) | (data[offset++] & 0xFF); // 5th
2084 _outputBuffer[_outputTail++] = (byte) ((i >> 5) & 0x7F);
2085 if (len > 5) {
2086 i = ((i & 0x1F) << 8) | (data[offset++] & 0xFF); // 6th
2087 _outputBuffer[_outputTail++] = (byte) ((i >> 6) & 0x7F);
2088 _outputBuffer[_outputTail++] = (byte) (i & 0x3F); // last 6 bits
2089 } else {
2090 _outputBuffer[_outputTail++] = (byte) (i & 0x1F); // last 5 bits
2091 }
2092 } else {
2093 _outputBuffer[_outputTail++] = (byte) (i & 0x0F); // last 4 bits
2094 }
2095 } else {
2096 _outputBuffer[_outputTail++] = (byte) (i & 0x07); // last 3 bits
2097 }
2098 } else {
2099 _outputBuffer[_outputTail++] = (byte) (i & 0x03); // last 2 bits
2100 }
2101 } else {
2102 _outputBuffer[_outputTail++] = (byte) (i & 0x01); // last bit
2103 }
2104 }
2105 }
2106
2107 protected int _write7BitBinaryWithLength(InputStream in, int bytesLeft, byte[] buffer)
2108 throws IOException
2109 {
2110 _writePositiveVInt(bytesLeft);
2111 int inputPtr = 0;
2112 int inputEnd = 0;
2113 int lastFullOffset = -7;
2114
2115 // first, let's handle full 7-byte chunks
2116 while (bytesLeft >= 7) {
2117 if (inputPtr > lastFullOffset) {
2118 inputEnd = _readMore(in, buffer, inputPtr, inputEnd, bytesLeft);
2119 inputPtr = 0;
2120 if (inputEnd < 7) { // required to try to read to have at least 7 bytes
2121 bytesLeft -= inputEnd; // just to give accurate error messages wrt how much was gotten
2122 break;
2123 }
2124 lastFullOffset = inputEnd-7;
2125 }
2126 if ((_outputTail + 8) >= _outputEnd) {
2127 _flushBuffer();
2128 }
2129 int i = buffer[inputPtr++]; // 1st byte
2130 _outputBuffer[_outputTail++] = (byte) ((i >> 1) & 0x7F);
2131 i = (i << 8) | (buffer[inputPtr++] & 0xFF); // 2nd
2132 _outputBuffer[_outputTail++] = (byte) ((i >> 2) & 0x7F);
2133 i = (i << 8) | (buffer[inputPtr++] & 0xFF); // 3rd
2134 _outputBuffer[_outputTail++] = (byte) ((i >> 3) & 0x7F);
2135 i = (i << 8) | (buffer[inputPtr++] & 0xFF); // 4th
2136 _outputBuffer[_outputTail++] = (byte) ((i >> 4) & 0x7F);
2137 i = (i << 8) | (buffer[inputPtr++] & 0xFF); // 5th
2138 _outputBuffer[_outputTail++] = (byte) ((i >> 5) & 0x7F);
2139 i = (i << 8) | (buffer[inputPtr++] & 0xFF); // 6th
2140 _outputBuffer[_outputTail++] = (byte) ((i >> 6) & 0x7F);
2141 i = (i << 8) | (buffer[inputPtr++] & 0xFF); // 7th
2142 _outputBuffer[_outputTail++] = (byte) ((i >> 7) & 0x7F);
2143 _outputBuffer[_outputTail++] = (byte) (i & 0x7F);
2144 bytesLeft -= 7;
2145 }
2146
2147 // and then partial piece, if any
2148 if (bytesLeft > 0) {
2149 // up to 6 bytes to output, resulting in at most 7 bytes (which can encode 49 bits)
2150 if ((_outputTail + 7) >= _outputEnd) {
2151 _flushBuffer();
2152 }
2153 inputEnd = _readMore(in, buffer, inputPtr, inputEnd, bytesLeft);
2154 inputPtr = 0;
2155 if (inputEnd > 0) { // yes, but do we have room for output?
2156 bytesLeft -= inputEnd;
2157 int i = buffer[inputPtr++];
2158 _outputBuffer[_outputTail++] = (byte) ((i >> 1) & 0x7F);
2159 if (inputEnd > 1) {
2160 i = ((i & 0x01) << 8) | (buffer[inputPtr++] & 0xFF); // 2nd
2161 _outputBuffer[_outputTail++] = (byte) ((i >> 2) & 0x7F);
2162 if (inputEnd > 2) {
2163 i = ((i & 0x03) << 8) | (buffer[inputPtr++] & 0xFF); // 3rd
2164 _outputBuffer[_outputTail++] = (byte) ((i >> 3) & 0x7F);
2165 if (inputEnd > 3) {
2166 i = ((i & 0x07) << 8) | (buffer[inputPtr++] & 0xFF); // 4th
2167 _outputBuffer[_outputTail++] = (byte) ((i >> 4) & 0x7F);
2168 if (inputEnd > 4) {
2169 i = ((i & 0x0F) << 8) | (buffer[inputPtr++] & 0xFF); // 5th
2170 _outputBuffer[_outputTail++] = (byte) ((i >> 5) & 0x7F);
2171 if (inputEnd > 5) {
2172 i = ((i & 0x1F) << 8) | (buffer[inputPtr++] & 0xFF); // 6th
2173 _outputBuffer[_outputTail++] = (byte) ((i >> 6) & 0x7F);
2174 _outputBuffer[_outputTail++] = (byte) (i & 0x3F); // last 6 bits
2175 } else {
2176 _outputBuffer[_outputTail++] = (byte) (i & 0x1F); // last 5 bits
2177 }
2178 } else {
2179 _outputBuffer[_outputTail++] = (byte) (i & 0x0F); // last 4 bits
2180 }
2181 } else {
2182 _outputBuffer[_outputTail++] = (byte) (i & 0x07); // last 3 bits
2183 }
2184 } else {
2185 _outputBuffer[_outputTail++] = (byte) (i & 0x03); // last 2 bits
2186 }
2187 } else {
2188 _outputBuffer[_outputTail++] = (byte) (i & 0x01); // last bit
2189 }
2190 }
2191 }
2192 return bytesLeft;
2193 }
2194
2195 private int _readMore(InputStream in,
2196 byte[] readBuffer, int inputPtr, int inputEnd,
2197 int maxRead) throws IOException
2198 {
2199 // anything to shift to front?
2200 int i = 0;
2201 while (inputPtr < inputEnd) {
2202 readBuffer[i++] = readBuffer[inputPtr++];
2203 }
2204 inputPtr = 0;
2205 inputEnd = i;
2206
2207 maxRead = Math.min(maxRead, readBuffer.length);
2208
2209 do {
2210 /* 26-Feb-2013, tatu: Similar to jackson-core issue #55, need to ensure
2211 * we have something to read.
2212 */
2213 int length = maxRead - inputEnd;
2214 if (length == 0) {
2215 break;
2216 }
2217 int count = in.read(readBuffer, inputEnd, length);
2218 if (count < 0) {
2219 return inputEnd;
2220 }
2221 inputEnd += count;
2222 } while (inputEnd < 7);
2223 return inputEnd;
2224 }
2225
2226 /*
2227 /**********************************************************
2228 /* Internal methods, buffer handling
2229 /**********************************************************
2230 */
2231
2232 @Override
2233 protected void _releaseBuffers()
2234 {
2235 byte[] buf = _outputBuffer;
2236 if (buf != null && _bufferRecyclable) {
2237 _outputBuffer = null;
2238 _ioContext.releaseWriteEncodingBuffer(buf);
2239 }
2240 /* Ok: since clearing up of larger arrays is much slower,
2241 * let's only recycle default-sized buffers...
2242 */
2243 {
2244 SharedStringNode[] nameBuf = _seenNames;
2245 if (nameBuf != null && nameBuf.length == SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH) {
2246 _seenNames = null;
2247 /* 28-Jun-2011, tatu: With 1.9, caller needs to clear the buffer; and note
2248 * that since it's a hash area, must clear all
2249 */
2250 if (_seenNameCount > 0) {
2251 Arrays.fill(nameBuf, null);
2252 }
2253 _smileBufferRecycler.releaseSeenNamesBuffer(nameBuf);
2254 }
2255 }
2256 {
2257 SharedStringNode[] valueBuf = _seenStringValues;
2258 if (valueBuf != null && valueBuf.length == SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH) {
2259 _seenStringValues = null;
2260 /* 28-Jun-2011, tatu: With 1.9, caller needs to clear the buffer; and note
2261 * that since it's a hash area, must clear all
2262 */
2263 if (_seenStringValueCount > 0) {
2264 Arrays.fill(valueBuf, null);
2265 }
2266 _smileBufferRecycler.releaseSeenStringValuesBuffer(valueBuf);
2267 }
2268 }
2269 }
2270
2271 protected final void _flushBuffer() throws IOException
2272 {
2273 if (_outputTail > 0) {
2274 _bytesWritten += _outputTail;
2275 _out.write(_outputBuffer, 0, _outputTail);
2276 _outputTail = 0;
2277 }
2278 }
2279
2280 /*
2281 /**********************************************************
2282 /* Internal methods, handling shared string "maps"
2283 /**********************************************************
2284 */
2285
2286 private final int _findSeenName(String name)
2287 {
2288 int hash = name.hashCode();
2289 SharedStringNode head = _seenNames[hash & (_seenNames.length-1)];
2290 if (head == null) {
2291 return -1;
2292 }
2293 SharedStringNode node = head;
2294 // first, identity match; assuming most of the time we get intern()ed String
2295 // And do unrolled initial check; 90+% likelihood head node has all info we need:
2296 if (node.value == name) {
2297 return node.index;
2298 }
2299 while ((node = node.next) != null) {
2300 if (node.value == name) {
2301 return node.index;
2302 }
2303 }
2304 // If not, equality check; we already know head is not null
2305 node = head;
2306 do {
2307 String value = node.value;
2308 if (value.hashCode() == hash && value.equals(name)) {
2309 return node.index;
2310 }
2311 node = node.next;
2312 } while (node != null);
2313 return -1;
2314 }
2315
2316 private final void _addSeenName(String name)
2317 {
2318 // first: do we need to expand?
2319 if (_seenNameCount == _seenNames.length) {
2320 if (_seenNameCount == MAX_SHARED_NAMES) { // we are too full, restart from empty
2321 Arrays.fill(_seenNames, null);
2322 _seenNameCount = 0;
2323 } else { // we always start with modest default size (like 64), so expand to full
2324 SharedStringNode[] old = _seenNames;
2325 _seenNames = new SharedStringNode[MAX_SHARED_NAMES];
2326 final int mask = MAX_SHARED_NAMES-1;
2327 for (SharedStringNode node : old) {
2328 while (node != null) {
2329 int ix = node.value.hashCode() & mask;
2330 SharedStringNode next = node.next;
2331 node.next = _seenNames[ix];
2332 _seenNames[ix] = node;
2333 node = next;
2334 }
2335 }
2336 }
2337 }
2338 // other than that, just slap it there
2339 int ref = _seenNameCount;
2340 if (_validBackRef(ref)) {
2341 int ix = name.hashCode() & (_seenNames.length-1);
2342 _seenNames[ix] = new SharedStringNode(name, ref, _seenNames[ix]);
2343 }
2344 _seenNameCount = ref+1;
2345 }
2346
2347 private final int _findSeenStringValue(String text)
2348 {
2349 int hash = text.hashCode();
2350 SharedStringNode head = _seenStringValues[hash & (_seenStringValues.length-1)];
2351 if (head != null) {
2352 SharedStringNode node = head;
2353 // first, identity match; assuming most of the time we get intern()ed String
2354 do {
2355 if (node.value == text) {
2356 return node.index;
2357 }
2358 node = node.next;
2359 } while (node != null);
2360 // and then comparison, if no match yet
2361 node = head;
2362 do {
2363 String value = node.value;
2364 if (value.hashCode() == hash && value.equals(text)) {
2365 return node.index;
2366 }
2367 node = node.next;
2368 } while (node != null);
2369 }
2370 return -1;
2371 }
2372
2373 private final void _addSeenStringValue(String text)
2374 {
2375 // first: do we need to expand?
2376 if (_seenStringValueCount == _seenStringValues.length) {
2377 if (_seenStringValueCount == MAX_SHARED_STRING_VALUES) { // we are too full, restart from empty
2378 Arrays.fill(_seenStringValues, null);
2379 _seenStringValueCount = 0;
2380 } else { // we always start with modest default size (like 64), so expand to full
2381 SharedStringNode[] old = _seenStringValues;
2382 _seenStringValues = new SharedStringNode[MAX_SHARED_STRING_VALUES];
2383 final int mask = MAX_SHARED_STRING_VALUES-1;
2384 for (SharedStringNode node : old) {
2385 while (node != null) {
2386 int ix = node.value.hashCode() & mask;
2387 SharedStringNode next = node.next;
2388 node.next = _seenStringValues[ix];
2389 _seenStringValues[ix] = node;
2390 node = next;
2391 }
2392 }
2393 }
2394 }
2395 // other than that, just slap it there
2396 /* [Issue#18]: Except need to avoid producing bytes 0xFE and 0xFF in content;
2397 * so skip additions of those; this may produce duplicate values (and lower
2398 * efficiency), but it must be done to since these bytes must be avoided by
2399 * encoder, as per specification (except for native byte content, or as explicit
2400 * end markers). Avoiding nulls is sort of
2401 */
2402 int ref = _seenStringValueCount;
2403 if (_validBackRef(ref)) {
2404 int ix = text.hashCode() & (_seenStringValues.length-1);
2405 _seenStringValues[ix] = new SharedStringNode(text, ref, _seenStringValues[ix]);
2406 }
2407 _seenStringValueCount = ref+1;
2408 }
2409
2410 /**
2411 * Helper method used to ensure that we do not use back-reference values
2412 * that would produce illegal byte sequences (ones with byte 0xFE or 0xFF).
2413 * Note that we do not try to avoid null byte (0x00) by default, although
2414 * it would be technically possible as well.
2415 */
2416 private final static boolean _validBackRef(int index) {
2417 return (index & 0xFF) < 0xFE;
2418 }
2419
2420 /*
2421 /**********************************************************
2422 /* Internal methods, error reporting
2423 /**********************************************************
2424 */
2425
2426 /**
2427 * Method for accessing offset of the next byte within the whole output
2428 * stream that this generator has produced.
2429 */
2430 protected long outputOffset() {
2431 return _bytesWritten + _outputTail;
2432 }
2433
2434 protected UnsupportedOperationException _notSupported() {
2435 return new UnsupportedOperationException();
2436 }
2437 }