Skip to content

Commit

Permalink
Fix the equals method of JsonPrimitive to work with BigInteger (#…
Browse files Browse the repository at this point in the history
…2311)

* Fix the `equals` method of `JsonPrimitive` to work with BigInteger

* Improve the `equals` & `getAsBigInteger` methods in `JsonPrimitive`
  • Loading branch information
MaicolAntali authored Feb 6, 2023
1 parent 9f26679 commit af21798
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
11 changes: 8 additions & 3 deletions gson/src/main/java/com/google/gson/JsonPrimitive.java
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,11 @@ public BigDecimal getAsBigDecimal() {
*/
@Override
public BigInteger getAsBigInteger() {
return value instanceof BigInteger ?
(BigInteger) value : new BigInteger(getAsString());
return value instanceof BigInteger
? (BigInteger) value
: isIntegral(this)
? BigInteger.valueOf(this.getAsNumber().longValue())
: new BigInteger(this.getAsString());
}

/**
Expand Down Expand Up @@ -282,7 +285,9 @@ public boolean equals(Object obj) {
return other.value == null;
}
if (isIntegral(this) && isIntegral(other)) {
return getAsNumber().longValue() == other.getAsNumber().longValue();
return this.value instanceof BigInteger || other.value instanceof BigInteger
? this.getAsBigInteger().equals(other.getAsBigInteger())
: this.getAsNumber().longValue() == other.getAsNumber().longValue();
}
if (value instanceof Number && other.value instanceof Number) {
double a = getAsNumber().doubleValue();
Expand Down
6 changes: 2 additions & 4 deletions gson/src/test/java/com/google/gson/JsonPrimitiveTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -300,10 +300,8 @@ public void testEqualsAcrossTypes() {
@Test
public void testEqualsIntegerAndBigInteger() {
JsonPrimitive a = new JsonPrimitive(5L);
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5
// Ideally, the following assertion should have failed but the price is too much to pay
// assertFalse(a + " equals " + b, a.equals(b));
assertWithMessage("%s equals %s", a, b).that(a.equals(b)).isTrue();
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621"));
assertWithMessage("%s not equals %s", a, b).that(a.equals(b)).isFalse();
}

@Test
Expand Down

0 comments on commit af21798

Please sign in to comment.