Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/main/java/com/amazon/ion/impl/IonCursorBinary.java
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,19 @@ private long slowReadVarUInt_1_0() {
throw new IonException("Found a VarUInt that was too large to fit in a `long`");
}

/**
* Narrows the given symbol ID to an `int`, throwing if it does not fit. A symbol ID that does not fit in an `int`
* can never be mapped by a symbol table; wrapping it around would silently resolve it to a different symbol.
* @param sid the symbol ID.
* @return the symbol ID as an `int`.
*/
static int symbolIdToInt(long sid) {
if (sid < 0 || sid > Integer.MAX_VALUE) {
throw new IonException("Found a symbol ID that was too large to fit in an `int`.");
}
return (int) sid;
}

/**
* Reads the header of an annotation wrapper. This must only be called when it is known that the buffer already
* contains all the bytes in the header. Sets `valueMarker` with the start and end indices of the wrapped value.
Expand Down Expand Up @@ -976,8 +989,12 @@ private boolean slowReadFieldName_1_0() {
if (!fillAt(peekIndex, 2)) {
return true;
}
fieldSid = (int) slowReadVarUInt_1_0();
return fieldSid < 0;
long sid = slowReadVarUInt_1_0();
if (sid < 0) {
return true;
}
fieldSid = symbolIdToInt(sid);
return false;
}

/* ---- Ion 1.1 ---- */
Expand Down Expand Up @@ -1571,7 +1588,7 @@ private boolean uncheckedNextContainedToken() {
if (b < 0) {
fieldSid = (b & LOWER_SEVEN_BITS_BITMASK);
} else {
fieldSid = (int) uncheckedReadVarUInt_1_0(b);
fieldSid = symbolIdToInt(uncheckedReadVarUInt_1_0(b));
}
} else {
uncheckedReadFieldName_1_1();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ class IonReaderContinuableCoreBinary extends IonCursorBinary implements IonReade
// The second-most significant bit in the most significant byte of a VarInt is the sign.
private static final int VAR_INT_SIGN_BITMASK = 0x40;

// The largest VarInt magnitude that can be decoded. This allows -2^31 (Integer.MIN_VALUE) as well as the
// exponent 2^31, which corresponds to a BigDecimal scale of Integer.MIN_VALUE.
private static final long MAXIMUM_VAR_INT_MAGNITUDE = -(long) Integer.MIN_VALUE;

// 32-bit floats must declare length 4.
private static final int FLOAT_32_BYTE_LENGTH = 4;

Expand Down Expand Up @@ -160,6 +164,9 @@ int readVarUInt_1_0() {
throw new IonException("Malformed data: declared length exceeds the number of bytes remaining in the stream.");
}
currentByte = buffer[(int)(peekIndex++)];
if (result > (Integer.MAX_VALUE >>> VALUE_BITS_PER_VARUINT_BYTE)) {
throw new IonException("Found a VarUInt that was too large to fit in an `int`.");
}
result = (result << VALUE_BITS_PER_VARUINT_BYTE) | (currentByte & LOWER_SEVEN_BITS_BITMASK);
}
return result;
Expand All @@ -168,33 +175,51 @@ int readVarUInt_1_0() {
/**
* Reads a 2+ byte VarInt, given the first byte. When called, `peekIndex` must point at the second byte in the
* VarInt. at `peekIndex`.When this method returns, `peekIndex` will point at the first byte that follows the
* VarInt. NOTE: the VarInt must fit in an `int`.
* VarInt. NOTE: the magnitude of the VarInt must not exceed `MAXIMUM_VAR_INT_MAGNITUDE`; callers must check that
* the value fits in an `int` before narrowing it.
* @param firstByte the first byte of the VarInt representation, which has already been retrieved from the buffer.
* @return the value.
*/
private int readVarInt_1_0(int firstByte) {
private long readVarInt_1_0(int firstByte) {
int currentByte = firstByte;
int sign = (currentByte & VAR_INT_SIGN_BITMASK) == 0 ? 1 : -1;
int result = currentByte & LOWER_SIX_BITS_BITMASK;
long result = currentByte & LOWER_SIX_BITS_BITMASK;
while ((currentByte & HIGHEST_BIT_BITMASK) == 0) {
if (peekIndex >= limit) {
throw new IonException("Malformed data: declared length exceeds the number of bytes remaining in the stream.");
}
currentByte = buffer[(int)(peekIndex++)];
result = (result << VALUE_BITS_PER_VARUINT_BYTE) | (currentByte & LOWER_SEVEN_BITS_BITMASK);
if (result > MAXIMUM_VAR_INT_MAGNITUDE) {
throw new IonException("Found a VarInt that was too large to fit in an `int`.");
}
}
return result * sign;
}

/**
* Reads the VarInt starting at `peekIndex`. When this method returns, `peekIndex` will point at the first byte
* that follows the VarUInt. NOTE: the VarInt must fit in an `int`.
* that follows the VarUInt. NOTE: the magnitude of the VarInt must not exceed `MAXIMUM_VAR_INT_MAGNITUDE`;
* callers must check that the value fits in an `int` before narrowing it.
* @return the value.
*/
private int readVarInt_1_0() {
private long readVarInt_1_0() {
return readVarInt_1_0(buffer[(int)(peekIndex++)]);
}

/**
* Reads the VarInt exponent of the decimal that begins at `peekIndex` and negates it to produce the scale of the
* decimal. When this method returns, `peekIndex` will point at the first byte of the decimal's coefficient.
* @return the scale.
*/
private int readDecimalScale_1_0() {
long scale = -readVarInt_1_0();
if (scale < Integer.MIN_VALUE || scale > Integer.MAX_VALUE) {
throw new IonException("Found a decimal exponent that was too large to fit in an `int`.");
}
return (int) scale;
}

/**
* Reads into a BigInteger the UInt value that begins at `valueMarker.startIndex` and ends at
* `valueMarker.endIndex`.
Expand Down Expand Up @@ -250,7 +275,7 @@ private BigInteger readIntAsBigInteger_1_0(int length) {
* @return the value.
*/
private BigDecimal readBigDecimal_1_0() {
int scale = -readVarInt_1_0();
int scale = readDecimalScale_1_0();
BigDecimal value;
int length = (int) (valueMarker.endIndex - peekIndex);
if (length < LONG_SIZE_IN_BYTES) {
Expand Down Expand Up @@ -278,7 +303,7 @@ private BigDecimal readBigDecimal_1_0() {
* @return the value.
*/
private Decimal readDecimal_1_0() {
int scale = -readVarInt_1_0();
int scale = readDecimalScale_1_0();
BigInteger coefficient;
int length = (int) (valueMarker.endIndex - peekIndex);
if (length > 0) {
Expand Down Expand Up @@ -338,7 +363,11 @@ private Timestamp readTimestamp_1_0() {
int firstByte = buffer[(int)(peekIndex++)] & SINGLE_BYTE_MASK;
Integer offset = null;
if (firstByte != VAR_INT_NEGATIVE_ZERO) {
offset = readVarInt_1_0(firstByte);
long offsetMinutes = readVarInt_1_0(firstByte);
if (offsetMinutes < Integer.MIN_VALUE || offsetMinutes > Integer.MAX_VALUE) {
throw new IonException("Found a timestamp offset that was too large to fit in an `int`.");
}
offset = (int) offsetMinutes;
}
int year = readVarUInt_1_0();
int month = 0;
Expand Down Expand Up @@ -796,7 +825,15 @@ public int symbolValueId() {
return -1;
}
prepareScalar();
return (int) readUInt(valueMarker.startIndex, valueMarker.endIndex);
// Skip any leading zero-padding bytes, which do not contribute to the magnitude.
long startIndex = valueMarker.startIndex;
while (startIndex < valueMarker.endIndex && buffer[(int) startIndex] == 0) {
startIndex++;
}
if (valueMarker.endIndex - startIndex > Integer.BYTES) {
throw new IonException("Found a symbol ID that was too large to fit in an `int`.");
}
return symbolIdToInt(readUInt(startIndex, valueMarker.endIndex));
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/amazon/ion/impl/bin/IonRawBinaryWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -1041,7 +1041,7 @@ private void writeDecimalValue(final BigDecimal value)
{
final boolean isNegZero = isNegativeZero(value);
final int signum = value.signum();
final int exponent = -value.scale();
final long exponent = -(long) value.scale();

writeVarInt(exponent);

Expand Down Expand Up @@ -1234,7 +1234,7 @@ public void writeTimestamp(final Timestamp value) throws IOException
final BigDecimal fraction = value.getZFractionalSecond();
if (fraction != null) {
final BigInteger mantissaBigInt = fraction.unscaledValue();
final int exponent = -fraction.scale();
final long exponent = -(long) fraction.scale();
if (!(mantissaBigInt.equals(BigInteger.ZERO) && exponent > -1)) {
writeDecimalValue(fraction);
}
Expand Down
35 changes: 8 additions & 27 deletions src/main/java/com/amazon/ion/impl/lite/ReverseBinaryEncoder.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
/*
* Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.ion.impl.lite;

import static com.amazon.ion.SymbolTable.UNKNOWN_SYMBOL_ID;
Expand Down Expand Up @@ -527,13 +514,13 @@ else if (v < (1 << (7 * 4))) // 4 bytes - 28 bits used - 0xfffffff max
* sign flag in the first octet of the representation, but part of the
* extension bits for all other octets.
* <p>
* Writes at least one byte, even for zero values. int parameter is enough
* as the scalar and container writers do not have APIs that return long or
* BigInteger representations.
* Writes at least one byte, even for zero values. The magnitude of the
* value must not exceed 2^31, which allows the exponent of a decimal whose
* scale is {@link Integer#MIN_VALUE}.
*
* @param v
*/
private void writeVarInt(int v)
private void writeVarInt(long v)
{
if (v == 0)
{
Expand All @@ -546,9 +533,6 @@ private void writeVarInt(int v)
boolean is_negative = (v < 0);
if (is_negative)
{
// note that for Integer.MIN_VALUE (0x80000000) the negative
// is the same, but that's also the bit pattern we need to
// write out - so no worries
v = -v;
}

Expand Down Expand Up @@ -594,15 +578,12 @@ else if (v < (1 << (7 * 4 - 1))) // 4 bytes - 27 bits used - 0x7ffffff max
myBuffer[offset + 2] = (byte) ((v >>> (7 * 1)) & 0x7f);
myBuffer[offset + 3] = (byte) ( v | 0x80);
}
else // 5 bytes - 31 bits used - 0x7fffffff max (Integer.MAX_VALUE)
else // 5 bytes - 34 bits available; magnitude is at most 2^31
{
if ((offset -= 5) < 0) {
offset = growBuffer(offset);
}

// This is different from the previous if-blocks because we
// cannot represent a int with more than 32 bits to perform
// the "OR-assignment" (|=).
myBuffer[offset] = (byte) ((v >>> (7 * 4)) & 0x7f);
if (is_negative) {
myBuffer[offset] |= 0x40;
Expand Down Expand Up @@ -840,7 +821,7 @@ private void writeIonDecimalContent(BigDecimal bd)
writeBytes(mantissaBits);

// Ion stores exponent, BigDecimal uses the negation 'scale' instead
int exponent = -bd.scale();
long exponent = -(long) bd.scale();
writeVarInt(exponent);
}

Expand Down
34 changes: 19 additions & 15 deletions src/test/java/com/amazon/ion/DatagramTest.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
/*
* Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.ion;

import static com.amazon.ion.SymbolTable.UNKNOWN_SYMBOL_ID;
Expand All @@ -28,6 +15,8 @@
import com.amazon.ion.impl._Private_IonValue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Iterator;
Expand Down Expand Up @@ -744,4 +733,19 @@ public void modifySymbolsAfterLoadThenSerialize()
assertEquals("abc", annotations[1]);
}
}

@Test
public void testGetBytesWithDecimalScaleAtIntBoundaries()
{
assertDecimalWithScaleRoundTripsThroughGetBytes(Integer.MIN_VALUE);
assertDecimalWithScaleRoundTripsThroughGetBytes(Integer.MAX_VALUE);
}

private void assertDecimalWithScaleRoundTripsThroughGetBytes(int scale)
{
BigDecimal expected = new BigDecimal(BigInteger.ONE, scale);
IonDatagram datagram = system().newDatagram(system().newDecimal(expected));
IonDatagram actual = myLoader.load(datagram.getBytes());
assertEquals(expected, ((IonDecimal) actual.get(0)).bigDecimalValue());
}
}
Loading
Loading