From 8cb2838f6a15e73b2a76854b629e70b3755453e7 Mon Sep 17 00:00:00 2001 From: Piotr Findeisen Date: Wed, 3 Aug 2022 15:32:11 +0200 Subject: [PATCH] Allow checking whether Duration is zero length This introduces new API method for checking whether duration is empty. The tempting terse alternative of `duration.toMillis() == 0` does not work correctly for sub-milli duration, so it's better to provide a shortcut that's correct. --- src/main/java/io/airlift/units/Duration.java | 10 ++++++++++ .../java/io/airlift/units/TestDuration.java | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/main/java/io/airlift/units/Duration.java b/src/main/java/io/airlift/units/Duration.java index b634dfb..3bad5f3 100644 --- a/src/main/java/io/airlift/units/Duration.java +++ b/src/main/java/io/airlift/units/Duration.java @@ -46,6 +46,8 @@ public final class Duration // call allocates a new array at each call. private static final TimeUnit[] TIME_UNITS = TimeUnit.values(); + public static final Duration ZERO = new Duration(0, SECONDS); + public static Duration nanosSince(long start) { return succinctNanos(System.nanoTime() - start); @@ -58,6 +60,9 @@ public static Duration succinctNanos(long nanos) public static Duration succinctDuration(double value, TimeUnit unit) { + if (value == 0) { + return ZERO; + } return new Duration(value, unit).convertToMostSuccinctTimeUnit(); } @@ -193,6 +198,11 @@ public int compareTo(Duration o) return Double.compare(getValue(MILLISECONDS), o.getValue(MILLISECONDS)); } + public boolean isZero() + { + return equals(ZERO); + } + @Override public boolean equals(Object o) { diff --git a/src/test/java/io/airlift/units/TestDuration.java b/src/test/java/io/airlift/units/TestDuration.java index 3f81101..27c1c2a 100644 --- a/src/test/java/io/airlift/units/TestDuration.java +++ b/src/test/java/io/airlift/units/TestDuration.java @@ -38,7 +38,9 @@ import static org.assertj.core.api.Assertions.offset; import static org.assertj.core.data.Percentage.withPercentage; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestDuration @@ -294,6 +296,22 @@ public void testEquals() assertNotEquals(new Duration(4444.0d, MILLISECONDS), new Duration(12359.0d, MILLISECONDS)); } + @Test + public void testIsZero() + { + assertTrue(Duration.ZERO.isZero()); + assertTrue(new Duration(0, HOURS).isZero()); + assertFalse(new Duration(12359.0d, MILLISECONDS).isZero()); + + // small values + assertFalse(new Duration(1e-20, MILLISECONDS).isZero()); + assertFalse(new Duration(1e-20, NANOSECONDS).isZero()); + + // very small values + assertFalse(new Duration(Double.MIN_VALUE, MILLISECONDS).isZero()); + assertTrue(new Duration(Double.MIN_VALUE, NANOSECONDS).isZero()); // TODO incorrect, due to equals converting to MILLIS + } + @Test public void testHashCode() {