From d901668e12ab09ee72cf6ab364fe857310d69628 Mon Sep 17 00:00:00 2001 From: Douglas Q Hawkins Date: Sat, 21 Nov 2026 09:37:19 -0500 Subject: [PATCH] Parse decimal numbers from a CharSequence range Adds parseUnsignedLong / parseLong / parseInt overloads to LongStringUtils that take the range [start, end) of a CharSequence and give the same result, or NumberFormatException, as their String counterparts on the same chars (Java 8 has no range-based CharSequence overloads of Long.parseLong / Integer.parseInt). They let a header value be parsed in place, from a view, without making a String first. parseUnsignedLong(String) now shares its 19-20 digit path with the range overload. LongStringUtilsRangeTest compares outcomes with the String parsers on edge cases (signs, Unicode digits, every length boundary, overflow) and on random input. Co-Authored-By: Claude Opus 5.5 --- .../api/internal/util/LongStringUtils.java | 180 +++++++++++++++--- .../util/LongStringUtilsRangeTest.java | 132 +++++++++++++ 2 files changed, 288 insertions(+), 24 deletions(-) create mode 100644 dd-trace-api/src/test/java/datadog/trace/api/internal/util/LongStringUtilsRangeTest.java diff --git a/dd-trace-api/src/main/java/datadog/trace/api/internal/util/LongStringUtils.java b/dd-trace-api/src/main/java/datadog/trace/api/internal/util/LongStringUtils.java index 99fd19709d1..8b202c4bf2f 100644 --- a/dd-trace-api/src/main/java/datadog/trace/api/internal/util/LongStringUtils.java +++ b/dd-trace-api/src/main/java/datadog/trace/api/internal/util/LongStringUtils.java @@ -133,38 +133,170 @@ public static long parseUnsignedLong(String s) throws NumberFormatException { } else { if (len <= 18) { // Signed 64 bits max is 19 digits, so this always fits return Long.parseLong(s); - } else if (len > 20) { // Unsigned 64 bits max is 20 digits, so this always overflows - throw numberFormatOutOfLongRange(s); } - // Now do the first part and the last character - long first = 0; - int ok = 0; - for (int i = 0; i < len - 1; i++) { - char c = s.charAt(i); - int d = Character.digit(c, 10); - ok |= d; - first = first * 10 + d; - } - int last = Character.digit(s.charAt(len - 1), 10); - ok |= last; - if (ok < 0) { - throw new NumberFormatException("Illegal character in " + s); - } - if (Long.compareUnsigned(first, MAX_FIRST_PART) > 0) { - throw numberFormatOutOfLongRange(s); - } - long guard = first * 10; - long result = guard + last; - if (guard < 0 && result >= 0) { - throw numberFormatOutOfLongRange(s); + return parseLongUnsignedDigits(s, 0, len); + } + } else { + throw new NumberFormatException("Empty input string"); + } + } + + /** + * {@link #parseUnsignedLong(String)} for the chars {@code [start, end)} of {@code s}: the same + * result, or a {@code NumberFormatException}, as for the same chars in a {@code String}, without + * making one. + */ + public static long parseUnsignedLong(CharSequence s, int start, int end) + throws NumberFormatException { + if (s == null) { + throw new NumberFormatException("s can't be null"); + } + + int len = end - start; + if (len > 0) { + char firstChar = s.charAt(start); + if (firstChar == '-') { + throw new NumberFormatException( + String.format( + Locale.ROOT, + "Illegal leading minus sign on unsigned string %s.", + s.subSequence(start, end))); + } else { + if (len <= 18) { // Signed 64 bits max is 19 digits, so this always fits + return parseLong(s, start, end); } - return result; + return parseLongUnsignedDigits(s, start, end); } } else { throw new NumberFormatException("Empty input string"); } } + /** The 19 or more digits {@code [start, end)} of {@code s} as an unsigned long. */ + private static long parseLongUnsignedDigits(CharSequence s, int start, int end) { + int len = end - start; + if (len > 20) { // Unsigned 64 bits max is 20 digits, so this always overflows + throw numberFormatOutOfLongRange(s.subSequence(start, end)); + } + // Now do the first part and the last character + long first = 0; + int ok = 0; + for (int i = start; i < end - 1; i++) { + char c = s.charAt(i); + int d = Character.digit(c, 10); + ok |= d; + first = first * 10 + d; + } + int last = Character.digit(s.charAt(end - 1), 10); + ok |= last; + if (ok < 0) { + throw new NumberFormatException("Illegal character in " + s.subSequence(start, end)); + } + if (Long.compareUnsigned(first, MAX_FIRST_PART) > 0) { + throw numberFormatOutOfLongRange(s.subSequence(start, end)); + } + long guard = first * 10; + long result = guard + last; + if (guard < 0 && result >= 0) { + throw numberFormatOutOfLongRange(s.subSequence(start, end)); + } + return result; + } + + /** + * {@link Long#parseLong(String)} for the chars {@code [start, end)} of {@code s}, in base 10: the + * same result, or a {@code NumberFormatException}, as for the same chars in a {@code String}. + * Java 8 has no range-based {@code CharSequence} overload. + */ + public static long parseLong(CharSequence s, int start, int end) throws NumberFormatException { + if (s == null) { + throw new NumberFormatException("s can't be null"); + } + if (start >= end) { + throw new NumberFormatException("Empty input string"); + } + boolean negative = false; + long limit = -Long.MAX_VALUE; + int i = start; + char firstChar = s.charAt(i); + if (firstChar < '0') { // possible leading "+" or "-" + if (firstChar == '-') { + negative = true; + limit = Long.MIN_VALUE; + } else if (firstChar != '+') { + throw forInput(s, start, end); + } + if (end - start == 1) { // a lone "+" or "-" + throw forInput(s, start, end); + } + i++; + } + long multmin = limit / 10; + long result = 0; + while (i < end) { + // Accumulating negatively avoids surprises near MAX_VALUE + int digit = Character.digit(s.charAt(i++), 10); + if (digit < 0 || result < multmin) { + throw forInput(s, start, end); + } + result *= 10; + if (result < limit + digit) { + throw forInput(s, start, end); + } + result -= digit; + } + return negative ? result : -result; + } + + /** + * {@link Integer#parseInt(String)} for the chars {@code [start, end)} of {@code s}: the same + * result, or a {@code NumberFormatException}, as for the same chars in a {@code String}. Java 8 + * has no range-based {@code CharSequence} overload. + */ + public static int parseInt(CharSequence s, int start, int end) throws NumberFormatException { + if (s == null) { + throw new NumberFormatException("s can't be null"); + } + if (start >= end) { + throw new NumberFormatException("Empty input string"); + } + boolean negative = false; + int limit = -Integer.MAX_VALUE; + int i = start; + char firstChar = s.charAt(i); + if (firstChar < '0') { // possible leading "+" or "-" + if (firstChar == '-') { + negative = true; + limit = Integer.MIN_VALUE; + } else if (firstChar != '+') { + throw forInput(s, start, end); + } + if (end - start == 1) { // a lone "+" or "-" + throw forInput(s, start, end); + } + i++; + } + int multmin = limit / 10; + int result = 0; + while (i < end) { + // Accumulating negatively avoids surprises near MAX_VALUE + int digit = Character.digit(s.charAt(i++), 10); + if (digit < 0 || result < multmin) { + throw forInput(s, start, end); + } + result *= 10; + if (result < limit + digit) { + throw forInput(s, start, end); + } + result -= digit; + } + return negative ? result : -result; + } + + private static NumberFormatException forInput(CharSequence s, int start, int end) { + return new NumberFormatException("For input string: \"" + s.subSequence(start, end) + "\""); + } + /** * Creates a {@code NumberFormatException} with a consistent error message. * diff --git a/dd-trace-api/src/test/java/datadog/trace/api/internal/util/LongStringUtilsRangeTest.java b/dd-trace-api/src/test/java/datadog/trace/api/internal/util/LongStringUtilsRangeTest.java new file mode 100644 index 00000000000..fa2e26f2b9a --- /dev/null +++ b/dd-trace-api/src/test/java/datadog/trace/api/internal/util/LongStringUtilsRangeTest.java @@ -0,0 +1,132 @@ +package datadog.trace.api.internal.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Random; +import java.util.concurrent.Callable; +import org.junit.jupiter.api.Test; + +/** + * The range-based {@code CharSequence} parsers give the same result, or a {@code + * NumberFormatException}, as their {@code String} counterparts on the same chars. + */ +class LongStringUtilsRangeTest { + + private static final String[] EDGES = { + "", + "0", + "+", + "-", + "+0", + "-0", + "00", + "007", + "-1", + "+1", + "++1", + "1+", + " 1", + "1 ", + "a", + "12a4", + "٣", // ARABIC-INDIC DIGIT THREE, a digit to Character.digit + "1٠2", + "2147483647", + "2147483648", + "-2147483648", + "-2147483649", + "+2147483647", + "9223372036854775807", + "9223372036854775808", + "-9223372036854775808", + "-9223372036854775809", + "+9223372036854775807", + "999999999999999999", + "1000000000000000000", + "18446744073709551615", + "18446744073709551616", + "28446744073709551615", + "00000000000000000001", + "000000000000000000001", + "+8446744073709551615", + "1844674407370955161a", + "184467440737095516150", + }; + + /** The outcome of a parse: its value, or "NFE". */ + private static String outcome(Callable parse) { + try { + return String.valueOf(parse.call()); + } catch (NumberFormatException e) { + return "NFE"; + } catch (Exception e) { + throw new AssertionError(e); + } + } + + private static void assertSameOutcomes(String s) { + // embedded in a non-String CharSequence, with chars around it + StringBuilder padded = new StringBuilder("x9").append(s).append("7y"); + int start = 2; + int end = 2 + s.length(); + assertEquals( + outcome(() -> Long.parseLong(s)), + outcome(() -> LongStringUtils.parseLong(padded, start, end)), + () -> "parseLong '" + s + "'"); + assertEquals( + outcome(() -> Integer.parseInt(s)), + outcome(() -> LongStringUtils.parseInt(padded, start, end)), + () -> "parseInt '" + s + "'"); + assertEquals( + outcome(() -> LongStringUtils.parseUnsignedLong(s)), + outcome(() -> LongStringUtils.parseUnsignedLong(padded, start, end)), + () -> "parseUnsignedLong '" + s + "'"); + } + + @Test + void matchesTheStringParsersOnEdgeCases() { + for (String edge : EDGES) { + assertSameOutcomes(edge); + } + } + + @Test + void matchesTheStringParsersOnRandomInput() { + char[] alphabet = {'0', '1', '5', '9', '+', '-', 'a', ' ', '٣'}; + Random random = new Random(42); + for (int run = 0; run < 50_000; run++) { + int length = random.nextInt(22); + StringBuilder s = new StringBuilder(); + for (int i = 0; i < length; i++) { + // mostly digits, so values near every length boundary come up + s.append( + random.nextInt(6) == 0 + ? alphabet[random.nextInt(alphabet.length)] + : (char) ('0' + random.nextInt(10))); + } + assertSameOutcomes(s.toString()); + } + } + + @Test + void matchesOnRandomNumbersOfEveryMagnitude() { + Random random = new Random(7); + for (int run = 0; run < 20_000; run++) { + long value = random.nextLong() >>> random.nextInt(64); + assertSameOutcomes(Long.toUnsignedString(value)); + assertSameOutcomes(Long.toString(value)); + assertSameOutcomes(Long.toString(-value)); + assertSameOutcomes(Integer.toString((int) value)); + } + } + + @Test + void rejectsNullAndEmptyRanges() { + assertThrows(NumberFormatException.class, () -> LongStringUtils.parseLong(null, 0, 0)); + assertThrows(NumberFormatException.class, () -> LongStringUtils.parseInt(null, 0, 0)); + assertThrows(NumberFormatException.class, () -> LongStringUtils.parseUnsignedLong(null, 0, 0)); + assertThrows(NumberFormatException.class, () -> LongStringUtils.parseLong("123", 1, 1)); + assertThrows(NumberFormatException.class, () -> LongStringUtils.parseInt("123", 2, 1)); + } +}