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
3 changes: 3 additions & 0 deletions release-notes/VERSION
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ Project: Stax2 API

4.3.2 (not yet released)

#51: Fast path for BigInteger decoding
(contributed by @winfriedgerlach)

4.3.1 (27-Sep-2026)

#41: Fix `ValueEncoderFactory.getScalarEncoder()` fails for long values
Expand Down
125 changes: 125 additions & 0 deletions src/main/java/org/codehaus/stax2/ri/typed/ValueDecoderFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,24 @@ public abstract static class DecoderBase

static final BigInteger BD_MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
static final BigInteger BD_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);

/**
* Value returned by {@code tryParseLong} for values it does not handle
* (it is never returned for handled values, as {@link Long#MIN_VALUE}
* itself is not handled)
*
* @since 4.3.2
*/
protected static final long NOT_A_LONG = Long.MIN_VALUE;

/**
* Max. number of digits (after leading zeroes) {@code tryParseLong}
* handles: same as for {@link Long#MAX_VALUE}
*/
static final int MAX_LONG_DIGITS = 19;

static final long MAX_LONG_DIV_10 = Long.MAX_VALUE / 10;
static final int MAX_LONG_LAST_DIGIT = (int) (Long.MAX_VALUE % 10);

/**
* Pointer to the next character to check, within lexical value
Expand Down Expand Up @@ -452,6 +470,101 @@ protected static final long parseLong(String digitChars, int start, int end)
return val + parseInt(digitChars, start2, end);
}

/**
* Non-throwing variant of {@code long} parsing, for decoders that
* have a more general (and slower) fallback: handles an optional sign
* followed by ASCII digits (leading zeroes are skipped), for any value
* that fits in a {@code long} except for {@link Long#MIN_VALUE}.
* Anything else, including invalid values, is left to the caller.
*
* @return Parsed value, or {@link #NOT_A_LONG} if value was not handled
*
* @since 4.3.2
*/
protected static final long tryParseLong(String lexical, int ptr, final int end)
{
if (ptr >= end) {
return NOT_A_LONG;
}
char ch = lexical.charAt(ptr);
final boolean neg = (ch == '-');
if (neg || ch == '+') {
if (++ptr == end) {
return NOT_A_LONG;
}
}
// Skip leading zeroes (but not the last digit, for value zero)
final int last = end-1;
while (ptr < last && lexical.charAt(ptr) == '0') {
++ptr;
}
if ((end - ptr) > MAX_LONG_DIGITS) {
return NOT_A_LONG;
}
long value = 0L;
for (; ptr < last; ++ptr) {
int digit = lexical.charAt(ptr) - '0';
if (digit < 0 || digit > 9) {
return NOT_A_LONG;
}
value = (value * 10) + digit;
}
return lastLongDigit(value, lexical.charAt(last) - '0', neg);
}

/**
* @see #tryParseLong(String, int, int)
*
* @since 4.3.2
*/
protected static final long tryParseLong(char[] lexical, int ptr, final int end)
{
if (ptr >= end) {
return NOT_A_LONG;
}
char ch = lexical[ptr];
final boolean neg = (ch == '-');
if (neg || ch == '+') {
if (++ptr == end) {
return NOT_A_LONG;
}
}
// Skip leading zeroes (but not the last digit, for value zero)
final int last = end-1;
while (ptr < last && lexical[ptr] == '0') {
++ptr;
}
if ((end - ptr) > MAX_LONG_DIGITS) {
return NOT_A_LONG;
}
long value = 0L;
for (; ptr < last; ++ptr) {
int digit = lexical[ptr] - '0';
if (digit < 0 || digit > 9) {
return NOT_A_LONG;
}
value = (value * 10) + digit;
}
return lastLongDigit(value, lexical[last] - '0', neg);
}

/**
* Helper method for {@code tryParseLong}: appends the last digit,
* which is the only one that can overflow (with up to 19 digits)
*/
private static long lastLongDigit(long value, int digit, boolean neg)
{
if (digit < 0 || digit > 9) {
return NOT_A_LONG;
}
if (value >= MAX_LONG_DIV_10
&& (value > MAX_LONG_DIV_10 || digit > MAX_LONG_LAST_DIGIT)) {
return NOT_A_LONG;
}
value = (value * 10) + digit;
return neg ? -value : value;
}

/*
///////////////////////////////////////////////
// Shared methods, error reporting
Expand Down Expand Up @@ -1028,6 +1141,13 @@ public IntegerDecoder() { }
@Override
public void decode(String lexical) throws IllegalArgumentException
{
// Fast path for values that fit in a long; anything else (including
// reporting of invalid values) is left to BigInteger
long l = tryParseLong(lexical, 0, lexical.length());
if (l != NOT_A_LONG) {
mValue = BigInteger.valueOf(l);
return;
}
try {
mValue = new BigInteger(lexical);
} catch (NumberFormatException nex) {
Expand All @@ -1038,6 +1158,11 @@ public void decode(String lexical) throws IllegalArgumentException
@Override
public void decode(char[] lexical, int start, int end) throws IllegalArgumentException
{
long l = tryParseLong(lexical, start, end);
if (l != NOT_A_LONG) {
mValue = BigInteger.valueOf(l);
return;
}
String lexicalStr = new String(lexical, start, (end-start));
try {
mValue = new BigInteger(lexicalStr);
Expand Down
125 changes: 125 additions & 0 deletions src/test/java/org/codehaus/stax2/ri/typed/BigIntegerDecoderTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package org.codehaus.stax2.ri.typed;

import java.math.BigInteger;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Tests for {@link ValueDecoderFactory.IntegerDecoder}: values that fit in a {@code long} take a fast path
* ({@link ValueDecoderFactory.DecoderBase#tryParseLong}), which must give the same results as
* {@link BigInteger#BigInteger(String)}, like all other values.
*/
class BigIntegerDecoderTest
{
private static final long NOT_A_LONG = ValueDecoderFactory.DecoderBase.NOT_A_LONG;

// Values handled by the fast path
private static final String[] VALID_LONG = {
"0", "-0", "+0", "5", "+5", "-5", "007", "-007", "42",
"2147483648", "-2147483649",
"999999999999999999", "-999999999999999999", "+100000000000000000",
// 19 digits, up to Long.MAX_VALUE
"1000000000000000000", "9223372036854775807", "-9223372036854775807",
// leading zeroes do not count towards max. digits
"0000000000000000000042", "-000000000000000000000000000001", "00000000000000000000000",
"0009223372036854775807"
};

// Valid values left to BigInteger
private static final String[] VALID_NOT_LONG = {
// overflow on last digit
"9223372036854775808", "-9223372036854775808", "9223372036854775810",
"9999999999999999999", "10000000000000000000",
"123456789012345678901234567890"
};

private static final String[] INVALID = {
"", "-", "+", "--1", "+-1", "1a", "a1", "1.5", "1e3", "1 2", " 1", "1 ", "0x10", "00-1"
};

@Test
void tryParseLong()
{
for (String value : VALID_LONG) {
long expected = Long.parseLong(value);
assertEquals(expected, ValueDecoderFactory.DecoderBase.tryParseLong(value, 0, value.length()), value);
char[] buf = pad(value);
assertEquals(expected, ValueDecoderFactory.DecoderBase.tryParseLong(buf, 2, buf.length - 2), value);
}
for (String[] values : new String[][] { VALID_NOT_LONG, INVALID }) {
for (String value : values) {
assertEquals(NOT_A_LONG, ValueDecoderFactory.DecoderBase.tryParseLong(value, 0, value.length()), value);
char[] buf = pad(value);
assertEquals(NOT_A_LONG, ValueDecoderFactory.DecoderBase.tryParseLong(buf, 2, buf.length - 2), value);
}
}
}

@Test
void decodeValidString()
{
for (String[] values : new String[][] { VALID_LONG, VALID_NOT_LONG }) {
for (String value : values) {
ValueDecoderFactory.IntegerDecoder decoder = newDecoder();
decoder.decode(value);
assertEquals(new BigInteger(value), decoder.getValue(), value);
}
}
}

@Test
void decodeValidCharArray()
{
for (String[] values : new String[][] { VALID_LONG, VALID_NOT_LONG }) {
for (String value : values) {
ValueDecoderFactory.IntegerDecoder decoder = newDecoder();
char[] buf = pad(value);
decoder.decode(buf, 2, buf.length - 2);
assertEquals(new BigInteger(value), decoder.getValue(), value);
}
}
}

@Test
void decodeInvalidString()
{
for (String value : INVALID) {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> newDecoder().decode(value), value);
assertTrue(e.getMessage().contains("not a valid lexical representation of integer"), e.getMessage());
}
}

@Test
void decodeInvalidCharArray()
{
for (String value : INVALID) {
char[] buf = pad(value);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> newDecoder().decode(buf, 2, buf.length - 2), value);
assertTrue(e.getMessage().contains("not a valid lexical representation of integer"), e.getMessage());
}
}

@Test
void decodeInvertedRange()
{
// Must not be decoded as an (empty) zero value
assertThrows(IndexOutOfBoundsException.class,
() -> newDecoder().decode("12345".toCharArray(), 4, 2));
}

private static ValueDecoderFactory.IntegerDecoder newDecoder() {
return new ValueDecoderFactory().getIntegerDecoder();
}

// Decoded range is not at the start or end of the array; padding with digits so reading outside
// of the range gives a wrong value, instead of falling back to BigInteger
private static char[] pad(String value) {
return ("12" + value + "34").toCharArray();
}
}
Loading