update_engine: Make utils::FormatTimeDelta() work with negative values.
BUG=chromium:401862
TEST=New unit test + unit tests pass.
Change-Id: I89b7ec72c11b792d4353eb6b36b23eac4f82107d
Reviewed-on: https://chromium-review.googlesource.com/212878
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Reviewed-by: Alex Deymo <deymo@chromium.org>
Commit-Queue: David Zeuthen <zeuthen@chromium.org>
Tested-by: David Zeuthen <zeuthen@chromium.org>
diff --git a/utils.cc b/utils.cc
index 2c17be8..37d1c9a 100644
--- a/utils.cc
+++ b/utils.cc
@@ -843,6 +843,14 @@
}
string FormatTimeDelta(TimeDelta delta) {
+ string str;
+
+ // Handle negative durations by prefixing with a minus.
+ if (delta.ToInternalValue() < 0) {
+ delta *= -1;
+ str = "-";
+ }
+
// Canonicalize into days, hours, minutes, seconds and microseconds.
unsigned days = delta.InDays();
delta -= TimeDelta::FromDays(days);
@@ -854,8 +862,6 @@
delta -= TimeDelta::FromSeconds(secs);
unsigned usecs = delta.InMicroseconds();
- // Construct and return string.
- string str;
if (days)
base::StringAppendF(&str, "%ud", days);
if (days || hours)
diff --git a/utils.h b/utils.h
index 8c4850e..6d14fbc 100644
--- a/utils.h
+++ b/utils.h
@@ -326,7 +326,8 @@
// as necessary; for example, an output of 5d2h0m15.053s means that the input
// time was precise to the milliseconds only. Zero padding not applied, except
// for fractions. Seconds are always shown, but fractions thereof are only shown
-// when applicable.
+// when applicable. If |delta| is negative, the output will have a leading '-'
+// followed by the absolute duration.
std::string FormatTimeDelta(base::TimeDelta delta);
// This method transforms the given error code to be suitable for UMA and
diff --git a/utils_unittest.cc b/utils_unittest.cc
index 53e4428..f23dd5c 100644
--- a/utils_unittest.cc
+++ b/utils_unittest.cc
@@ -459,6 +459,8 @@
EXPECT_EQ(utils::FormatTimeDelta(base::TimeDelta::FromSeconds(200000) +
base::TimeDelta::FromMilliseconds(1)),
"2d7h33m20.001s");
+ EXPECT_EQ(utils::FormatTimeDelta(base::TimeDelta::FromSeconds(-1)),
+ "-1s");
}
TEST(UtilsTest, TimeFromStructTimespecTest) {