Bound j2000 timestamps into [0, <int32_t>::max()] interval

We use j2000 timestamps in base::Values and macaroon tokens.
base::Values use int32_t and macaroon use uint32_t, so this interval should be
safe.

Change-Id: Ibcd7a8b8749ace62c561b2c03f3ccfdac2e74706
Reviewed-on: https://weave-review.googlesource.com/2882
Reviewed-by: Alex Vakulenko <avakulenko@google.com>
diff --git a/src/utils.cc b/src/utils.cc
index 5d1c3e3..bd15e61 100644
--- a/src/utils.cc
+++ b/src/utils.cc
@@ -4,6 +4,8 @@
 
 #include "src/utils.h"
 
+#include <limits>
+
 #include <base/bind_helpers.h>
 #include <base/json/json_reader.h>
 
@@ -72,10 +74,14 @@
 }
 
 uint32_t ToJ2000Time(const base::Time& time) {
-  return std::max(time.ToTimeT(), kJ2000ToTimeT) - kJ2000ToTimeT;
+  return std::min<int64_t>(
+      std::numeric_limits<int32_t>::max(),
+      std::max<int64_t>(kJ2000ToTimeT, time.ToTimeT()) - kJ2000ToTimeT);
 }
 
 base::Time FromJ2000Time(uint32_t time) {
+  if (time >= static_cast<uint32_t>(std::numeric_limits<int32_t>::max()))
+    return base::Time::Max();
   return base::Time::FromTimeT(time + kJ2000ToTimeT);
 }