Skip to content

Commit

Permalink
Allow checking whether Duration is zero length
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
findepi committed Jul 4, 2023
1 parent cbd7bea commit 82df863
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/main/java/io/airlift/units/Duration.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();
}

Expand Down Expand Up @@ -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)
{
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/io/airlift/units/TestDuration.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
{
Expand Down

0 comments on commit 82df863

Please sign in to comment.