Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow checking whether Duration is zero length #27

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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