package com.fasterxml.jackson.dataformat.cbor;
import java.util.Arrays;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.GeneratorBase;
import com.fasterxml.jackson.core.io.IOContext;
import com.fasterxml.jackson.core.json.DupDetector;
import com.fasterxml.jackson.core.util.JacksonFeatureSet;
import static com.fasterxml.jackson.dataformat.cbor.CBORConstants.*;
public class CBORGenerator extends GeneratorBase
{
private final static int[] NO_INTS = new int[0];
final static int BYTE_BUFFER_FOR_OUTPUT = 16000;
final static int REPLACEMENT_CHAR = 0xfffd;
private final static int MAX_LONG_STRING_CHARS = (BYTE_BUFFER_FOR_OUTPUT / 4) - 4;
private final static int MAX_LONG_STRING_BYTES = (MAX_LONG_STRING_CHARS * 3) + 3;
public enum Feature implements FormatFeature {
WRITE_MINIMAL_INTS(true),
WRITE_TYPE_HEADER(false),
LENIENT_UTF_ENCODING(false),
;
protected final boolean _defaultState;
protected final int _mask;
public static int collectDefaults() {
int flags = 0;
for (Feature f : values()) {
if (f.enabledByDefault()) {
flags |= f.getMask();
}
}
return flags;
}
private Feature(boolean defaultState) {
_defaultState = defaultState;
_mask = (1 << ordinal());
}
@Override
public boolean enabledByDefault() {
return _defaultState;
}
@Override
public boolean enabledIn(int flags) {
return (flags & getMask()) != 0;
}
@Override
public int getMask() {
return _mask;
}
}
private final static int MIN_BUFFER_LENGTH = (3 * 256) + 2;
private final static int INDEFINITE_LENGTH = -2;
final protected IOContext _ioContext;
final protected OutputStream _out;
protected int _formatFeatures;
protected boolean _cfgMinimalInts;
protected CBORWriteContext _cborContext;
protected byte[] _outputBuffer;
protected int _outputTail = 0;
protected final int _outputEnd;
protected char[] _charBuffer;
protected final int _charBufferLength;
protected int _bytesWritten;
protected int[] _elementCounts = NO_INTS;
protected int _elementCountsPtr;
protected int _currentRemainingElements = INDEFINITE_LENGTH;
protected boolean _bufferRecyclable;
public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures,
ObjectCodec codec, OutputStream out) {
super(stdFeatures, codec, null);
DupDetector dups = JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION.enabledIn(stdFeatures)
? DupDetector.rootDetector(this)
: null;
_cborContext = CBORWriteContext.createRootContext(dups);
_formatFeatures = formatFeatures;
_cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures);
_ioContext = ctxt;
_out = out;
_bufferRecyclable = true;
_outputBuffer = ctxt.allocWriteEncodingBuffer(BYTE_BUFFER_FOR_OUTPUT);
_outputEnd = _outputBuffer.length;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
if (_outputEnd < MIN_BUFFER_LENGTH) {
throw new IllegalStateException("Internal encoding buffer length ("
+ _outputEnd + ") too short, must be at least "
+ MIN_BUFFER_LENGTH);
}
}
public CBORGenerator(IOContext ctxt, int stdFeatures, int formatFeatures,
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;
_cborContext = CBORWriteContext.createRootContext(dups);
_formatFeatures = formatFeatures;
_cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(formatFeatures);
_ioContext = ctxt;
_out = out;
_bufferRecyclable = bufferRecyclable;
_outputTail = offset;
_outputBuffer = outputBuffer;
_outputEnd = _outputBuffer.length;
_charBuffer = ctxt.allocConcatBuffer();
_charBufferLength = _charBuffer.length;
if (_outputEnd < MIN_BUFFER_LENGTH) {
throw new IllegalStateException("Internal encoding buffer length ("
+ _outputEnd + ") too short, must be at least "
+ MIN_BUFFER_LENGTH);
}
}
@Override
public Version version() {
return PackageVersion.VERSION;
}
@Override
public boolean canWriteBinaryNatively() {
return true;
}
@Override
public JacksonFeatureSet<StreamWriteCapability> getWriteCapabilities() {
return DEFAULT_BINARY_WRITE_CAPABILITIES;
}
@Override
public JsonGenerator useDefaultPrettyPrinter() {
return this;
}
@Override
public JsonGenerator setPrettyPrinter(PrettyPrinter pp) {
return this;
}
@Override
public Object getOutputTarget() {
return _out;
}
@Override
public int getOutputBuffered() {
return _outputTail;
}
@Override
public int getFormatFeatures() {
return _formatFeatures;
}
@Override
public JsonGenerator overrideStdFeatures(int values, int mask) {
int oldState = _features;
int newState = (oldState & ~mask) | (values & mask);
if (oldState != newState) {
_features = newState;
}
return this;
}
@Override
public JsonGenerator overrideFormatFeatures(int values, int mask) {
int oldState = _formatFeatures;
int newState = (_formatFeatures & ~mask) | (values & mask);
if (oldState != newState) {
_formatFeatures = newState;
_cfgMinimalInts = Feature.WRITE_MINIMAL_INTS.enabledIn(newState);
}
return this;
}
@Override
public Object getCurrentValue() {
return _cborContext.getCurrentValue();
}
@Override
public void setCurrentValue(Object v) {
_cborContext.setCurrentValue(v);
}
@Override
public JsonStreamContext getOutputContext() {
return _cborContext;
}
public CBORGenerator enable(Feature f) {
_formatFeatures |= f.getMask();
if (f == Feature.WRITE_MINIMAL_INTS) {
_cfgMinimalInts = true;
}
return this;
}
public CBORGenerator disable(Feature f) {
_formatFeatures &= ~f.getMask();
if (f == Feature.WRITE_MINIMAL_INTS) {
_cfgMinimalInts = false;
}
return this;
}
public final boolean isEnabled(Feature f) {
return (_formatFeatures & f.getMask()) != 0;
}
public CBORGenerator configure(Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
@Override
public final void writeFieldName(String name) throws IOException {
if (!_cborContext.writeFieldName(name)) {
_reportError("Can not write a field name, expecting a value");
}
_writeString(name);
}
@Override
public final void writeFieldName(SerializableString name)
throws IOException {
if (!_cborContext.writeFieldName(name.getValue())) {
_reportError("Can not write a field name, expecting a value");
}
byte[] raw = name.asUnquotedUTF8();
final int len = raw.length;
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeLengthMarker(PREFIX_TYPE_TEXT, len);
_writeBytes(raw, 0, len);
}
@Override
public final void writeFieldId(long id) throws IOException {
if (!_cborContext.writeFieldId(id)) {
_reportError("Can not write a field id, expecting a value");
}
_writeLongNoCheck(id);
}
@Override
public void copyCurrentEvent(JsonParser p) throws IOException {
maybeCopyTag(p);
super.copyCurrentEvent(p);
}
@Override
public void copyCurrentStructure(JsonParser p) throws IOException {
maybeCopyTag(p);
super.copyCurrentStructure(p);
}
protected void maybeCopyTag(JsonParser p) throws IOException {
if (p instanceof CBORParser) {
if (p.hasCurrentToken()) {
final int currentTag = ((CBORParser) p).getCurrentTag();
if (currentTag != -1) {
writeTag(currentTag);
}
}
}
}
@Override
public final void writeStartArray() throws IOException {
_verifyValueWrite("start an array");
_cborContext = _cborContext.createChildArrayContext(null);
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_ARRAY_INDEFINITE);
}
@Override
public void writeStartArray(Object forValue) throws IOException {
_verifyValueWrite("start an array");
_cborContext = _cborContext.createChildArrayContext(forValue);
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_ARRAY_INDEFINITE);
}
@Override
public void writeStartArray(Object forValue, int elementsToWrite) throws IOException {
_verifyValueWrite("start an array");
_cborContext = _cborContext.createChildArrayContext(forValue);
_pushRemainingElements();
_currentRemainingElements = elementsToWrite;
_writeLengthMarker(PREFIX_TYPE_ARRAY, elementsToWrite);
}
@Deprecated
@Override
public void writeStartArray(int elementsToWrite) throws IOException {
_verifyValueWrite("start an array");
_cborContext = _cborContext.createChildArrayContext(null);
_pushRemainingElements();
_currentRemainingElements = elementsToWrite;
_writeLengthMarker(PREFIX_TYPE_ARRAY, elementsToWrite);
}
@Override
public final void writeEndArray() throws IOException {
if (!_cborContext.inArray()) {
_reportError("Current context not Array but "+_cborContext.typeDesc());
}
closeComplexElement();
_cborContext = _cborContext.getParent();
}
@Override
public final void writeStartObject() throws IOException {
_verifyValueWrite("start an object");
_cborContext = _cborContext.createChildObjectContext(null);
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_OBJECT_INDEFINITE);
}
@Override
public final void writeStartObject(Object forValue) throws IOException {
_verifyValueWrite("start an object");
CBORWriteContext ctxt = _cborContext.createChildObjectContext(forValue);
_cborContext = ctxt;
if (_elementCountsPtr > 0) {
_pushRemainingElements();
}
_currentRemainingElements = INDEFINITE_LENGTH;
_writeByte(BYTE_OBJECT_INDEFINITE);
}
public final void writeStartObject(int elementsToWrite) throws IOException {
_verifyValueWrite("start an object");
_cborContext = _cborContext.createChildObjectContext(null);
_pushRemainingElements();
_currentRemainingElements = elementsToWrite;
_writeLengthMarker(PREFIX_TYPE_OBJECT, elementsToWrite);
}
@Override
public final void writeEndObject() throws IOException {
if (!_cborContext.inObject()) {
_reportError("Current context not Object but "+ _cborContext.typeDesc());
}
closeComplexElement();
_cborContext = _cborContext.getParent();
}
@Override
public void writeArray(int[] array, int offset, int length) throws IOException
{
_verifyOffsets(array.length, offset, length);
_verifyValueWrite("write int array");
_writeLengthMarker(PREFIX_TYPE_ARRAY, length);
if (_cfgMinimalInts) {
for (int i = offset, end = offset+length; i < end; ++i) {
final int value = array[i];
if (value < 0) {
_writeIntMinimal(PREFIX_TYPE_INT_NEG, -value - 1);
} else {
_writeIntMinimal(PREFIX_TYPE_INT_POS, value);
}
}
} else {
for (int i = offset, end = offset+length; i < end; ++i) {
final int value = array[i];
if (value < 0) {
_writeIntFull(PREFIX_TYPE_INT_NEG, -value - 1);
} else {
_writeIntFull(PREFIX_TYPE_INT_POS, value);
}
}
}
}
@Override
public void writeArray(long[] array, int offset, int length) throws IOException
{
_verifyOffsets(array.length, offset, length);
_verifyValueWrite("write int array");
_writeLengthMarker(PREFIX_TYPE_ARRAY, length);
for (int i = offset, end = offset+length; i < end; ++i) {
_writeLongNoCheck(array[i]);
}
}
@Override
public void writeArray(double[] array, int offset, int length) throws IOException
{
_verifyOffsets(array.length, offset, length);
_verifyValueWrite("write int array");
_writeLengthMarker(PREFIX_TYPE_ARRAY, length);
for (int i = offset, end = offset+length; i < end; ++i) {
_writeDoubleNoCheck(array[i]);
}
}
private final void _pushRemainingElements() {
if (_elementCounts.length == _elementCountsPtr) {
_elementCounts = Arrays.copyOf(_elementCounts, _elementCounts.length+10);
}
_elementCounts[_elementCountsPtr++] = _currentRemainingElements;
}
private final void _writeIntMinimal(int markerBase, int i) throws IOException
{
_ensureRoomForOutput(5);
byte b0;
if (i >= 0) {
if (i < 24) {
_outputBuffer[_outputTail++] = (byte) (markerBase + i);
return;
}
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT8_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
return;
}
b0 = (byte) i;
i >>= 8;
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT16_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
return;
}
} else {
b0 = (byte) i;
i >>= 8;
}
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
}
private final void _writeIntFull(int markerBase, int i) throws IOException
{
_ensureRoomForOutput(5);
_outputBuffer[_outputTail++] = (byte) (markerBase + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
private final void _writeLongNoCheck(long l) throws IOException {
if (_cfgMinimalInts) {
if (l >= 0) {
if (l <= 0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_POS, (int) l);
return;
}
} else if (l >= -0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_NEG, (int) (-l - 1));
return;
}
}
_ensureRoomForOutput(9);
if (l < 0L) {
l += 1;
l = -l;
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS);
} else {
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS);
}
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
private final void _writeDoubleNoCheck(double d) throws IOException {
_ensureRoomForOutput(11);
long l = Double.doubleToRawLongBits(d);
_outputBuffer[_outputTail++] = BYTE_FLOAT64;
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
@Override
public void writeString(String text) throws IOException {
if (text == null) {
writeNull();
return;
}
_verifyValueWrite("write String value");
_writeString(text);
}
@Override
public final void writeString(SerializableString sstr) throws IOException {
_verifyValueWrite("write String value");
byte[] raw = sstr.asUnquotedUTF8();
final int len = raw.length;
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeLengthMarker(PREFIX_TYPE_TEXT, len);
_writeBytes(raw, 0, len);
}
@Override
public void writeString(char[] text, int offset, int len)
throws IOException {
_verifyValueWrite("write String value");
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeString(text, offset, len);
}
@Override
public void writeRawUTF8String(byte[] raw, int offset, int len)
throws IOException
{
_verifyValueWrite("write String value");
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
_writeLengthMarker(PREFIX_TYPE_TEXT, len);
_writeBytes(raw, 0, len);
}
@Override
public final void writeUTF8String(byte[] text, int offset, int len)
throws IOException {
writeRawUTF8String(text, offset, len);
}
@Override
public void writeRaw(String text) throws IOException {
throw _notSupported();
}
@Override
public void writeRaw(String text, int offset, int len) throws IOException {
throw _notSupported();
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException {
throw _notSupported();
}
@Override
public void writeRaw(char c) throws IOException {
throw _notSupported();
}
@Override
public void writeRawValue(String text) throws IOException {
throw _notSupported();
}
@Override
public void writeRawValue(String text, int offset, int len)
throws IOException {
throw _notSupported();
}
@Override
public void writeRawValue(char[] text, int offset, int len)
throws IOException {
throw _notSupported();
}
@Override
public void writeBinary(Base64Variant b64variant, byte[] data, int offset,
int len) throws IOException {
if (data == null) {
writeNull();
return;
}
_verifyValueWrite("write Binary value");
_writeLengthMarker(PREFIX_TYPE_BYTES, len);
_writeBytes(data, offset, len);
}
@Override
public int writeBinary(InputStream data, int dataLength) throws IOException {
if (dataLength < 0) {
throw new UnsupportedOperationException(
"Must pass actual length for CBOR encoded data");
}
_verifyValueWrite("write Binary value");
int missing;
_writeLengthMarker(PREFIX_TYPE_BYTES, dataLength);
missing = _writeBytes(data, dataLength);
if (missing > 0) {
_reportError("Too few bytes available: missing " + missing
+ " bytes (out of " + dataLength + ")");
}
return dataLength;
}
@Override
public int writeBinary(Base64Variant b64variant, InputStream data,
int dataLength) throws IOException {
return writeBinary(data, dataLength);
}
@Override
public void writeBoolean(boolean state) throws IOException {
_verifyValueWrite("write boolean value");
if (state) {
_writeByte(BYTE_TRUE);
} else {
_writeByte(BYTE_FALSE);
}
}
@Override
public void writeNull() throws IOException {
_verifyValueWrite("write null value");
_writeByte(BYTE_NULL);
}
@Override
public void writeNumber(int i) throws IOException {
_verifyValueWrite("write number");
int marker;
if (i < 0) {
i = -i - 1;
marker = PREFIX_TYPE_INT_NEG;
} else {
marker = PREFIX_TYPE_INT_POS;
}
_ensureRoomForOutput(5);
byte b0;
if (_cfgMinimalInts) {
if (i < 24) {
_outputBuffer[_outputTail++] = (byte) (marker + i);
return;
}
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT8_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
return;
}
b0 = (byte) i;
i >>= 8;
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT16_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
return;
}
} else {
b0 = (byte) i;
i >>= 8;
}
_outputBuffer[_outputTail++] = (byte) (marker + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
}
@Override
public void writeNumber(long l) throws IOException {
_verifyValueWrite("write number");
if (_cfgMinimalInts) {
if (l >= 0) {
if (l <= 0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_POS, (int) l);
return;
}
} else if (l >= -0x100000000L) {
_writeIntMinimal(PREFIX_TYPE_INT_NEG, (int) (-l - 1));
return;
}
}
_ensureRoomForOutput(9);
if (l < 0L) {
l += 1;
l = -l;
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS);
} else {
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS);
}
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
@Override
public void writeNumber(BigInteger v) throws IOException {
if (v == null) {
writeNull();
return;
}
_verifyValueWrite("write number");
_write(v);
}
protected void _write(BigInteger v) throws IOException {
if (v.signum() < 0) {
_writeByte(BYTE_TAG_BIGNUM_NEG);
v = v.negate();
} else {
_writeByte(BYTE_TAG_BIGNUM_POS);
}
byte[] data = v.toByteArray();
final int len = data.length;
_writeLengthMarker(PREFIX_TYPE_BYTES, len);
_writeBytes(data, 0, len);
}
@Override
public void writeNumber(double d) throws IOException {
_verifyValueWrite("write number");
_ensureRoomForOutput(11);
long l = Double.doubleToRawLongBits(d);
_outputBuffer[_outputTail++] = BYTE_FLOAT64;
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
@Override
public void writeNumber(float f) throws IOException {
_ensureRoomForOutput(6);
_verifyValueWrite("write number");
int i = Float.floatToRawIntBits(f);
_outputBuffer[_outputTail++] = BYTE_FLOAT32;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
@Override
public void writeNumber(BigDecimal dec) throws IOException {
if (dec == null) {
writeNull();
return;
}
_verifyValueWrite("write number");
_writeByte(BYTE_TAG_DECIMAL_FRACTION);
_writeByte(BYTE_ARRAY_2_ELEMENTS);
int scale = dec.scale();
_writeIntValue(-scale);
BigInteger unscaled = dec.unscaledValue();
int bitLength = unscaled.bitLength();
if (bitLength <= 31) {
_writeIntValue(unscaled.intValue());
} else if (bitLength <= 63) {
_writeLongValue(unscaled.longValue());
} else {
_write(unscaled);
}
}
@Override
public void writeNumber(String encodedValue) throws IOException,
JsonGenerationException, UnsupportedOperationException {
writeString(encodedValue);
}
@Override
protected final void _verifyValueWrite(String typeMsg) throws IOException {
if (!_cborContext.writeValue()) {
_reportError("Can not " + typeMsg + ", expecting field name/id");
}
int count = _currentRemainingElements;
if (count != INDEFINITE_LENGTH) {
--count;
if (count < 0) {
_failSizedArrayOrObject();
return;
}
_currentRemainingElements = count;
}
}
private void _failSizedArrayOrObject() throws IOException
{
_reportError(String.format("%s size mismatch: number of element encoded is not equal to reported array/map size.",
_cborContext.typeDesc()));
}
@Override
public final void flush() throws IOException {
_flushBuffer();
if (isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)) {
_out.flush();
}
}
@Override
public void close() throws IOException {
if ((_outputBuffer != null)
&& isEnabled(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT)) {
while (true) {
JsonStreamContext ctxt = getOutputContext();
if (ctxt.inArray()) {
writeEndArray();
} else if (ctxt.inObject()) {
writeEndObject();
} else {
break;
}
}
}
super.close();
_flushBuffer();
if (_ioContext.isResourceManaged()
|| isEnabled(JsonGenerator.Feature.AUTO_CLOSE_TARGET)) {
_out.close();
} else if (isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)) {
_out.flush();
}
_releaseBuffers();
}
public void writeTag(int tagId) throws IOException {
if (tagId < 0) {
throw new IllegalArgumentException(
"Can not write negative tag ids (" + tagId + ")");
}
_writeLengthMarker(PREFIX_TYPE_TAG, tagId);
}
public void writeRaw(byte b) throws IOException {
_writeByte(b);
}
public void writeBytes(byte[] data, int offset, int len) throws IOException {
_writeBytes(data, offset, len);
}
private final static int MAX_SHORT_STRING_CHARS = 23;
private final static int MAX_SHORT_STRING_BYTES = 23 * 3 + 2;
private final static int MAX_MEDIUM_STRING_CHARS = 255;
private final static int MAX_MEDIUM_STRING_BYTES = 255 * 3 + 3;
protected final void _writeString(String name) throws IOException {
int len = name.length();
if (len == 0) {
_writeByte(BYTE_EMPTY_STRING);
return;
}
if (len <= MAX_SHORT_STRING_CHARS) {
_ensureSpace(MAX_SHORT_STRING_BYTES);
int actual = _encode(_outputTail + 1, name, len);
final byte[] buf = _outputBuffer;
int ix = _outputTail;
if (actual <= MAX_SHORT_STRING_CHARS) {
buf[ix++] = (byte) (PREFIX_TYPE_TEXT + actual);
_outputTail = ix + actual;
return;
}
System.arraycopy(buf, ix + 1, buf, ix + 2, actual);
buf[ix++] = BYTE_STRING_1BYTE_LEN;
buf[ix++] = (byte) actual;
_outputTail = ix + actual;
return;
}
char[] cbuf = _charBuffer;
if (len > cbuf.length) {
_charBuffer = cbuf = new char[Math
.max(_charBuffer.length + 32, len)];
}
name.getChars(0, len, cbuf, 0);
_writeString(cbuf, 0, len);
}
protected final void _ensureSpace(int needed) throws IOException {
if ((_outputTail + needed + 3) > _outputEnd) {
_flushBuffer();
}
}
protected final void _writeString(char[] text, int offset, int len)
throws IOException
{
if (len <= MAX_SHORT_STRING_CHARS) {
_ensureSpace(MAX_SHORT_STRING_BYTES);
int actual = _encode(_outputTail + 1, text, offset, offset + len);
final byte[] buf = _outputBuffer;
int ix = _outputTail;
if (actual <= MAX_SHORT_STRING_CHARS) {
buf[ix++] = (byte) (PREFIX_TYPE_TEXT + actual);
_outputTail = ix + actual;
return;
}
System.arraycopy(buf, ix + 1, buf, ix + 2, actual);
buf[ix++] = BYTE_STRING_1BYTE_LEN;
buf[ix++] = (byte) actual;
_outputTail = ix + actual;
return;
}
if (len <= MAX_MEDIUM_STRING_CHARS) {
_ensureSpace(MAX_MEDIUM_STRING_BYTES);
int actual = _encode(_outputTail + 2, text, offset, offset + len);
final byte[] buf = _outputBuffer;
int ix = _outputTail;
if (actual <= MAX_MEDIUM_STRING_CHARS) {
buf[ix++] = BYTE_STRING_1BYTE_LEN;
buf[ix++] = (byte) actual;
_outputTail = ix + actual;
return;
}
System.arraycopy(buf, ix + 2, buf, ix + 3, actual);
buf[ix++] = BYTE_STRING_2BYTE_LEN;
buf[ix++] = (byte) (actual >> 8);
buf[ix++] = (byte) actual;
_outputTail = ix + actual;
return;
}
if (len <= MAX_LONG_STRING_CHARS) {
_ensureSpace(MAX_LONG_STRING_BYTES);
int ix = _outputTail;
int actual = _encode(ix + 3, text, offset, offset+len);
final byte[] buf = _outputBuffer;
buf[ix++] = BYTE_STRING_2BYTE_LEN;
buf[ix++] = (byte) (actual >> 8);
buf[ix++] = (byte) actual;
_outputTail = ix + actual;
return;
}
_writeChunkedString(text, offset, len);
}
protected final void _writeChunkedString(char[] text, int offset, int len)
throws IOException
{
_writeByte(BYTE_STRING_INDEFINITE);
while (len > MAX_LONG_STRING_CHARS) {
_ensureSpace(MAX_LONG_STRING_BYTES);
int ix = _outputTail;
int amount = MAX_LONG_STRING_CHARS;
int end = offset + amount;
char c = text[end-1];
if (c >= SURR1_FIRST && c <= SURR1_LAST) {
--end;
--amount;
}
int actual = _encode(_outputTail + 3, text, offset, end);
final byte[] buf = _outputBuffer;
buf[ix++] = BYTE_STRING_2BYTE_LEN;
buf[ix++] = (byte) (actual >> 8);
buf[ix++] = (byte) actual;
_outputTail = ix + actual;
offset += amount;
len -= amount;
}
if (len > 0) {
_writeString(text, offset, len);
}
_writeByte(BYTE_BREAK);
}
private final int _encode(int outputPtr, char[] str, int i, int end) {
final byte[] outBuf = _outputBuffer;
final int outputStart = outputPtr;
do {
int c = str[i];
if (c > 0x7F) {
return _shortUTF8Encode2(str, i, end, outputPtr, outputStart);
}
outBuf[outputPtr++] = (byte) c;
} while (++i < end);
return outputPtr - outputStart;
}
private final int _shortUTF8Encode2(char[] str, int i, int end,
int outputPtr, int outputStart) {
final byte[] outBuf = _outputBuffer;
while (i < end) {
int c = str[i++];
if (c <= 0x7F) {
outBuf[outputPtr++] = (byte) c;
continue;
}
if (c < 0x800) {
outBuf[outputPtr++] = (byte) (0xc0 | (c >> 6));
outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
continue;
}
if (c < SURR1_FIRST || c > SURR2_LAST) {
outBuf[outputPtr++] = (byte) (0xe0 | (c >> 12));
outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
continue;
}
if ((c <= SURR1_LAST) && (i < end)) {
final int d = str[i];
if ((d <= SURR2_LAST) && (d >= SURR2_FIRST)) {
++i;
outputPtr = _decodeAndWriteSurrogate(c, d, outBuf, outputPtr);
continue;
}
outputPtr = _invalidSurrogateEnd(c, d, outBuf, outputPtr);
continue;
}
outputPtr = _invalidSurrogateStart(c, outBuf, outputPtr);
}
return (outputPtr - outputStart);
}
private final int _encode(int outputPtr, String str, int len) {
final byte[] outBuf = _outputBuffer;
final int outputStart = outputPtr;
for (int i = 0; i < len; ++i) {
int c = str.charAt(i);
if (c > 0x7F) {
return _encode2(i, outputPtr, str, len, outputStart);
}
outBuf[outputPtr++] = (byte) c;
}
return (outputPtr - outputStart);
}
private final int _encode2(int i, int outputPtr, String str, int len,
int outputStart) {
final byte[] outBuf = _outputBuffer;
while (i < len) {
int c = str.charAt(i++);
if (c <= 0x7F) {
outBuf[outputPtr++] = (byte) c;
continue;
}
if (c < 0x800) {
outBuf[outputPtr++] = (byte) (0xc0 | (c >> 6));
outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
continue;
}
if (c < SURR1_FIRST || c > SURR2_LAST) {
outBuf[outputPtr++] = (byte) (0xe0 | (c >> 12));
outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
continue;
}
if ((c <= SURR1_LAST) && (i < len)) {
final int d = str.charAt(i);
if ((d <= SURR2_LAST) && (d >= SURR2_FIRST)) {
++i;
outputPtr = _decodeAndWriteSurrogate(c, d, outBuf, outputPtr);
continue;
}
outputPtr = _invalidSurrogateEnd(c, d, outBuf, outputPtr);
continue;
}
outputPtr = _invalidSurrogateStart(c, outBuf, outputPtr);
}
return (outputPtr - outputStart);
}
private int _invalidSurrogateStart(int code, byte[] outBuf, int outputPtr) {
if (isEnabled(Feature.LENIENT_UTF_ENCODING)) {
return _appendReplacementChar(outBuf, outputPtr);
}
if (code <= SURR1_LAST) {
throw new IllegalArgumentException(String.format(
"Unmatched surrogate pair, starts with valid high surrogate (0x%04X) but ends without low surrogate",
code));
}
throw new IllegalArgumentException(String.format(
"Invalid surrogate pair, starts with invalid high surrogate (0x%04X), not in valid range [0xD800, 0xDBFF]",
code));
}
private int _invalidSurrogateEnd(int surr1, int surr2,
byte[] outBuf, int outputPtr)
{
if (isEnabled(Feature.LENIENT_UTF_ENCODING)) {
return _appendReplacementChar(outBuf, outputPtr);
}
throw new IllegalArgumentException(String.format(
"Invalid surrogate pair, starts with valid high surrogate (0x%04X)"
+" but ends with invalid low surrogate (0x%04X), not in valid range [0xDC00, 0xDFFF]",
surr1, surr2));
}
private int _appendReplacementChar(byte[] outBuf, int outputPtr) {
outBuf[outputPtr++] = (byte) (0xe0 | (REPLACEMENT_CHAR >> 12));
outBuf[outputPtr++] = (byte) (0x80 | ((REPLACEMENT_CHAR >> 6) & 0x3f));
outBuf[outputPtr++] = (byte) (0x80 | (REPLACEMENT_CHAR & 0x3f));
return outputPtr;
}
private int _decodeAndWriteSurrogate(int surr1, int surr2,
byte[] outBuf, int outputPtr)
{
final int c = 0x10000 + ((surr1 - SURR1_FIRST) << 10)
+ (surr2 - SURR2_FIRST);
outBuf[outputPtr++] = (byte) (0xf0 | (c >> 18));
outBuf[outputPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f));
outBuf[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f));
outBuf[outputPtr++] = (byte) (0x80 | (c & 0x3f));
return outputPtr;
}
private final void _ensureRoomForOutput(int needed) throws IOException {
if ((_outputTail + needed) >= _outputEnd) {
_flushBuffer();
}
}
private final void _writeIntValue(int i) throws IOException {
int marker;
if (i < 0) {
i = -i - 1;
marker = PREFIX_TYPE_INT_NEG;
} else {
marker = PREFIX_TYPE_INT_POS;
}
_writeLengthMarker(marker, i);
}
private final void _writeLongValue(long l) throws IOException {
_ensureRoomForOutput(9);
if (l < 0) {
l += 1;
l = -l;
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_NEG + SUFFIX_UINT64_ELEMENTS);
} else {
_outputBuffer[_outputTail++] = (PREFIX_TYPE_INT_POS + SUFFIX_UINT64_ELEMENTS);
}
int i = (int) (l >> 32);
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
i = (int) l;
_outputBuffer[_outputTail++] = (byte) (i >> 24);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
}
private final void _writeLengthMarker(int majorType, int i)
throws IOException {
_ensureRoomForOutput(5);
if (i < 24) {
_outputBuffer[_outputTail++] = (byte) (majorType + i);
return;
}
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (majorType + SUFFIX_UINT8_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
return;
}
final byte b0 = (byte) i;
i >>= 8;
if (i <= 0xFF) {
_outputBuffer[_outputTail++] = (byte) (majorType + SUFFIX_UINT16_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
return;
}
_outputBuffer[_outputTail++] = (byte) (majorType + SUFFIX_UINT32_ELEMENTS);
_outputBuffer[_outputTail++] = (byte) (i >> 16);
_outputBuffer[_outputTail++] = (byte) (i >> 8);
_outputBuffer[_outputTail++] = (byte) i;
_outputBuffer[_outputTail++] = b0;
}
private final void _writeByte(byte b) throws IOException {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = b;
}
private final void _writeBytes(byte[] data, int offset, int len)
throws IOException {
if (len == 0) {
return;
}
if ((_outputTail + len) >= _outputEnd) {
_writeBytesLong(data, offset, len);
return;
}
System.arraycopy(data, offset, _outputBuffer, _outputTail, len);
_outputTail += len;
}
private final int _writeBytes(InputStream in, int bytesLeft)
throws IOException {
while (bytesLeft > 0) {
int room = _outputEnd - _outputTail;
if (room <= 0) {
_flushBuffer();
room = _outputEnd - _outputTail;
}
int count = in.read(_outputBuffer, _outputTail, room);
if (count < 0) {
break;
}
_outputTail += count;
bytesLeft -= count;
}
return bytesLeft;
}
private final void _writeBytesLong(byte[] data, int offset, int len)
throws IOException {
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
while (true) {
int currLen = Math.min(len, (_outputEnd - _outputTail));
System.arraycopy(data, offset, _outputBuffer, _outputTail, currLen);
_outputTail += currLen;
if ((len -= currLen) == 0) {
break;
}
offset += currLen;
_flushBuffer();
}
}
@Override
protected void _releaseBuffers() {
byte[] buf = _outputBuffer;
if (buf != null && _bufferRecyclable) {
_outputBuffer = null;
_ioContext.releaseWriteEncodingBuffer(buf);
}
char[] cbuf = _charBuffer;
if (cbuf != null) {
_charBuffer = null;
_ioContext.releaseConcatBuffer(cbuf);
}
}
protected final void _flushBuffer() throws IOException {
if (_outputTail > 0) {
_bytesWritten += _outputTail;
_out.write(_outputBuffer, 0, _outputTail);
_outputTail = 0;
}
}
private final void closeComplexElement() throws IOException {
switch (_currentRemainingElements) {
case INDEFINITE_LENGTH:
_writeByte(BYTE_BREAK);
break;
case 0:
break;
default:
_reportError(String.format("%s size mismatch: expected %d more elements",
_cborContext.typeDesc(), _currentRemainingElements));
}
_currentRemainingElements = (_elementCountsPtr == 0)
? INDEFINITE_LENGTH
: _elementCounts[--_elementCountsPtr];
}
protected UnsupportedOperationException _notSupported() {
return new UnsupportedOperationException();
}
}