Fix DurationToMilliseconds mult overflow

PiperOrigin-RevId: 588443477
pull/14954/head
Protobuf Team Bot 12 months ago committed by Copybara-Service
parent 43e7e52b28
commit 17b8dd6476
  1. 6
      src/google/protobuf/util/time_util.cc
  2. 6
      src/google/protobuf/util/time_util_test.cc

@ -311,11 +311,13 @@ int64_t TimeUtil::DurationToNanoseconds(const Duration& duration) {
}
int64_t TimeUtil::DurationToMicroseconds(const Duration& duration) {
return RoundTowardZero(DurationToNanoseconds(duration), kNanosPerMicrosecond);
return DurationToSeconds(duration) * kMicrosPerSecond +
RoundTowardZero(duration.nanos(), kNanosPerMicrosecond);
}
int64_t TimeUtil::DurationToMilliseconds(const Duration& duration) {
return RoundTowardZero(DurationToNanoseconds(duration), kNanosPerMillisecond);
return DurationToSeconds(duration) * kMillisPerSecond +
RoundTowardZero(duration.nanos(), kNanosPerMillisecond);
}
int64_t TimeUtil::DurationToSeconds(const Duration& duration) {

@ -145,6 +145,12 @@ TEST(TimeUtilTest, DurationIntegerConversion) {
1, TimeUtil::DurationToMilliseconds(TimeUtil::MillisecondsToDuration(1)));
EXPECT_EQ(-1, TimeUtil::DurationToMilliseconds(
TimeUtil::MillisecondsToDuration(-1)));
// Test overflow issue
EXPECT_EQ(315576000000000, TimeUtil::DurationToMilliseconds(
TimeUtil::SecondsToDuration(315576000000)));
// Test overflow issue
EXPECT_EQ(315576000000000000, TimeUtil::DurationToMicroseconds(
TimeUtil::SecondsToDuration(315576000000)));
EXPECT_EQ(1, TimeUtil::DurationToSeconds(TimeUtil::SecondsToDuration(1)));
EXPECT_EQ(-1, TimeUtil::DurationToSeconds(TimeUtil::SecondsToDuration(-1)));
EXPECT_EQ(1, TimeUtil::DurationToMinutes(TimeUtil::MinutesToDuration(1)));

Loading…
Cancel
Save