Skip to content

Commit

Permalink
additional tests and comments
Browse files Browse the repository at this point in the history
  • Loading branch information
not-napoleon committed Dec 5, 2024
1 parent 4dbdff9 commit 7048e44
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,8 @@ public static int compareNanosToMillis(long nanos, long millis) {
if (millis > MAX_NANOSECOND_IN_MILLIS) {
return -1;
}
// This can't overflow, because we know millis is between 0 and MAX_NANOSECOND_IN_MILLIS,
// and MAX_NANOSECOND_IN_MILLIS * 1_000_000 doesn't overflow.
long diff = nanos - (millis * 1_000_000);
return diff == 0 ? 0 : diff < 0 ? -1 : 1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import static org.elasticsearch.common.time.DateUtils.MAX_MILLIS_BEFORE_MINUS_9999;
import static org.elasticsearch.common.time.DateUtils.MAX_NANOSECOND_INSTANT;
import static org.elasticsearch.common.time.DateUtils.MAX_NANOSECOND_IN_MILLIS;
import static org.elasticsearch.common.time.DateUtils.clampToNanosRange;
import static org.elasticsearch.common.time.DateUtils.compareNanosToMillis;
import static org.elasticsearch.common.time.DateUtils.toInstant;
Expand All @@ -31,12 +32,19 @@
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;

public class DateUtilsTests extends ESTestCase {

public void testCompareNanosToMillis() {
assertThat(MAX_NANOSECOND_IN_MILLIS * 1_000_000, lessThan(Long.MAX_VALUE));

assertThat(compareNanosToMillis(toLong(Instant.EPOCH), Instant.EPOCH.toEpochMilli()), is(0));

// This should be 1, because the millisecond version should truncate a bit
assertThat(compareNanosToMillis(toLong(MAX_NANOSECOND_INSTANT), MAX_NANOSECOND_INSTANT.toEpochMilli()), is(1));

assertThat(compareNanosToMillis(toLong(MAX_NANOSECOND_INSTANT), -1000), is(1));
// millis before epoch
assertCompareInstants(
randomInstantBetween(Instant.EPOCH, MAX_NANOSECOND_INSTANT),
Expand Down

0 comments on commit 7048e44

Please sign in to comment.