Automated rollback of commit 976a6eb6a4.

PiperOrigin-RevId: 613296331
pull/16036/head
Protobuf Team Bot 9 months ago committed by Copybara-Service
parent 5d58cb8559
commit f1d3f28eca
  1. 21
      java/util/src/main/java/com/google/protobuf/util/Timestamps.java
  2. 10
      java/util/src/test/java/com/google/protobuf/util/TimestampsTest.java

@ -137,7 +137,7 @@ public final class Timestamps {
*/
@SuppressWarnings("GoodTime") // this is a legacy conversion API
public static boolean isValid(long seconds, int nanos) {
if (seconds < TIMESTAMP_SECONDS_MIN || seconds > TIMESTAMP_SECONDS_MAX) {
if (!isValidSeconds(seconds)) {
return false;
}
if (nanos < 0 || nanos >= NANOS_PER_SECOND) {
@ -146,6 +146,16 @@ public final class Timestamps {
return true;
}
/**
* Returns true if the given number of seconds is valid, if combined with a valid number of nanos.
* The {@code seconds} value must be in the range [-62,135,596,800, +253,402,300,799] (i.e.,
* between 0001-01-01T00:00:00Z and 9999-12-31T23:59:59Z).
*/
@SuppressWarnings("GoodTime") // this is a legacy conversion API
private static boolean isValidSeconds(long seconds) {
return seconds >= TIMESTAMP_SECONDS_MIN && seconds <= TIMESTAMP_SECONDS_MAX;
}
/** Throws an {@link IllegalArgumentException} if the given {@link Timestamp} is not valid. */
@CanIgnoreReturnValue
public static Timestamp checkValid(Timestamp timestamp) {
@ -487,6 +497,15 @@ public final class Timestamps {
}
static Timestamp normalizedTimestamp(long seconds, int nanos) {
// This only checks seconds, because nanos can intentionally overflow to increment the seconds
// when normalized.
if (!isValidSeconds(seconds)) {
throw new IllegalArgumentException(
String.format(
"Timestamp is not valid. Input seconds is too large. "
+ "Seconds (%s) must be in range [-62,135,596,800, +253,402,300,799]. ",
seconds));
}
if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
nanos = (int) (nanos % NANOS_PER_SECOND);

@ -857,6 +857,16 @@ public class TimestampsTest {
.isEqualTo(timestamp(3, 1));
}
@Test
public void normalizedTimestamp_veryLarge_isInvalidNotOverflow() {
try {
Timestamps.normalizedTimestamp(9223372036854775807L, 2);
fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertThat(expected).hasMessageThat().startsWith("Timestamp is not valid.");
}
}
static Timestamp timestamp(long seconds, int nanos) {
return Timestamps.checkValid(
Timestamps.checkValid(Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos)));

Loading…
Cancel
Save