aboutsummaryrefslogtreecommitdiffhomepage
path: root/java/util/src/main/java/com/google/protobuf/util/Durations.java
diff options
context:
space:
mode:
Diffstat (limited to 'java/util/src/main/java/com/google/protobuf/util/Durations.java')
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Durations.java182
1 files changed, 116 insertions, 66 deletions
diff --git a/java/util/src/main/java/com/google/protobuf/util/Durations.java b/java/util/src/main/java/com/google/protobuf/util/Durations.java
index 5fe6ebca..9333168d 100644
--- a/java/util/src/main/java/com/google/protobuf/util/Durations.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Durations.java
@@ -30,50 +30,86 @@
package com.google.protobuf.util;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.math.IntMath.checkedAdd;
+import static com.google.common.math.IntMath.checkedSubtract;
+import static com.google.common.math.LongMath.checkedAdd;
+import static com.google.common.math.LongMath.checkedMultiply;
+import static com.google.common.math.LongMath.checkedSubtract;
import static com.google.protobuf.util.Timestamps.MICROS_PER_SECOND;
import static com.google.protobuf.util.Timestamps.MILLIS_PER_SECOND;
import static com.google.protobuf.util.Timestamps.NANOS_PER_MICROSECOND;
import static com.google.protobuf.util.Timestamps.NANOS_PER_MILLISECOND;
import static com.google.protobuf.util.Timestamps.NANOS_PER_SECOND;
+import com.google.common.collect.ComparisonChain;
import com.google.protobuf.Duration;
-
import java.text.ParseException;
+import java.util.Comparator;
/**
- * Utilities to help create/manipulate {@code protobuf/duration.proto}.
+ * Utilities to help create/manipulate {@code protobuf/duration.proto}. All operations throw an
+ * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Duration) valid}.
*/
public final class Durations {
static final long DURATION_SECONDS_MIN = -315576000000L;
static final long DURATION_SECONDS_MAX = 315576000000L;
- // TODO(kak): Do we want to expose Duration constants for MAX/MIN?
+ /** A constant holding the minimum valid {@link Duration}, approximately {@code -10,000} years. */
+ public static final Duration MIN_VALUE =
+ Duration.newBuilder().setSeconds(DURATION_SECONDS_MIN).setNanos(-999999999).build();
+
+ /** A constant holding the maximum valid {@link Duration}, approximately {@code +10,000} years. */
+ public static final Duration MAX_VALUE =
+ Duration.newBuilder().setSeconds(DURATION_SECONDS_MAX).setNanos(999999999).build();
private Durations() {}
+ private static final Comparator<Duration> COMPARATOR =
+ new Comparator<Duration>() {
+ @Override
+ public int compare(Duration d1, Duration d2) {
+ checkValid(d1);
+ checkValid(d2);
+
+ return ComparisonChain.start()
+ .compare(d1.getSeconds(), d2.getSeconds())
+ .compare(d1.getNanos(), d2.getNanos())
+ .result();
+ }
+ };
+
+ /**
+ * Returns a {@link Comparator} for {@link Duration}s which sorts in increasing chronological
+ * order. Nulls and invalid {@link Duration}s are not allowed (see {@link #isValid}).
+ */
+ public static Comparator<Duration> comparator() {
+ return COMPARATOR;
+ }
+
/**
* Returns true if the given {@link Duration} is valid. The {@code seconds} value must be in the
* range [-315,576,000,000, +315,576,000,000]. The {@code nanos} value must be in the range
* [-999,999,999, +999,999,999].
*
- * <p>Note: Durations less than one second are represented with a 0 {@code seconds} field and a
- * positive or negative {@code nanos} field. For durations of one second or more, a non-zero value
- * for the {@code nanos} field must be of the same sign as the {@code seconds} field.
+ * <p><b>Note:</b> Durations less than one second are represented with a 0 {@code seconds} field
+ * and a positive or negative {@code nanos} field. For durations of one second or more, a non-zero
+ * value for the {@code nanos} field must be of the same sign as the {@code seconds} field.
*/
public static boolean isValid(Duration duration) {
return isValid(duration.getSeconds(), duration.getNanos());
}
/**
- * Returns true if the given number of seconds and nanos is a valid {@link Duration}. The
- * {@code seconds} value must be in the range [-315,576,000,000, +315,576,000,000]. The
- * {@code nanos} value must be in the range [-999,999,999, +999,999,999].
+ * Returns true if the given number of seconds and nanos is a valid {@link Duration}. The {@code
+ * seconds} value must be in the range [-315,576,000,000, +315,576,000,000]. The {@code nanos}
+ * value must be in the range [-999,999,999, +999,999,999].
*
- * <p>Note: Durations less than one second are represented with a 0 {@code seconds} field and a
- * positive or negative {@code nanos} field. For durations of one second or more, a non-zero value
- * for the {@code nanos} field must be of the same sign as the {@code seconds} field.
+ * <p><b>Note:</b> Durations less than one second are represented with a 0 {@code seconds} field
+ * and a positive or negative {@code nanos} field. For durations of one second or more, a non-zero
+ * value for the {@code nanos} field must be of the same sign as the {@code seconds} field.
*/
- public static boolean isValid(long seconds, long nanos) {
+ public static boolean isValid(long seconds, int nanos) {
if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) {
return false;
}
@@ -88,35 +124,35 @@ public final class Durations {
return true;
}
- /**
- * Throws an {@link IllegalArgumentException} if the given seconds/nanos are not
- * a valid {@link Duration}.
- */
- private static void checkValid(long seconds, int nanos) {
- if (!isValid(seconds, nanos)) {
- throw new IllegalArgumentException(String.format(
- "Duration is not valid. See proto definition for valid values. "
- + "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000]."
- + "Nanos (%s) must be in range [-999,999,999, +999,999,999]. "
- + "Nanos must have the same sign as seconds", seconds, nanos));
- }
+ /** Throws an {@link IllegalArgumentException} if the given {@link Duration} is not valid. */
+ public static Duration checkValid(Duration duration) {
+ long seconds = duration.getSeconds();
+ int nanos = duration.getNanos();
+ checkArgument(
+ isValid(seconds, nanos),
+ "Duration is not valid. See proto definition for valid values. "
+ + "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000]. "
+ + "Nanos (%s) must be in range [-999,999,999, +999,999,999]. "
+ + "Nanos must have the same sign as seconds",
+ seconds,
+ nanos);
+ return duration;
}
/**
- * Convert Duration to string format. The string format will contains 3, 6,
- * or 9 fractional digits depending on the precision required to represent
- * the exact Duration value. For example: "1s", "1.010s", "1.000000100s",
- * "-3.100s" The range that can be represented by Duration is from
+ * Convert Duration to string format. The string format will contains 3, 6, or 9 fractional digits
+ * depending on the precision required to represent the exact Duration value. For example: "1s",
+ * "1.010s", "1.000000100s", "-3.100s" The range that can be represented by Duration is from
* -315,576,000,000 to +315,576,000,000 inclusive (in seconds).
*
* @return The string representation of the given duration.
- * @throws IllegalArgumentException if the given duration is not in the valid
- * range.
+ * @throws IllegalArgumentException if the given duration is not in the valid range.
*/
public static String toString(Duration duration) {
+ checkValid(duration);
+
long seconds = duration.getSeconds();
int nanos = duration.getNanos();
- checkValid(seconds, nanos);
StringBuilder result = new StringBuilder();
if (seconds < 0 || nanos < 0) {
@@ -172,9 +208,20 @@ public final class Durations {
}
}
+ /** Create a Duration from the number of seconds. */
+ public static Duration fromSeconds(long seconds) {
+ return normalizedDuration(seconds, 0);
+ }
+
/**
- * Create a Duration from the number of milliseconds.
+ * Convert a Duration to the number of seconds. The result will be rounded towards 0 to the
+ * nearest second. E.g., if the duration represents -1 nanosecond, it will be rounded to 0.
*/
+ public static long toSeconds(Duration duration) {
+ return checkValid(duration).getSeconds();
+ }
+
+ /** Create a Duration from the number of milliseconds. */
public static Duration fromMillis(long milliseconds) {
return normalizedDuration(
milliseconds / MILLIS_PER_SECOND,
@@ -182,17 +229,17 @@ public final class Durations {
}
/**
- * Convert a Duration to the number of milliseconds.The result will be
- * rounded towards 0 to the nearest millisecond. E.g., if the duration
- * represents -1 nanosecond, it will be rounded to 0.
+ * Convert a Duration to the number of milliseconds. The result will be rounded towards 0 to the
+ * nearest millisecond. E.g., if the duration represents -1 nanosecond, it will be rounded to 0.
*/
public static long toMillis(Duration duration) {
- return duration.getSeconds() * MILLIS_PER_SECOND + duration.getNanos() / NANOS_PER_MILLISECOND;
+ checkValid(duration);
+ return checkedAdd(
+ checkedMultiply(duration.getSeconds(), MILLIS_PER_SECOND),
+ duration.getNanos() / NANOS_PER_MILLISECOND);
}
- /**
- * Create a Duration from the number of microseconds.
- */
+ /** Create a Duration from the number of microseconds. */
public static Duration fromMicros(long microseconds) {
return normalizedDuration(
microseconds / MICROS_PER_SECOND,
@@ -200,57 +247,60 @@ public final class Durations {
}
/**
- * Convert a Duration to the number of microseconds.The result will be
- * rounded towards 0 to the nearest microseconds. E.g., if the duration
- * represents -1 nanosecond, it will be rounded to 0.
+ * Convert a Duration to the number of microseconds. The result will be rounded towards 0 to the
+ * nearest microseconds. E.g., if the duration represents -1 nanosecond, it will be rounded to 0.
*/
public static long toMicros(Duration duration) {
- return duration.getSeconds() * MICROS_PER_SECOND + duration.getNanos() / NANOS_PER_MICROSECOND;
+ checkValid(duration);
+ return checkedAdd(
+ checkedMultiply(duration.getSeconds(), MICROS_PER_SECOND),
+ duration.getNanos() / NANOS_PER_MICROSECOND);
}
- /**
- * Create a Duration from the number of nanoseconds.
- */
+ /** Create a Duration from the number of nanoseconds. */
public static Duration fromNanos(long nanoseconds) {
return normalizedDuration(
nanoseconds / NANOS_PER_SECOND, (int) (nanoseconds % NANOS_PER_SECOND));
}
- /**
- * Convert a Duration to the number of nanoseconds.
- */
+ /** Convert a Duration to the number of nanoseconds. */
public static long toNanos(Duration duration) {
- return duration.getSeconds() * NANOS_PER_SECOND + duration.getNanos();
+ checkValid(duration);
+ return checkedAdd(
+ checkedMultiply(duration.getSeconds(), NANOS_PER_SECOND), duration.getNanos());
}
- /**
- * Add two durations.
- */
+ /** Add two durations. */
public static Duration add(Duration d1, Duration d2) {
- return normalizedDuration(d1.getSeconds() + d2.getSeconds(), d1.getNanos() + d2.getNanos());
+ checkValid(d1);
+ checkValid(d2);
+ return normalizedDuration(
+ checkedAdd(d1.getSeconds(), d2.getSeconds()), checkedAdd(d1.getNanos(), d2.getNanos()));
}
- /**
- * Subtract a duration from another.
- */
+ /** Subtract a duration from another. */
public static Duration subtract(Duration d1, Duration d2) {
- return normalizedDuration(d1.getSeconds() - d2.getSeconds(), d1.getNanos() - d2.getNanos());
+ checkValid(d1);
+ checkValid(d2);
+ return normalizedDuration(
+ checkedSubtract(d1.getSeconds(), d2.getSeconds()),
+ checkedSubtract(d1.getNanos(), d2.getNanos()));
}
static Duration normalizedDuration(long seconds, int nanos) {
if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
- seconds += nanos / NANOS_PER_SECOND;
+ seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
nanos %= NANOS_PER_SECOND;
}
if (seconds > 0 && nanos < 0) {
- nanos += NANOS_PER_SECOND;
- seconds -= 1;
+ nanos += NANOS_PER_SECOND; // no overflow since nanos is negative (and we're adding)
+ seconds--; // no overflow since seconds is positive (and we're decrementing)
}
if (seconds < 0 && nanos > 0) {
- nanos -= NANOS_PER_SECOND;
- seconds += 1;
+ nanos -= NANOS_PER_SECOND; // no overflow since nanos is positive (and we're subtracting)
+ seconds++; // no overflow since seconds is negative (and we're incrementing)
}
- checkValid(seconds, nanos);
- return Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
+ Duration duration = Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
+ return checkValid(duration);
}
}