Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve JsonWriter#value(Number) performance #2702

Merged
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
29 changes: 13 additions & 16 deletions gson/src/main/java/com/google/gson/stream/JsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -638,14 +638,16 @@ public JsonWriter value(Number value) throws IOException {

writeDeferredName();
String string = value.toString();
if (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN")) {
if (strictness != Strictness.LENIENT) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + string);
}
} else {
Class<? extends Number> numberClass = value.getClass();
Class<? extends Number> numberClass = value.getClass();

if (!alwaysCreatesValidJsonNumber(numberClass)) {
// Validate that string is valid before writing it directly to JSON output
if (!isTrustedNumberType(numberClass)
if (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN")) {
if (strictness != Strictness.LENIENT) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + string);
}
} else if (numberClass != Float.class
&& numberClass != Double.class
&& !VALID_JSON_NUMBER_PATTERN.matcher(string).matches()) {
throw new IllegalArgumentException(
"String created by " + numberClass + " is not a valid JSON number: " + string);
Expand Down Expand Up @@ -725,17 +727,12 @@ public void close() throws IOException {
stackSize = 0;
}

/**
* Returns whether the {@code toString()} of {@code c} can be trusted to return a valid JSON
* number.
*/
private static boolean isTrustedNumberType(Class<? extends Number> c) {
// Note: Don't consider LazilyParsedNumber trusted because it could contain
// an arbitrary malformed string
/** Returns whether the {@code toString()} of {@code c} will always return a valid JSON number. */
private static boolean alwaysCreatesValidJsonNumber(Class<? extends Number> c) {
// Does not include Float or Double because their value can be NaN or Infinity
// Does not include LazilyParsedNumber because it could contain a malformed string
return c == Integer.class
|| c == Long.class
|| c == Double.class
|| c == Float.class
|| c == Byte.class
|| c == Short.class
|| c == BigDecimal.class
Expand Down