Skip to content

Commit

Permalink
Avoid precision loss in DocValueFormat.RAW#parseLong (#49063) (#49169)
Browse files Browse the repository at this point in the history
  • Loading branch information
not-napoleon authored Nov 15, 2019
1 parent aa4d86c commit dad68c5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ public String format(BytesRef value) {

@Override
public long parseLong(String value, boolean roundUp, LongSupplier now) {
try {
// Prefer parsing as a long to avoid losing precision
return Long.parseLong(value);
} catch (NumberFormatException e) {
// retry as a double
}
double d = Double.parseDouble(value);
if (roundUp) {
d = Math.ceil(d);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ public void testGeoTileFormat() {
public void testRawParse() {
assertEquals(-1L, DocValueFormat.RAW.parseLong("-1", randomBoolean(), null));
assertEquals(1L, DocValueFormat.RAW.parseLong("1", randomBoolean(), null));
assertEquals(Long.MAX_VALUE - 2, DocValueFormat.RAW.parseLong(Long.toString(Long.MAX_VALUE - 2), randomBoolean(), null));
// not checking exception messages as they could depend on the JVM
expectThrows(IllegalArgumentException.class, () -> DocValueFormat.RAW.parseLong("", randomBoolean(), null));
expectThrows(IllegalArgumentException.class, () -> DocValueFormat.RAW.parseLong("abc", randomBoolean(), null));
Expand All @@ -176,8 +177,8 @@ public void testRawParse() {
assertEquals(1d, DocValueFormat.RAW.parseDouble("1", randomBoolean(), null), 0d);
assertEquals(.5, DocValueFormat.RAW.parseDouble("0.5", randomBoolean(), null), 0d);
// not checking exception messages as they could depend on the JVM
expectThrows(IllegalArgumentException.class, () -> DocValueFormat.RAW.parseLong("", randomBoolean(), null));
expectThrows(IllegalArgumentException.class, () -> DocValueFormat.RAW.parseLong("abc", randomBoolean(), null));
expectThrows(IllegalArgumentException.class, () -> DocValueFormat.RAW.parseDouble("", randomBoolean(), null));
expectThrows(IllegalArgumentException.class, () -> DocValueFormat.RAW.parseDouble("abc", randomBoolean(), null));

assertEquals(new BytesRef("abc"), DocValueFormat.RAW.parseBytesRef("abc"));
}
Expand Down

0 comments on commit dad68c5

Please sign in to comment.