Fix the `equals` method of `JsonPrimitive` to work with `BigInteger` (#2311)

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

* Improve the `equals` & `getAsBigInteger` methods in `JsonPrimitive`
This commit is contained in:
Maicol 2023-02-06 18:40:11 +01:00 committed by GitHub
parent 9f26679e7a
commit af21798436
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 7 deletions

View File

@ -180,8 +180,11 @@ public final class JsonPrimitive extends JsonElement {
*/
@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());
}
/**
@ -282,7 +285,9 @@ public final class JsonPrimitive extends JsonElement {
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();

View File

@ -300,10 +300,8 @@ public class JsonPrimitiveTest {
@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