• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #if defined(_MSC_VER)
16 #include <winsock2.h>  // for timeval
17 #endif
18 
19 #include <chrono>  // NOLINT(build/c++11)
20 #include <cfloat>
21 #include <cmath>
22 #include <cstdint>
23 #include <ctime>
24 #include <iomanip>
25 #include <limits>
26 #include <random>
27 #include <string>
28 
29 #include "gmock/gmock.h"
30 #include "gtest/gtest.h"
31 #include "absl/time/time.h"
32 
33 namespace {
34 
35 constexpr int64_t kint64max = std::numeric_limits<int64_t>::max();
36 constexpr int64_t kint64min = std::numeric_limits<int64_t>::min();
37 
38 // Approximates the given number of years. This is only used to make some test
39 // code more readable.
ApproxYears(int64_t n)40 absl::Duration ApproxYears(int64_t n) { return absl::Hours(n) * 365 * 24; }
41 
42 // A gMock matcher to match timespec values. Use this matcher like:
43 // timespec ts1, ts2;
44 // EXPECT_THAT(ts1, TimespecMatcher(ts2));
45 MATCHER_P(TimespecMatcher, ts, "") {
46   if (ts.tv_sec == arg.tv_sec && ts.tv_nsec == arg.tv_nsec)
47     return true;
48   *result_listener << "expected: {" << ts.tv_sec << ", " << ts.tv_nsec << "} ";
49   *result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_nsec << "}";
50   return false;
51 }
52 
53 // A gMock matcher to match timeval values. Use this matcher like:
54 // timeval tv1, tv2;
55 // EXPECT_THAT(tv1, TimevalMatcher(tv2));
56 MATCHER_P(TimevalMatcher, tv, "") {
57   if (tv.tv_sec == arg.tv_sec && tv.tv_usec == arg.tv_usec)
58     return true;
59   *result_listener << "expected: {" << tv.tv_sec << ", " << tv.tv_usec << "} ";
60   *result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_usec << "}";
61   return false;
62 }
63 
TEST(Duration,ConstExpr)64 TEST(Duration, ConstExpr) {
65   constexpr absl::Duration d0 = absl::ZeroDuration();
66   static_assert(d0 == absl::ZeroDuration(), "ZeroDuration()");
67   constexpr absl::Duration d1 = absl::Seconds(1);
68   static_assert(d1 == absl::Seconds(1), "Seconds(1)");
69   static_assert(d1 != absl::ZeroDuration(), "Seconds(1)");
70   constexpr absl::Duration d2 = absl::InfiniteDuration();
71   static_assert(d2 == absl::InfiniteDuration(), "InfiniteDuration()");
72   static_assert(d2 != absl::ZeroDuration(), "InfiniteDuration()");
73 }
74 
TEST(Duration,ValueSemantics)75 TEST(Duration, ValueSemantics) {
76   // If this compiles, the test passes.
77   constexpr absl::Duration a;      // Default construction
78   constexpr absl::Duration b = a;  // Copy construction
79   constexpr absl::Duration c(b);   // Copy construction (again)
80 
81   absl::Duration d;
82   d = c;  // Assignment
83 }
84 
TEST(Duration,Factories)85 TEST(Duration, Factories) {
86   constexpr absl::Duration zero = absl::ZeroDuration();
87   constexpr absl::Duration nano = absl::Nanoseconds(1);
88   constexpr absl::Duration micro = absl::Microseconds(1);
89   constexpr absl::Duration milli = absl::Milliseconds(1);
90   constexpr absl::Duration sec = absl::Seconds(1);
91   constexpr absl::Duration min = absl::Minutes(1);
92   constexpr absl::Duration hour = absl::Hours(1);
93 
94   EXPECT_EQ(zero, absl::Duration());
95   EXPECT_EQ(zero, absl::Seconds(0));
96   EXPECT_EQ(nano, absl::Nanoseconds(1));
97   EXPECT_EQ(micro, absl::Nanoseconds(1000));
98   EXPECT_EQ(milli, absl::Microseconds(1000));
99   EXPECT_EQ(sec, absl::Milliseconds(1000));
100   EXPECT_EQ(min, absl::Seconds(60));
101   EXPECT_EQ(hour, absl::Minutes(60));
102 
103   // Tests factory limits
104   const absl::Duration inf = absl::InfiniteDuration();
105 
106   EXPECT_GT(inf, absl::Seconds(kint64max));
107   EXPECT_LT(-inf, absl::Seconds(kint64min));
108   EXPECT_LT(-inf, absl::Seconds(-kint64max));
109 
110   EXPECT_EQ(inf, absl::Minutes(kint64max));
111   EXPECT_EQ(-inf, absl::Minutes(kint64min));
112   EXPECT_EQ(-inf, absl::Minutes(-kint64max));
113   EXPECT_GT(inf, absl::Minutes(kint64max / 60));
114   EXPECT_LT(-inf, absl::Minutes(kint64min / 60));
115   EXPECT_LT(-inf, absl::Minutes(-kint64max / 60));
116 
117   EXPECT_EQ(inf, absl::Hours(kint64max));
118   EXPECT_EQ(-inf, absl::Hours(kint64min));
119   EXPECT_EQ(-inf, absl::Hours(-kint64max));
120   EXPECT_GT(inf, absl::Hours(kint64max / 3600));
121   EXPECT_LT(-inf, absl::Hours(kint64min / 3600));
122   EXPECT_LT(-inf, absl::Hours(-kint64max / 3600));
123 }
124 
TEST(Duration,ToConversion)125 TEST(Duration, ToConversion) {
126 #define TEST_DURATION_CONVERSION(UNIT)                                  \
127   do {                                                                  \
128     const absl::Duration d = absl::UNIT(1.5);                           \
129     constexpr absl::Duration z = absl::ZeroDuration();                  \
130     constexpr absl::Duration inf = absl::InfiniteDuration();            \
131     constexpr double dbl_inf = std::numeric_limits<double>::infinity(); \
132     EXPECT_EQ(kint64min, absl::ToInt64##UNIT(-inf));                    \
133     EXPECT_EQ(-1, absl::ToInt64##UNIT(-d));                             \
134     EXPECT_EQ(0, absl::ToInt64##UNIT(z));                               \
135     EXPECT_EQ(1, absl::ToInt64##UNIT(d));                               \
136     EXPECT_EQ(kint64max, absl::ToInt64##UNIT(inf));                     \
137     EXPECT_EQ(-dbl_inf, absl::ToDouble##UNIT(-inf));                    \
138     EXPECT_EQ(-1.5, absl::ToDouble##UNIT(-d));                          \
139     EXPECT_EQ(0, absl::ToDouble##UNIT(z));                              \
140     EXPECT_EQ(1.5, absl::ToDouble##UNIT(d));                            \
141     EXPECT_EQ(dbl_inf, absl::ToDouble##UNIT(inf));                      \
142   } while (0)
143 
144   TEST_DURATION_CONVERSION(Nanoseconds);
145   TEST_DURATION_CONVERSION(Microseconds);
146   TEST_DURATION_CONVERSION(Milliseconds);
147   TEST_DURATION_CONVERSION(Seconds);
148   TEST_DURATION_CONVERSION(Minutes);
149   TEST_DURATION_CONVERSION(Hours);
150 
151 #undef TEST_DURATION_CONVERSION
152 }
153 
154 template <int64_t N>
TestToConversion()155 void TestToConversion() {
156   constexpr absl::Duration nano = absl::Nanoseconds(N);
157   EXPECT_EQ(N, absl::ToInt64Nanoseconds(nano));
158   EXPECT_EQ(0, absl::ToInt64Microseconds(nano));
159   EXPECT_EQ(0, absl::ToInt64Milliseconds(nano));
160   EXPECT_EQ(0, absl::ToInt64Seconds(nano));
161   EXPECT_EQ(0, absl::ToInt64Minutes(nano));
162   EXPECT_EQ(0, absl::ToInt64Hours(nano));
163   const absl::Duration micro = absl::Microseconds(N);
164   EXPECT_EQ(N * 1000, absl::ToInt64Nanoseconds(micro));
165   EXPECT_EQ(N, absl::ToInt64Microseconds(micro));
166   EXPECT_EQ(0, absl::ToInt64Milliseconds(micro));
167   EXPECT_EQ(0, absl::ToInt64Seconds(micro));
168   EXPECT_EQ(0, absl::ToInt64Minutes(micro));
169   EXPECT_EQ(0, absl::ToInt64Hours(micro));
170   const absl::Duration milli = absl::Milliseconds(N);
171   EXPECT_EQ(N * 1000 * 1000, absl::ToInt64Nanoseconds(milli));
172   EXPECT_EQ(N * 1000, absl::ToInt64Microseconds(milli));
173   EXPECT_EQ(N, absl::ToInt64Milliseconds(milli));
174   EXPECT_EQ(0, absl::ToInt64Seconds(milli));
175   EXPECT_EQ(0, absl::ToInt64Minutes(milli));
176   EXPECT_EQ(0, absl::ToInt64Hours(milli));
177   const absl::Duration sec = absl::Seconds(N);
178   EXPECT_EQ(N * 1000 * 1000 * 1000, absl::ToInt64Nanoseconds(sec));
179   EXPECT_EQ(N * 1000 * 1000, absl::ToInt64Microseconds(sec));
180   EXPECT_EQ(N * 1000, absl::ToInt64Milliseconds(sec));
181   EXPECT_EQ(N, absl::ToInt64Seconds(sec));
182   EXPECT_EQ(0, absl::ToInt64Minutes(sec));
183   EXPECT_EQ(0, absl::ToInt64Hours(sec));
184   const absl::Duration min = absl::Minutes(N);
185   EXPECT_EQ(N * 60 * 1000 * 1000 * 1000, absl::ToInt64Nanoseconds(min));
186   EXPECT_EQ(N * 60 * 1000 * 1000, absl::ToInt64Microseconds(min));
187   EXPECT_EQ(N * 60 * 1000, absl::ToInt64Milliseconds(min));
188   EXPECT_EQ(N * 60, absl::ToInt64Seconds(min));
189   EXPECT_EQ(N, absl::ToInt64Minutes(min));
190   EXPECT_EQ(0, absl::ToInt64Hours(min));
191   const absl::Duration hour = absl::Hours(N);
192   EXPECT_EQ(N * 60 * 60 * 1000 * 1000 * 1000, absl::ToInt64Nanoseconds(hour));
193   EXPECT_EQ(N * 60 * 60 * 1000 * 1000, absl::ToInt64Microseconds(hour));
194   EXPECT_EQ(N * 60 * 60 * 1000, absl::ToInt64Milliseconds(hour));
195   EXPECT_EQ(N * 60 * 60, absl::ToInt64Seconds(hour));
196   EXPECT_EQ(N * 60, absl::ToInt64Minutes(hour));
197   EXPECT_EQ(N, absl::ToInt64Hours(hour));
198 }
199 
TEST(Duration,ToConversionDeprecated)200 TEST(Duration, ToConversionDeprecated) {
201   TestToConversion<43>();
202   TestToConversion<1>();
203   TestToConversion<0>();
204   TestToConversion<-1>();
205   TestToConversion<-43>();
206 }
207 
208 template <int64_t N>
TestFromChronoBasicEquality()209 void TestFromChronoBasicEquality() {
210   using std::chrono::nanoseconds;
211   using std::chrono::microseconds;
212   using std::chrono::milliseconds;
213   using std::chrono::seconds;
214   using std::chrono::minutes;
215   using std::chrono::hours;
216 
217   static_assert(absl::Nanoseconds(N) == absl::FromChrono(nanoseconds(N)), "");
218   static_assert(absl::Microseconds(N) == absl::FromChrono(microseconds(N)), "");
219   static_assert(absl::Milliseconds(N) == absl::FromChrono(milliseconds(N)), "");
220   static_assert(absl::Seconds(N) == absl::FromChrono(seconds(N)), "");
221   static_assert(absl::Minutes(N) == absl::FromChrono(minutes(N)), "");
222   static_assert(absl::Hours(N) == absl::FromChrono(hours(N)), "");
223 }
224 
TEST(Duration,FromChrono)225 TEST(Duration, FromChrono) {
226   TestFromChronoBasicEquality<-123>();
227   TestFromChronoBasicEquality<-1>();
228   TestFromChronoBasicEquality<0>();
229   TestFromChronoBasicEquality<1>();
230   TestFromChronoBasicEquality<123>();
231 
232   // Minutes (might, depending on the platform) saturate at +inf.
233   const auto chrono_minutes_max = std::chrono::minutes::max();
234   const auto minutes_max = absl::FromChrono(chrono_minutes_max);
235   const int64_t minutes_max_count = chrono_minutes_max.count();
236   if (minutes_max_count > kint64max / 60) {
237     EXPECT_EQ(absl::InfiniteDuration(), minutes_max);
238   } else {
239     EXPECT_EQ(absl::Minutes(minutes_max_count), minutes_max);
240   }
241 
242   // Minutes (might, depending on the platform) saturate at -inf.
243   const auto chrono_minutes_min = std::chrono::minutes::min();
244   const auto minutes_min = absl::FromChrono(chrono_minutes_min);
245   const int64_t minutes_min_count = chrono_minutes_min.count();
246   if (minutes_min_count < kint64min / 60) {
247     EXPECT_EQ(-absl::InfiniteDuration(), minutes_min);
248   } else {
249     EXPECT_EQ(absl::Minutes(minutes_min_count), minutes_min);
250   }
251 
252   // Hours (might, depending on the platform) saturate at +inf.
253   const auto chrono_hours_max = std::chrono::hours::max();
254   const auto hours_max = absl::FromChrono(chrono_hours_max);
255   const int64_t hours_max_count = chrono_hours_max.count();
256   if (hours_max_count > kint64max / 3600) {
257     EXPECT_EQ(absl::InfiniteDuration(), hours_max);
258   } else {
259     EXPECT_EQ(absl::Hours(hours_max_count), hours_max);
260   }
261 
262   // Hours (might, depending on the platform) saturate at -inf.
263   const auto chrono_hours_min = std::chrono::hours::min();
264   const auto hours_min = absl::FromChrono(chrono_hours_min);
265   const int64_t hours_min_count = chrono_hours_min.count();
266   if (hours_min_count < kint64min / 3600) {
267     EXPECT_EQ(-absl::InfiniteDuration(), hours_min);
268   } else {
269     EXPECT_EQ(absl::Hours(hours_min_count), hours_min);
270   }
271 }
272 
273 template <int64_t N>
TestToChrono()274 void TestToChrono() {
275   using std::chrono::nanoseconds;
276   using std::chrono::microseconds;
277   using std::chrono::milliseconds;
278   using std::chrono::seconds;
279   using std::chrono::minutes;
280   using std::chrono::hours;
281 
282   EXPECT_EQ(nanoseconds(N), absl::ToChronoNanoseconds(absl::Nanoseconds(N)));
283   EXPECT_EQ(microseconds(N), absl::ToChronoMicroseconds(absl::Microseconds(N)));
284   EXPECT_EQ(milliseconds(N), absl::ToChronoMilliseconds(absl::Milliseconds(N)));
285   EXPECT_EQ(seconds(N), absl::ToChronoSeconds(absl::Seconds(N)));
286 
287   constexpr auto absl_minutes = absl::Minutes(N);
288   auto chrono_minutes = minutes(N);
289   if (absl_minutes == -absl::InfiniteDuration()) {
290     chrono_minutes = minutes::min();
291   } else if (absl_minutes == absl::InfiniteDuration()) {
292     chrono_minutes = minutes::max();
293   }
294   EXPECT_EQ(chrono_minutes, absl::ToChronoMinutes(absl_minutes));
295 
296   constexpr auto absl_hours = absl::Hours(N);
297   auto chrono_hours = hours(N);
298   if (absl_hours == -absl::InfiniteDuration()) {
299     chrono_hours = hours::min();
300   } else if (absl_hours == absl::InfiniteDuration()) {
301     chrono_hours = hours::max();
302   }
303   EXPECT_EQ(chrono_hours, absl::ToChronoHours(absl_hours));
304 }
305 
TEST(Duration,ToChrono)306 TEST(Duration, ToChrono) {
307   using std::chrono::nanoseconds;
308   using std::chrono::microseconds;
309   using std::chrono::milliseconds;
310   using std::chrono::seconds;
311   using std::chrono::minutes;
312   using std::chrono::hours;
313 
314   TestToChrono<kint64min>();
315   TestToChrono<-1>();
316   TestToChrono<0>();
317   TestToChrono<1>();
318   TestToChrono<kint64max>();
319 
320   // Verify truncation toward zero.
321   const auto tick = absl::Nanoseconds(1) / 4;
322   EXPECT_EQ(nanoseconds(0), absl::ToChronoNanoseconds(tick));
323   EXPECT_EQ(nanoseconds(0), absl::ToChronoNanoseconds(-tick));
324   EXPECT_EQ(microseconds(0), absl::ToChronoMicroseconds(tick));
325   EXPECT_EQ(microseconds(0), absl::ToChronoMicroseconds(-tick));
326   EXPECT_EQ(milliseconds(0), absl::ToChronoMilliseconds(tick));
327   EXPECT_EQ(milliseconds(0), absl::ToChronoMilliseconds(-tick));
328   EXPECT_EQ(seconds(0), absl::ToChronoSeconds(tick));
329   EXPECT_EQ(seconds(0), absl::ToChronoSeconds(-tick));
330   EXPECT_EQ(minutes(0), absl::ToChronoMinutes(tick));
331   EXPECT_EQ(minutes(0), absl::ToChronoMinutes(-tick));
332   EXPECT_EQ(hours(0), absl::ToChronoHours(tick));
333   EXPECT_EQ(hours(0), absl::ToChronoHours(-tick));
334 
335   // Verifies +/- infinity saturation at max/min.
336   constexpr auto inf = absl::InfiniteDuration();
337   EXPECT_EQ(nanoseconds::min(), absl::ToChronoNanoseconds(-inf));
338   EXPECT_EQ(nanoseconds::max(), absl::ToChronoNanoseconds(inf));
339   EXPECT_EQ(microseconds::min(), absl::ToChronoMicroseconds(-inf));
340   EXPECT_EQ(microseconds::max(), absl::ToChronoMicroseconds(inf));
341   EXPECT_EQ(milliseconds::min(), absl::ToChronoMilliseconds(-inf));
342   EXPECT_EQ(milliseconds::max(), absl::ToChronoMilliseconds(inf));
343   EXPECT_EQ(seconds::min(), absl::ToChronoSeconds(-inf));
344   EXPECT_EQ(seconds::max(), absl::ToChronoSeconds(inf));
345   EXPECT_EQ(minutes::min(), absl::ToChronoMinutes(-inf));
346   EXPECT_EQ(minutes::max(), absl::ToChronoMinutes(inf));
347   EXPECT_EQ(hours::min(), absl::ToChronoHours(-inf));
348   EXPECT_EQ(hours::max(), absl::ToChronoHours(inf));
349 }
350 
TEST(Duration,FactoryOverloads)351 TEST(Duration, FactoryOverloads) {
352   enum E { kOne = 1 };
353 #define TEST_FACTORY_OVERLOADS(NAME)                                          \
354   EXPECT_EQ(1, NAME(kOne) / NAME(kOne));                                      \
355   EXPECT_EQ(1, NAME(static_cast<int8_t>(1)) / NAME(1));                       \
356   EXPECT_EQ(1, NAME(static_cast<int16_t>(1)) / NAME(1));                      \
357   EXPECT_EQ(1, NAME(static_cast<int32_t>(1)) / NAME(1));                      \
358   EXPECT_EQ(1, NAME(static_cast<int64_t>(1)) / NAME(1));                      \
359   EXPECT_EQ(1, NAME(static_cast<uint8_t>(1)) / NAME(1));                      \
360   EXPECT_EQ(1, NAME(static_cast<uint16_t>(1)) / NAME(1));                     \
361   EXPECT_EQ(1, NAME(static_cast<uint32_t>(1)) / NAME(1));                     \
362   EXPECT_EQ(1, NAME(static_cast<uint64_t>(1)) / NAME(1));                     \
363   EXPECT_EQ(NAME(1) / 2, NAME(static_cast<float>(0.5)));                      \
364   EXPECT_EQ(NAME(1) / 2, NAME(static_cast<double>(0.5)));                     \
365   EXPECT_EQ(1.5, absl::FDivDuration(NAME(static_cast<float>(1.5)), NAME(1))); \
366   EXPECT_EQ(1.5, absl::FDivDuration(NAME(static_cast<double>(1.5)), NAME(1)));
367 
368   TEST_FACTORY_OVERLOADS(absl::Nanoseconds);
369   TEST_FACTORY_OVERLOADS(absl::Microseconds);
370   TEST_FACTORY_OVERLOADS(absl::Milliseconds);
371   TEST_FACTORY_OVERLOADS(absl::Seconds);
372   TEST_FACTORY_OVERLOADS(absl::Minutes);
373   TEST_FACTORY_OVERLOADS(absl::Hours);
374 
375 #undef TEST_FACTORY_OVERLOADS
376 
377   EXPECT_EQ(absl::Milliseconds(1500), absl::Seconds(1.5));
378   EXPECT_LT(absl::Nanoseconds(1), absl::Nanoseconds(1.5));
379   EXPECT_GT(absl::Nanoseconds(2), absl::Nanoseconds(1.5));
380 
381   const double dbl_inf = std::numeric_limits<double>::infinity();
382   EXPECT_EQ(absl::InfiniteDuration(), absl::Nanoseconds(dbl_inf));
383   EXPECT_EQ(absl::InfiniteDuration(), absl::Microseconds(dbl_inf));
384   EXPECT_EQ(absl::InfiniteDuration(), absl::Milliseconds(dbl_inf));
385   EXPECT_EQ(absl::InfiniteDuration(), absl::Seconds(dbl_inf));
386   EXPECT_EQ(absl::InfiniteDuration(), absl::Minutes(dbl_inf));
387   EXPECT_EQ(absl::InfiniteDuration(), absl::Hours(dbl_inf));
388   EXPECT_EQ(-absl::InfiniteDuration(), absl::Nanoseconds(-dbl_inf));
389   EXPECT_EQ(-absl::InfiniteDuration(), absl::Microseconds(-dbl_inf));
390   EXPECT_EQ(-absl::InfiniteDuration(), absl::Milliseconds(-dbl_inf));
391   EXPECT_EQ(-absl::InfiniteDuration(), absl::Seconds(-dbl_inf));
392   EXPECT_EQ(-absl::InfiniteDuration(), absl::Minutes(-dbl_inf));
393   EXPECT_EQ(-absl::InfiniteDuration(), absl::Hours(-dbl_inf));
394 }
395 
TEST(Duration,InfinityExamples)396 TEST(Duration, InfinityExamples) {
397   // These examples are used in the documentation in time.h. They are
398   // written so that they can be copy-n-pasted easily.
399 
400   constexpr absl::Duration inf = absl::InfiniteDuration();
401   constexpr absl::Duration d = absl::Seconds(1);  // Any finite duration
402 
403   EXPECT_TRUE(inf == inf + inf);
404   EXPECT_TRUE(inf == inf + d);
405   EXPECT_TRUE(inf == inf - inf);
406   EXPECT_TRUE(-inf == d - inf);
407 
408   EXPECT_TRUE(inf == d * 1e100);
409   EXPECT_TRUE(0 == d / inf);  // NOLINT(readability/check)
410 
411   // Division by zero returns infinity, or kint64min/MAX where necessary.
412   EXPECT_TRUE(inf == d / 0);
413   EXPECT_TRUE(kint64max == d / absl::ZeroDuration());
414 }
415 
TEST(Duration,InfinityComparison)416 TEST(Duration, InfinityComparison) {
417   const absl::Duration inf = absl::InfiniteDuration();
418   const absl::Duration any_dur = absl::Seconds(1);
419 
420   // Equality
421   EXPECT_EQ(inf, inf);
422   EXPECT_EQ(-inf, -inf);
423   EXPECT_NE(inf, -inf);
424   EXPECT_NE(any_dur, inf);
425   EXPECT_NE(any_dur, -inf);
426 
427   // Relational
428   EXPECT_GT(inf, any_dur);
429   EXPECT_LT(-inf, any_dur);
430   EXPECT_LT(-inf, inf);
431   EXPECT_GT(inf, -inf);
432 }
433 
TEST(Duration,InfinityAddition)434 TEST(Duration, InfinityAddition) {
435   const absl::Duration sec_max = absl::Seconds(kint64max);
436   const absl::Duration sec_min = absl::Seconds(kint64min);
437   const absl::Duration any_dur = absl::Seconds(1);
438   const absl::Duration inf = absl::InfiniteDuration();
439 
440   // Addition
441   EXPECT_EQ(inf, inf + inf);
442   EXPECT_EQ(inf, inf + -inf);
443   EXPECT_EQ(-inf, -inf + inf);
444   EXPECT_EQ(-inf, -inf + -inf);
445 
446   EXPECT_EQ(inf, inf + any_dur);
447   EXPECT_EQ(inf, any_dur + inf);
448   EXPECT_EQ(-inf, -inf + any_dur);
449   EXPECT_EQ(-inf, any_dur + -inf);
450 
451   // Interesting case
452   absl::Duration almost_inf = sec_max + absl::Nanoseconds(999999999);
453   EXPECT_GT(inf, almost_inf);
454   almost_inf += -absl::Nanoseconds(999999999);
455   EXPECT_GT(inf, almost_inf);
456 
457   // Addition overflow/underflow
458   EXPECT_EQ(inf, sec_max + absl::Seconds(1));
459   EXPECT_EQ(inf, sec_max + sec_max);
460   EXPECT_EQ(-inf, sec_min + -absl::Seconds(1));
461   EXPECT_EQ(-inf, sec_min + -sec_max);
462 
463   // For reference: IEEE 754 behavior
464   const double dbl_inf = std::numeric_limits<double>::infinity();
465   EXPECT_TRUE(std::isinf(dbl_inf + dbl_inf));
466   EXPECT_TRUE(std::isnan(dbl_inf + -dbl_inf));  // We return inf
467   EXPECT_TRUE(std::isnan(-dbl_inf + dbl_inf));  // We return inf
468   EXPECT_TRUE(std::isinf(-dbl_inf + -dbl_inf));
469 }
470 
TEST(Duration,InfinitySubtraction)471 TEST(Duration, InfinitySubtraction) {
472   const absl::Duration sec_max = absl::Seconds(kint64max);
473   const absl::Duration sec_min = absl::Seconds(kint64min);
474   const absl::Duration any_dur = absl::Seconds(1);
475   const absl::Duration inf = absl::InfiniteDuration();
476 
477   // Subtraction
478   EXPECT_EQ(inf, inf - inf);
479   EXPECT_EQ(inf, inf - -inf);
480   EXPECT_EQ(-inf, -inf - inf);
481   EXPECT_EQ(-inf, -inf - -inf);
482 
483   EXPECT_EQ(inf, inf - any_dur);
484   EXPECT_EQ(-inf, any_dur - inf);
485   EXPECT_EQ(-inf, -inf - any_dur);
486   EXPECT_EQ(inf, any_dur - -inf);
487 
488   // Subtraction overflow/underflow
489   EXPECT_EQ(inf, sec_max - -absl::Seconds(1));
490   EXPECT_EQ(inf, sec_max - -sec_max);
491   EXPECT_EQ(-inf, sec_min - absl::Seconds(1));
492   EXPECT_EQ(-inf, sec_min - sec_max);
493 
494   // Interesting case
495   absl::Duration almost_neg_inf = sec_min;
496   EXPECT_LT(-inf, almost_neg_inf);
497   almost_neg_inf -= -absl::Nanoseconds(1);
498   EXPECT_LT(-inf, almost_neg_inf);
499 
500   // For reference: IEEE 754 behavior
501   const double dbl_inf = std::numeric_limits<double>::infinity();
502   EXPECT_TRUE(std::isnan(dbl_inf - dbl_inf));  // We return inf
503   EXPECT_TRUE(std::isinf(dbl_inf - -dbl_inf));
504   EXPECT_TRUE(std::isinf(-dbl_inf - dbl_inf));
505   EXPECT_TRUE(std::isnan(-dbl_inf - -dbl_inf));  // We return inf
506 }
507 
TEST(Duration,InfinityMultiplication)508 TEST(Duration, InfinityMultiplication) {
509   const absl::Duration sec_max = absl::Seconds(kint64max);
510   const absl::Duration sec_min = absl::Seconds(kint64min);
511   const absl::Duration inf = absl::InfiniteDuration();
512 
513 #define TEST_INF_MUL_WITH_TYPE(T)                                     \
514   EXPECT_EQ(inf, inf * static_cast<T>(2));                            \
515   EXPECT_EQ(-inf, inf * static_cast<T>(-2));                          \
516   EXPECT_EQ(-inf, -inf * static_cast<T>(2));                          \
517   EXPECT_EQ(inf, -inf * static_cast<T>(-2));                          \
518   EXPECT_EQ(inf, inf * static_cast<T>(0));                            \
519   EXPECT_EQ(-inf, -inf * static_cast<T>(0));                          \
520   EXPECT_EQ(inf, sec_max * static_cast<T>(2));                        \
521   EXPECT_EQ(inf, sec_min * static_cast<T>(-2));                       \
522   EXPECT_EQ(inf, (sec_max / static_cast<T>(2)) * static_cast<T>(3));  \
523   EXPECT_EQ(-inf, sec_max * static_cast<T>(-2));                      \
524   EXPECT_EQ(-inf, sec_min * static_cast<T>(2));                       \
525   EXPECT_EQ(-inf, (sec_min / static_cast<T>(2)) * static_cast<T>(3));
526 
527   TEST_INF_MUL_WITH_TYPE(int64_t);  // NOLINT(readability/function)
528   TEST_INF_MUL_WITH_TYPE(double);   // NOLINT(readability/function)
529 
530 #undef TEST_INF_MUL_WITH_TYPE
531 
532   const double dbl_inf = std::numeric_limits<double>::infinity();
533   EXPECT_EQ(inf, inf * dbl_inf);
534   EXPECT_EQ(-inf, -inf * dbl_inf);
535   EXPECT_EQ(-inf, inf * -dbl_inf);
536   EXPECT_EQ(inf, -inf * -dbl_inf);
537 
538   const absl::Duration any_dur = absl::Seconds(1);
539   EXPECT_EQ(inf, any_dur * dbl_inf);
540   EXPECT_EQ(-inf, -any_dur * dbl_inf);
541   EXPECT_EQ(-inf, any_dur * -dbl_inf);
542   EXPECT_EQ(inf, -any_dur * -dbl_inf);
543 
544   // Fixed-point multiplication will produce a finite value, whereas floating
545   // point fuzziness will overflow to inf.
546   EXPECT_NE(absl::InfiniteDuration(), absl::Seconds(1) * kint64max);
547   EXPECT_EQ(inf, absl::Seconds(1) * static_cast<double>(kint64max));
548   EXPECT_NE(-absl::InfiniteDuration(), absl::Seconds(1) * kint64min);
549   EXPECT_EQ(-inf, absl::Seconds(1) * static_cast<double>(kint64min));
550 
551   // Note that sec_max * or / by 1.0 overflows to inf due to the 53-bit
552   // limitations of double.
553   EXPECT_NE(inf, sec_max);
554   EXPECT_NE(inf, sec_max / 1);
555   EXPECT_EQ(inf, sec_max / 1.0);
556   EXPECT_NE(inf, sec_max * 1);
557   EXPECT_EQ(inf, sec_max * 1.0);
558 }
559 
TEST(Duration,InfinityDivision)560 TEST(Duration, InfinityDivision) {
561   const absl::Duration sec_max = absl::Seconds(kint64max);
562   const absl::Duration sec_min = absl::Seconds(kint64min);
563   const absl::Duration inf = absl::InfiniteDuration();
564 
565   // Division of Duration by a double
566 #define TEST_INF_DIV_WITH_TYPE(T)            \
567   EXPECT_EQ(inf, inf / static_cast<T>(2));   \
568   EXPECT_EQ(-inf, inf / static_cast<T>(-2)); \
569   EXPECT_EQ(-inf, -inf / static_cast<T>(2)); \
570   EXPECT_EQ(inf, -inf / static_cast<T>(-2));
571 
572   TEST_INF_DIV_WITH_TYPE(int64_t);  // NOLINT(readability/function)
573   TEST_INF_DIV_WITH_TYPE(double);   // NOLINT(readability/function)
574 
575 #undef TEST_INF_DIV_WITH_TYPE
576 
577   // Division of Duration by a double overflow/underflow
578   EXPECT_EQ(inf, sec_max / 0.5);
579   EXPECT_EQ(inf, sec_min / -0.5);
580   EXPECT_EQ(inf, ((sec_max / 0.5) + absl::Seconds(1)) / 0.5);
581   EXPECT_EQ(-inf, sec_max / -0.5);
582   EXPECT_EQ(-inf, sec_min / 0.5);
583   EXPECT_EQ(-inf, ((sec_min / 0.5) - absl::Seconds(1)) / 0.5);
584 
585   const double dbl_inf = std::numeric_limits<double>::infinity();
586   EXPECT_EQ(inf, inf / dbl_inf);
587   EXPECT_EQ(-inf, inf / -dbl_inf);
588   EXPECT_EQ(-inf, -inf / dbl_inf);
589   EXPECT_EQ(inf, -inf / -dbl_inf);
590 
591   const absl::Duration any_dur = absl::Seconds(1);
592   EXPECT_EQ(absl::ZeroDuration(), any_dur / dbl_inf);
593   EXPECT_EQ(absl::ZeroDuration(), any_dur / -dbl_inf);
594   EXPECT_EQ(absl::ZeroDuration(), -any_dur / dbl_inf);
595   EXPECT_EQ(absl::ZeroDuration(), -any_dur / -dbl_inf);
596 }
597 
TEST(Duration,InfinityModulus)598 TEST(Duration, InfinityModulus) {
599   const absl::Duration sec_max = absl::Seconds(kint64max);
600   const absl::Duration any_dur = absl::Seconds(1);
601   const absl::Duration inf = absl::InfiniteDuration();
602 
603   EXPECT_EQ(inf, inf % inf);
604   EXPECT_EQ(inf, inf % -inf);
605   EXPECT_EQ(-inf, -inf % -inf);
606   EXPECT_EQ(-inf, -inf % inf);
607 
608   EXPECT_EQ(any_dur, any_dur % inf);
609   EXPECT_EQ(any_dur, any_dur % -inf);
610   EXPECT_EQ(-any_dur, -any_dur % inf);
611   EXPECT_EQ(-any_dur, -any_dur % -inf);
612 
613   EXPECT_EQ(inf, inf % -any_dur);
614   EXPECT_EQ(inf, inf % any_dur);
615   EXPECT_EQ(-inf, -inf % -any_dur);
616   EXPECT_EQ(-inf, -inf % any_dur);
617 
618   // Remainder isn't affected by overflow.
619   EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Seconds(1));
620   EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Milliseconds(1));
621   EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Microseconds(1));
622   EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Nanoseconds(1));
623   EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Nanoseconds(1) / 4);
624 }
625 
TEST(Duration,InfinityIDiv)626 TEST(Duration, InfinityIDiv) {
627   const absl::Duration sec_max = absl::Seconds(kint64max);
628   const absl::Duration any_dur = absl::Seconds(1);
629   const absl::Duration inf = absl::InfiniteDuration();
630   const double dbl_inf = std::numeric_limits<double>::infinity();
631 
632   // IDivDuration (int64_t return value + a remainer)
633   absl::Duration rem = absl::ZeroDuration();
634   EXPECT_EQ(kint64max, absl::IDivDuration(inf, inf, &rem));
635   EXPECT_EQ(inf, rem);
636 
637   rem = absl::ZeroDuration();
638   EXPECT_EQ(kint64max, absl::IDivDuration(-inf, -inf, &rem));
639   EXPECT_EQ(-inf, rem);
640 
641   rem = absl::ZeroDuration();
642   EXPECT_EQ(kint64max, absl::IDivDuration(inf, any_dur, &rem));
643   EXPECT_EQ(inf, rem);
644 
645   rem = absl::ZeroDuration();
646   EXPECT_EQ(0, absl::IDivDuration(any_dur, inf, &rem));
647   EXPECT_EQ(any_dur, rem);
648 
649   rem = absl::ZeroDuration();
650   EXPECT_EQ(kint64max, absl::IDivDuration(-inf, -any_dur, &rem));
651   EXPECT_EQ(-inf, rem);
652 
653   rem = absl::ZeroDuration();
654   EXPECT_EQ(0, absl::IDivDuration(-any_dur, -inf, &rem));
655   EXPECT_EQ(-any_dur, rem);
656 
657   rem = absl::ZeroDuration();
658   EXPECT_EQ(kint64min, absl::IDivDuration(-inf, inf, &rem));
659   EXPECT_EQ(-inf, rem);
660 
661   rem = absl::ZeroDuration();
662   EXPECT_EQ(kint64min, absl::IDivDuration(inf, -inf, &rem));
663   EXPECT_EQ(inf, rem);
664 
665   rem = absl::ZeroDuration();
666   EXPECT_EQ(kint64min, absl::IDivDuration(-inf, any_dur, &rem));
667   EXPECT_EQ(-inf, rem);
668 
669   rem = absl::ZeroDuration();
670   EXPECT_EQ(0, absl::IDivDuration(-any_dur, inf, &rem));
671   EXPECT_EQ(-any_dur, rem);
672 
673   rem = absl::ZeroDuration();
674   EXPECT_EQ(kint64min, absl::IDivDuration(inf, -any_dur, &rem));
675   EXPECT_EQ(inf, rem);
676 
677   rem = absl::ZeroDuration();
678   EXPECT_EQ(0, absl::IDivDuration(any_dur, -inf, &rem));
679   EXPECT_EQ(any_dur, rem);
680 
681   // IDivDuration overflow/underflow
682   rem = any_dur;
683   EXPECT_EQ(kint64max,
684             absl::IDivDuration(sec_max, absl::Nanoseconds(1) / 4, &rem));
685   EXPECT_EQ(sec_max - absl::Nanoseconds(kint64max) / 4, rem);
686 
687   rem = any_dur;
688   EXPECT_EQ(kint64max,
689             absl::IDivDuration(sec_max, absl::Milliseconds(1), &rem));
690   EXPECT_EQ(sec_max - absl::Milliseconds(kint64max), rem);
691 
692   rem = any_dur;
693   EXPECT_EQ(kint64max,
694             absl::IDivDuration(-sec_max, -absl::Milliseconds(1), &rem));
695   EXPECT_EQ(-sec_max + absl::Milliseconds(kint64max), rem);
696 
697   rem = any_dur;
698   EXPECT_EQ(kint64min,
699             absl::IDivDuration(-sec_max, absl::Milliseconds(1), &rem));
700   EXPECT_EQ(-sec_max - absl::Milliseconds(kint64min), rem);
701 
702   rem = any_dur;
703   EXPECT_EQ(kint64min,
704             absl::IDivDuration(sec_max, -absl::Milliseconds(1), &rem));
705   EXPECT_EQ(sec_max + absl::Milliseconds(kint64min), rem);
706 
707   //
708   // operator/(Duration, Duration) is a wrapper for IDivDuration().
709   //
710 
711   // IEEE 754 says inf / inf should be nan, but int64_t doesn't have
712   // nan so we'll return kint64max/kint64min instead.
713   EXPECT_TRUE(std::isnan(dbl_inf / dbl_inf));
714   EXPECT_EQ(kint64max, inf / inf);
715   EXPECT_EQ(kint64max, -inf / -inf);
716   EXPECT_EQ(kint64min, -inf / inf);
717   EXPECT_EQ(kint64min, inf / -inf);
718 
719   EXPECT_TRUE(std::isinf(dbl_inf / 2.0));
720   EXPECT_EQ(kint64max, inf / any_dur);
721   EXPECT_EQ(kint64max, -inf / -any_dur);
722   EXPECT_EQ(kint64min, -inf / any_dur);
723   EXPECT_EQ(kint64min, inf / -any_dur);
724 
725   EXPECT_EQ(0.0, 2.0 / dbl_inf);
726   EXPECT_EQ(0, any_dur / inf);
727   EXPECT_EQ(0, any_dur / -inf);
728   EXPECT_EQ(0, -any_dur / inf);
729   EXPECT_EQ(0, -any_dur / -inf);
730   EXPECT_EQ(0, absl::ZeroDuration() / inf);
731 
732   // Division of Duration by a Duration overflow/underflow
733   EXPECT_EQ(kint64max, sec_max / absl::Milliseconds(1));
734   EXPECT_EQ(kint64max, -sec_max / -absl::Milliseconds(1));
735   EXPECT_EQ(kint64min, -sec_max / absl::Milliseconds(1));
736   EXPECT_EQ(kint64min, sec_max / -absl::Milliseconds(1));
737 }
738 
TEST(Duration,InfinityFDiv)739 TEST(Duration, InfinityFDiv) {
740   const absl::Duration any_dur = absl::Seconds(1);
741   const absl::Duration inf = absl::InfiniteDuration();
742   const double dbl_inf = std::numeric_limits<double>::infinity();
743 
744   EXPECT_EQ(dbl_inf, absl::FDivDuration(inf, inf));
745   EXPECT_EQ(dbl_inf, absl::FDivDuration(-inf, -inf));
746   EXPECT_EQ(dbl_inf, absl::FDivDuration(inf, any_dur));
747   EXPECT_EQ(0.0, absl::FDivDuration(any_dur, inf));
748   EXPECT_EQ(dbl_inf, absl::FDivDuration(-inf, -any_dur));
749   EXPECT_EQ(0.0, absl::FDivDuration(-any_dur, -inf));
750 
751   EXPECT_EQ(-dbl_inf, absl::FDivDuration(-inf, inf));
752   EXPECT_EQ(-dbl_inf, absl::FDivDuration(inf, -inf));
753   EXPECT_EQ(-dbl_inf, absl::FDivDuration(-inf, any_dur));
754   EXPECT_EQ(0.0, absl::FDivDuration(-any_dur, inf));
755   EXPECT_EQ(-dbl_inf, absl::FDivDuration(inf, -any_dur));
756   EXPECT_EQ(0.0, absl::FDivDuration(any_dur, -inf));
757 }
758 
TEST(Duration,DivisionByZero)759 TEST(Duration, DivisionByZero) {
760   const absl::Duration zero = absl::ZeroDuration();
761   const absl::Duration inf = absl::InfiniteDuration();
762   const absl::Duration any_dur = absl::Seconds(1);
763   const double dbl_inf = std::numeric_limits<double>::infinity();
764   const double dbl_denorm = std::numeric_limits<double>::denorm_min();
765 
766   // Operator/(Duration, double)
767   EXPECT_EQ(inf, zero / 0.0);
768   EXPECT_EQ(-inf, zero / -0.0);
769   EXPECT_EQ(inf, any_dur / 0.0);
770   EXPECT_EQ(-inf, any_dur / -0.0);
771   EXPECT_EQ(-inf, -any_dur / 0.0);
772   EXPECT_EQ(inf, -any_dur / -0.0);
773 
774   // Tests dividing by a number very close to, but not quite zero.
775   EXPECT_EQ(zero, zero / dbl_denorm);
776   EXPECT_EQ(zero, zero / -dbl_denorm);
777   EXPECT_EQ(inf, any_dur / dbl_denorm);
778   EXPECT_EQ(-inf, any_dur / -dbl_denorm);
779   EXPECT_EQ(-inf, -any_dur / dbl_denorm);
780   EXPECT_EQ(inf, -any_dur / -dbl_denorm);
781 
782   // IDiv
783   absl::Duration rem = zero;
784   EXPECT_EQ(kint64max, absl::IDivDuration(zero, zero, &rem));
785   EXPECT_EQ(inf, rem);
786 
787   rem = zero;
788   EXPECT_EQ(kint64max, absl::IDivDuration(any_dur, zero, &rem));
789   EXPECT_EQ(inf, rem);
790 
791   rem = zero;
792   EXPECT_EQ(kint64min, absl::IDivDuration(-any_dur, zero, &rem));
793   EXPECT_EQ(-inf, rem);
794 
795   // Operator/(Duration, Duration)
796   EXPECT_EQ(kint64max, zero / zero);
797   EXPECT_EQ(kint64max, any_dur / zero);
798   EXPECT_EQ(kint64min, -any_dur / zero);
799 
800   // FDiv
801   EXPECT_EQ(dbl_inf, absl::FDivDuration(zero, zero));
802   EXPECT_EQ(dbl_inf, absl::FDivDuration(any_dur, zero));
803   EXPECT_EQ(-dbl_inf, absl::FDivDuration(-any_dur, zero));
804 }
805 
TEST(Duration,NaN)806 TEST(Duration, NaN) {
807   // Note that IEEE 754 does not define the behavior of a nan's sign when it is
808   // copied, so the code below allows for either + or - InfiniteDuration.
809 #define TEST_NAN_HANDLING(NAME, NAN)           \
810   do {                                         \
811     const auto inf = absl::InfiniteDuration(); \
812     auto x = NAME(NAN);                        \
813     EXPECT_TRUE(x == inf || x == -inf);        \
814     auto y = NAME(42);                         \
815     y *= NAN;                                  \
816     EXPECT_TRUE(y == inf || y == -inf);        \
817     auto z = NAME(42);                         \
818     z /= NAN;                                  \
819     EXPECT_TRUE(z == inf || z == -inf);        \
820   } while (0)
821 
822   const double nan = std::numeric_limits<double>::quiet_NaN();
823   TEST_NAN_HANDLING(absl::Nanoseconds, nan);
824   TEST_NAN_HANDLING(absl::Microseconds, nan);
825   TEST_NAN_HANDLING(absl::Milliseconds, nan);
826   TEST_NAN_HANDLING(absl::Seconds, nan);
827   TEST_NAN_HANDLING(absl::Minutes, nan);
828   TEST_NAN_HANDLING(absl::Hours, nan);
829 
830   TEST_NAN_HANDLING(absl::Nanoseconds, -nan);
831   TEST_NAN_HANDLING(absl::Microseconds, -nan);
832   TEST_NAN_HANDLING(absl::Milliseconds, -nan);
833   TEST_NAN_HANDLING(absl::Seconds, -nan);
834   TEST_NAN_HANDLING(absl::Minutes, -nan);
835   TEST_NAN_HANDLING(absl::Hours, -nan);
836 
837 #undef TEST_NAN_HANDLING
838 }
839 
TEST(Duration,Range)840 TEST(Duration, Range) {
841   const absl::Duration range = ApproxYears(100 * 1e9);
842   const absl::Duration range_future = range;
843   const absl::Duration range_past = -range;
844 
845   EXPECT_LT(range_future, absl::InfiniteDuration());
846   EXPECT_GT(range_past, -absl::InfiniteDuration());
847 
848   const absl::Duration full_range = range_future - range_past;
849   EXPECT_GT(full_range, absl::ZeroDuration());
850   EXPECT_LT(full_range, absl::InfiniteDuration());
851 
852   const absl::Duration neg_full_range = range_past - range_future;
853   EXPECT_LT(neg_full_range, absl::ZeroDuration());
854   EXPECT_GT(neg_full_range, -absl::InfiniteDuration());
855 
856   EXPECT_LT(neg_full_range, full_range);
857   EXPECT_EQ(neg_full_range, -full_range);
858 }
859 
TEST(Duration,RelationalOperators)860 TEST(Duration, RelationalOperators) {
861 #define TEST_REL_OPS(UNIT)               \
862   static_assert(UNIT(2) == UNIT(2), ""); \
863   static_assert(UNIT(1) != UNIT(2), ""); \
864   static_assert(UNIT(1) < UNIT(2), "");  \
865   static_assert(UNIT(3) > UNIT(2), "");  \
866   static_assert(UNIT(1) <= UNIT(2), ""); \
867   static_assert(UNIT(2) <= UNIT(2), ""); \
868   static_assert(UNIT(3) >= UNIT(2), ""); \
869   static_assert(UNIT(2) >= UNIT(2), "");
870 
871   TEST_REL_OPS(absl::Nanoseconds);
872   TEST_REL_OPS(absl::Microseconds);
873   TEST_REL_OPS(absl::Milliseconds);
874   TEST_REL_OPS(absl::Seconds);
875   TEST_REL_OPS(absl::Minutes);
876   TEST_REL_OPS(absl::Hours);
877 
878 #undef TEST_REL_OPS
879 }
880 
TEST(Duration,Addition)881 TEST(Duration, Addition) {
882 #define TEST_ADD_OPS(UNIT)                  \
883   do {                                      \
884     EXPECT_EQ(UNIT(2), UNIT(1) + UNIT(1));  \
885     EXPECT_EQ(UNIT(1), UNIT(2) - UNIT(1));  \
886     EXPECT_EQ(UNIT(0), UNIT(2) - UNIT(2));  \
887     EXPECT_EQ(UNIT(-1), UNIT(1) - UNIT(2)); \
888     EXPECT_EQ(UNIT(-2), UNIT(0) - UNIT(2)); \
889     EXPECT_EQ(UNIT(-2), UNIT(1) - UNIT(3)); \
890     absl::Duration a = UNIT(1);             \
891     a += UNIT(1);                           \
892     EXPECT_EQ(UNIT(2), a);                  \
893     a -= UNIT(1);                           \
894     EXPECT_EQ(UNIT(1), a);                  \
895   } while (0)
896 
897   TEST_ADD_OPS(absl::Nanoseconds);
898   TEST_ADD_OPS(absl::Microseconds);
899   TEST_ADD_OPS(absl::Milliseconds);
900   TEST_ADD_OPS(absl::Seconds);
901   TEST_ADD_OPS(absl::Minutes);
902   TEST_ADD_OPS(absl::Hours);
903 
904 #undef TEST_ADD_OPS
905 
906   EXPECT_EQ(absl::Seconds(2), absl::Seconds(3) - 2 * absl::Milliseconds(500));
907   EXPECT_EQ(absl::Seconds(2) + absl::Milliseconds(500),
908             absl::Seconds(3) - absl::Milliseconds(500));
909 
910   EXPECT_EQ(absl::Seconds(1) + absl::Milliseconds(998),
911             absl::Milliseconds(999) + absl::Milliseconds(999));
912 
913   EXPECT_EQ(absl::Milliseconds(-1),
914             absl::Milliseconds(998) - absl::Milliseconds(999));
915 
916   // Tests fractions of a nanoseconds. These are implementation details only.
917   EXPECT_GT(absl::Nanoseconds(1), absl::Nanoseconds(1) / 2);
918   EXPECT_EQ(absl::Nanoseconds(1),
919             absl::Nanoseconds(1) / 2 + absl::Nanoseconds(1) / 2);
920   EXPECT_GT(absl::Nanoseconds(1) / 4, absl::Nanoseconds(0));
921   EXPECT_EQ(absl::Nanoseconds(1) / 8, absl::Nanoseconds(0));
922 
923   // Tests subtraction that will cause wrap around of the rep_lo_ bits.
924   absl::Duration d_7_5 = absl::Seconds(7) + absl::Milliseconds(500);
925   absl::Duration d_3_7 = absl::Seconds(3) + absl::Milliseconds(700);
926   absl::Duration ans_3_8 = absl::Seconds(3) + absl::Milliseconds(800);
927   EXPECT_EQ(ans_3_8, d_7_5 - d_3_7);
928 
929   // Subtracting min_duration
930   absl::Duration min_dur = absl::Seconds(kint64min);
931   EXPECT_EQ(absl::Seconds(0), min_dur - min_dur);
932   EXPECT_EQ(absl::Seconds(kint64max), absl::Seconds(-1) - min_dur);
933 }
934 
TEST(Duration,Negation)935 TEST(Duration, Negation) {
936   // By storing negations of various values in constexpr variables we
937   // verify that the initializers are constant expressions.
938   constexpr absl::Duration negated_zero_duration = -absl::ZeroDuration();
939   EXPECT_EQ(negated_zero_duration, absl::ZeroDuration());
940 
941   constexpr absl::Duration negated_infinite_duration =
942       -absl::InfiniteDuration();
943   EXPECT_NE(negated_infinite_duration, absl::InfiniteDuration());
944   EXPECT_EQ(-negated_infinite_duration, absl::InfiniteDuration());
945 
946   // The public APIs to check if a duration is infinite depend on using
947   // -InfiniteDuration(), but we're trying to test operator- here, so we
948   // need to use the lower-level internal query IsInfiniteDuration.
949   EXPECT_TRUE(
950       absl::time_internal::IsInfiniteDuration(negated_infinite_duration));
951 
952   // The largest Duration is kint64max seconds and kTicksPerSecond - 1 ticks.
953   // Using the absl::time_internal::MakeDuration API is the cleanest way to
954   // construct that Duration.
955   constexpr absl::Duration max_duration = absl::time_internal::MakeDuration(
956       kint64max, absl::time_internal::kTicksPerSecond - 1);
957   constexpr absl::Duration negated_max_duration = -max_duration;
958   // The largest negatable value is one tick above the minimum representable;
959   // it's the negation of max_duration.
960   constexpr absl::Duration nearly_min_duration =
961       absl::time_internal::MakeDuration(kint64min, int64_t{1});
962   constexpr absl::Duration negated_nearly_min_duration = -nearly_min_duration;
963 
964   EXPECT_EQ(negated_max_duration, nearly_min_duration);
965   EXPECT_EQ(negated_nearly_min_duration, max_duration);
966   EXPECT_EQ(-(-max_duration), max_duration);
967 
968   constexpr absl::Duration min_duration =
969       absl::time_internal::MakeDuration(kint64min);
970   constexpr absl::Duration negated_min_duration = -min_duration;
971   EXPECT_EQ(negated_min_duration, absl::InfiniteDuration());
972 }
973 
TEST(Duration,AbsoluteValue)974 TEST(Duration, AbsoluteValue) {
975   EXPECT_EQ(absl::ZeroDuration(), AbsDuration(absl::ZeroDuration()));
976   EXPECT_EQ(absl::Seconds(1), AbsDuration(absl::Seconds(1)));
977   EXPECT_EQ(absl::Seconds(1), AbsDuration(absl::Seconds(-1)));
978 
979   EXPECT_EQ(absl::InfiniteDuration(), AbsDuration(absl::InfiniteDuration()));
980   EXPECT_EQ(absl::InfiniteDuration(), AbsDuration(-absl::InfiniteDuration()));
981 
982   absl::Duration max_dur =
983       absl::Seconds(kint64max) + (absl::Seconds(1) - absl::Nanoseconds(1) / 4);
984   EXPECT_EQ(max_dur, AbsDuration(max_dur));
985 
986   absl::Duration min_dur = absl::Seconds(kint64min);
987   EXPECT_EQ(absl::InfiniteDuration(), AbsDuration(min_dur));
988   EXPECT_EQ(max_dur, AbsDuration(min_dur + absl::Nanoseconds(1) / 4));
989 }
990 
TEST(Duration,Multiplication)991 TEST(Duration, Multiplication) {
992 #define TEST_MUL_OPS(UNIT)                                    \
993   do {                                                        \
994     EXPECT_EQ(UNIT(5), UNIT(2) * 2.5);                        \
995     EXPECT_EQ(UNIT(2), UNIT(5) / 2.5);                        \
996     EXPECT_EQ(UNIT(-5), UNIT(-2) * 2.5);                      \
997     EXPECT_EQ(UNIT(-5), -UNIT(2) * 2.5);                      \
998     EXPECT_EQ(UNIT(-5), UNIT(2) * -2.5);                      \
999     EXPECT_EQ(UNIT(-2), UNIT(-5) / 2.5);                      \
1000     EXPECT_EQ(UNIT(-2), -UNIT(5) / 2.5);                      \
1001     EXPECT_EQ(UNIT(-2), UNIT(5) / -2.5);                      \
1002     EXPECT_EQ(UNIT(2), UNIT(11) % UNIT(3));                   \
1003     absl::Duration a = UNIT(2);                               \
1004     a *= 2.5;                                                 \
1005     EXPECT_EQ(UNIT(5), a);                                    \
1006     a /= 2.5;                                                 \
1007     EXPECT_EQ(UNIT(2), a);                                    \
1008     a %= UNIT(1);                                             \
1009     EXPECT_EQ(UNIT(0), a);                                    \
1010     absl::Duration big = UNIT(1000000000);                    \
1011     big *= 3;                                                 \
1012     big /= 3;                                                 \
1013     EXPECT_EQ(UNIT(1000000000), big);                         \
1014     EXPECT_EQ(-UNIT(2), -UNIT(2));                            \
1015     EXPECT_EQ(-UNIT(2), UNIT(2) * -1);                        \
1016     EXPECT_EQ(-UNIT(2), -1 * UNIT(2));                        \
1017     EXPECT_EQ(-UNIT(-2), UNIT(2));                            \
1018     EXPECT_EQ(2, UNIT(2) / UNIT(1));                          \
1019     absl::Duration rem;                                       \
1020     EXPECT_EQ(2, absl::IDivDuration(UNIT(2), UNIT(1), &rem)); \
1021     EXPECT_EQ(2.0, absl::FDivDuration(UNIT(2), UNIT(1)));     \
1022   } while (0)
1023 
1024   TEST_MUL_OPS(absl::Nanoseconds);
1025   TEST_MUL_OPS(absl::Microseconds);
1026   TEST_MUL_OPS(absl::Milliseconds);
1027   TEST_MUL_OPS(absl::Seconds);
1028   TEST_MUL_OPS(absl::Minutes);
1029   TEST_MUL_OPS(absl::Hours);
1030 
1031 #undef TEST_MUL_OPS
1032 
1033   // Ensures that multiplication and division by 1 with a maxed-out durations
1034   // doesn't lose precision.
1035   absl::Duration max_dur =
1036       absl::Seconds(kint64max) + (absl::Seconds(1) - absl::Nanoseconds(1) / 4);
1037   absl::Duration min_dur = absl::Seconds(kint64min);
1038   EXPECT_EQ(max_dur, max_dur * 1);
1039   EXPECT_EQ(max_dur, max_dur / 1);
1040   EXPECT_EQ(min_dur, min_dur * 1);
1041   EXPECT_EQ(min_dur, min_dur / 1);
1042 
1043   // Tests division on a Duration with a large number of significant digits.
1044   // Tests when the digits span hi and lo as well as only in hi.
1045   absl::Duration sigfigs = absl::Seconds(2000000000) + absl::Nanoseconds(3);
1046   EXPECT_EQ(absl::Seconds(666666666) + absl::Nanoseconds(666666667) +
1047                 absl::Nanoseconds(1) / 2,
1048             sigfigs / 3);
1049   sigfigs = absl::Seconds(int64_t{7000000000});
1050   EXPECT_EQ(absl::Seconds(2333333333) + absl::Nanoseconds(333333333) +
1051                 absl::Nanoseconds(1) / 4,
1052             sigfigs / 3);
1053 
1054   EXPECT_EQ(absl::Seconds(7) + absl::Milliseconds(500), absl::Seconds(3) * 2.5);
1055   EXPECT_EQ(absl::Seconds(8) * -1 + absl::Milliseconds(300),
1056             (absl::Seconds(2) + absl::Milliseconds(200)) * -3.5);
1057   EXPECT_EQ(-absl::Seconds(8) + absl::Milliseconds(300),
1058             (absl::Seconds(2) + absl::Milliseconds(200)) * -3.5);
1059   EXPECT_EQ(absl::Seconds(1) + absl::Milliseconds(875),
1060             (absl::Seconds(7) + absl::Milliseconds(500)) / 4);
1061   EXPECT_EQ(absl::Seconds(30),
1062             (absl::Seconds(7) + absl::Milliseconds(500)) / 0.25);
1063   EXPECT_EQ(absl::Seconds(3),
1064             (absl::Seconds(7) + absl::Milliseconds(500)) / 2.5);
1065 
1066   // Tests division remainder.
1067   EXPECT_EQ(absl::Nanoseconds(0), absl::Nanoseconds(7) % absl::Nanoseconds(1));
1068   EXPECT_EQ(absl::Nanoseconds(0), absl::Nanoseconds(0) % absl::Nanoseconds(10));
1069   EXPECT_EQ(absl::Nanoseconds(2), absl::Nanoseconds(7) % absl::Nanoseconds(5));
1070   EXPECT_EQ(absl::Nanoseconds(2), absl::Nanoseconds(2) % absl::Nanoseconds(5));
1071 
1072   EXPECT_EQ(absl::Nanoseconds(1), absl::Nanoseconds(10) % absl::Nanoseconds(3));
1073   EXPECT_EQ(absl::Nanoseconds(1),
1074             absl::Nanoseconds(10) % absl::Nanoseconds(-3));
1075   EXPECT_EQ(absl::Nanoseconds(-1),
1076             absl::Nanoseconds(-10) % absl::Nanoseconds(3));
1077   EXPECT_EQ(absl::Nanoseconds(-1),
1078             absl::Nanoseconds(-10) % absl::Nanoseconds(-3));
1079 
1080   EXPECT_EQ(absl::Milliseconds(100),
1081             absl::Seconds(1) % absl::Milliseconds(300));
1082   EXPECT_EQ(
1083       absl::Milliseconds(300),
1084       (absl::Seconds(3) + absl::Milliseconds(800)) % absl::Milliseconds(500));
1085 
1086   EXPECT_EQ(absl::Nanoseconds(1), absl::Nanoseconds(1) % absl::Seconds(1));
1087   EXPECT_EQ(absl::Nanoseconds(-1), absl::Nanoseconds(-1) % absl::Seconds(1));
1088   EXPECT_EQ(0, absl::Nanoseconds(-1) / absl::Seconds(1));  // Actual -1e-9
1089 
1090   // Tests identity a = (a/b)*b + a%b
1091 #define TEST_MOD_IDENTITY(a, b) \
1092   EXPECT_EQ((a), ((a) / (b))*(b) + ((a)%(b)))
1093 
1094   TEST_MOD_IDENTITY(absl::Seconds(0), absl::Seconds(2));
1095   TEST_MOD_IDENTITY(absl::Seconds(1), absl::Seconds(1));
1096   TEST_MOD_IDENTITY(absl::Seconds(1), absl::Seconds(2));
1097   TEST_MOD_IDENTITY(absl::Seconds(2), absl::Seconds(1));
1098 
1099   TEST_MOD_IDENTITY(absl::Seconds(-2), absl::Seconds(1));
1100   TEST_MOD_IDENTITY(absl::Seconds(2), absl::Seconds(-1));
1101   TEST_MOD_IDENTITY(absl::Seconds(-2), absl::Seconds(-1));
1102 
1103   TEST_MOD_IDENTITY(absl::Nanoseconds(0), absl::Nanoseconds(2));
1104   TEST_MOD_IDENTITY(absl::Nanoseconds(1), absl::Nanoseconds(1));
1105   TEST_MOD_IDENTITY(absl::Nanoseconds(1), absl::Nanoseconds(2));
1106   TEST_MOD_IDENTITY(absl::Nanoseconds(2), absl::Nanoseconds(1));
1107 
1108   TEST_MOD_IDENTITY(absl::Nanoseconds(-2), absl::Nanoseconds(1));
1109   TEST_MOD_IDENTITY(absl::Nanoseconds(2), absl::Nanoseconds(-1));
1110   TEST_MOD_IDENTITY(absl::Nanoseconds(-2), absl::Nanoseconds(-1));
1111 
1112   // Mixed seconds + subseconds
1113   absl::Duration mixed_a = absl::Seconds(1) + absl::Nanoseconds(2);
1114   absl::Duration mixed_b = absl::Seconds(1) + absl::Nanoseconds(3);
1115 
1116   TEST_MOD_IDENTITY(absl::Seconds(0), mixed_a);
1117   TEST_MOD_IDENTITY(mixed_a, mixed_a);
1118   TEST_MOD_IDENTITY(mixed_a, mixed_b);
1119   TEST_MOD_IDENTITY(mixed_b, mixed_a);
1120 
1121   TEST_MOD_IDENTITY(-mixed_a, mixed_b);
1122   TEST_MOD_IDENTITY(mixed_a, -mixed_b);
1123   TEST_MOD_IDENTITY(-mixed_a, -mixed_b);
1124 
1125 #undef TEST_MOD_IDENTITY
1126 }
1127 
TEST(Duration,Truncation)1128 TEST(Duration, Truncation) {
1129   const absl::Duration d = absl::Nanoseconds(1234567890);
1130   const absl::Duration inf = absl::InfiniteDuration();
1131   for (int unit_sign : {1, -1}) {  // sign shouldn't matter
1132     EXPECT_EQ(absl::Nanoseconds(1234567890),
1133               Trunc(d, unit_sign * absl::Nanoseconds(1)));
1134     EXPECT_EQ(absl::Microseconds(1234567),
1135               Trunc(d, unit_sign * absl::Microseconds(1)));
1136     EXPECT_EQ(absl::Milliseconds(1234),
1137               Trunc(d, unit_sign * absl::Milliseconds(1)));
1138     EXPECT_EQ(absl::Seconds(1), Trunc(d, unit_sign * absl::Seconds(1)));
1139     EXPECT_EQ(inf, Trunc(inf, unit_sign * absl::Seconds(1)));
1140 
1141     EXPECT_EQ(absl::Nanoseconds(-1234567890),
1142               Trunc(-d, unit_sign * absl::Nanoseconds(1)));
1143     EXPECT_EQ(absl::Microseconds(-1234567),
1144               Trunc(-d, unit_sign * absl::Microseconds(1)));
1145     EXPECT_EQ(absl::Milliseconds(-1234),
1146               Trunc(-d, unit_sign * absl::Milliseconds(1)));
1147     EXPECT_EQ(absl::Seconds(-1), Trunc(-d, unit_sign * absl::Seconds(1)));
1148     EXPECT_EQ(-inf, Trunc(-inf, unit_sign * absl::Seconds(1)));
1149   }
1150 }
1151 
TEST(Duration,Flooring)1152 TEST(Duration, Flooring) {
1153   const absl::Duration d = absl::Nanoseconds(1234567890);
1154   const absl::Duration inf = absl::InfiniteDuration();
1155   for (int unit_sign : {1, -1}) {  // sign shouldn't matter
1156     EXPECT_EQ(absl::Nanoseconds(1234567890),
1157               absl::Floor(d, unit_sign * absl::Nanoseconds(1)));
1158     EXPECT_EQ(absl::Microseconds(1234567),
1159               absl::Floor(d, unit_sign * absl::Microseconds(1)));
1160     EXPECT_EQ(absl::Milliseconds(1234),
1161               absl::Floor(d, unit_sign * absl::Milliseconds(1)));
1162     EXPECT_EQ(absl::Seconds(1), absl::Floor(d, unit_sign * absl::Seconds(1)));
1163     EXPECT_EQ(inf, absl::Floor(inf, unit_sign * absl::Seconds(1)));
1164 
1165     EXPECT_EQ(absl::Nanoseconds(-1234567890),
1166               absl::Floor(-d, unit_sign * absl::Nanoseconds(1)));
1167     EXPECT_EQ(absl::Microseconds(-1234568),
1168               absl::Floor(-d, unit_sign * absl::Microseconds(1)));
1169     EXPECT_EQ(absl::Milliseconds(-1235),
1170               absl::Floor(-d, unit_sign * absl::Milliseconds(1)));
1171     EXPECT_EQ(absl::Seconds(-2), absl::Floor(-d, unit_sign * absl::Seconds(1)));
1172     EXPECT_EQ(-inf, absl::Floor(-inf, unit_sign * absl::Seconds(1)));
1173   }
1174 }
1175 
TEST(Duration,Ceiling)1176 TEST(Duration, Ceiling) {
1177   const absl::Duration d = absl::Nanoseconds(1234567890);
1178   const absl::Duration inf = absl::InfiniteDuration();
1179   for (int unit_sign : {1, -1}) {  // // sign shouldn't matter
1180     EXPECT_EQ(absl::Nanoseconds(1234567890),
1181               absl::Ceil(d, unit_sign * absl::Nanoseconds(1)));
1182     EXPECT_EQ(absl::Microseconds(1234568),
1183               absl::Ceil(d, unit_sign * absl::Microseconds(1)));
1184     EXPECT_EQ(absl::Milliseconds(1235),
1185               absl::Ceil(d, unit_sign * absl::Milliseconds(1)));
1186     EXPECT_EQ(absl::Seconds(2), absl::Ceil(d, unit_sign * absl::Seconds(1)));
1187     EXPECT_EQ(inf, absl::Ceil(inf, unit_sign * absl::Seconds(1)));
1188 
1189     EXPECT_EQ(absl::Nanoseconds(-1234567890),
1190               absl::Ceil(-d, unit_sign * absl::Nanoseconds(1)));
1191     EXPECT_EQ(absl::Microseconds(-1234567),
1192               absl::Ceil(-d, unit_sign * absl::Microseconds(1)));
1193     EXPECT_EQ(absl::Milliseconds(-1234),
1194               absl::Ceil(-d, unit_sign * absl::Milliseconds(1)));
1195     EXPECT_EQ(absl::Seconds(-1), absl::Ceil(-d, unit_sign * absl::Seconds(1)));
1196     EXPECT_EQ(-inf, absl::Ceil(-inf, unit_sign * absl::Seconds(1)));
1197   }
1198 }
1199 
TEST(Duration,RoundTripUnits)1200 TEST(Duration, RoundTripUnits) {
1201   const int kRange = 100000;
1202 
1203 #define ROUND_TRIP_UNIT(U, LOW, HIGH)          \
1204   do {                                         \
1205     for (int64_t i = LOW; i < HIGH; ++i) {     \
1206       absl::Duration d = absl::U(i);           \
1207       if (d == absl::InfiniteDuration())       \
1208         EXPECT_EQ(kint64max, d / absl::U(1));  \
1209       else if (d == -absl::InfiniteDuration()) \
1210         EXPECT_EQ(kint64min, d / absl::U(1));  \
1211       else                                     \
1212         EXPECT_EQ(i, absl::U(i) / absl::U(1)); \
1213     }                                          \
1214   } while (0)
1215 
1216   ROUND_TRIP_UNIT(Nanoseconds, kint64min, kint64min + kRange);
1217   ROUND_TRIP_UNIT(Nanoseconds, -kRange, kRange);
1218   ROUND_TRIP_UNIT(Nanoseconds, kint64max - kRange, kint64max);
1219 
1220   ROUND_TRIP_UNIT(Microseconds, kint64min, kint64min + kRange);
1221   ROUND_TRIP_UNIT(Microseconds, -kRange, kRange);
1222   ROUND_TRIP_UNIT(Microseconds, kint64max - kRange, kint64max);
1223 
1224   ROUND_TRIP_UNIT(Milliseconds, kint64min, kint64min + kRange);
1225   ROUND_TRIP_UNIT(Milliseconds, -kRange, kRange);
1226   ROUND_TRIP_UNIT(Milliseconds, kint64max - kRange, kint64max);
1227 
1228   ROUND_TRIP_UNIT(Seconds, kint64min, kint64min + kRange);
1229   ROUND_TRIP_UNIT(Seconds, -kRange, kRange);
1230   ROUND_TRIP_UNIT(Seconds, kint64max - kRange, kint64max);
1231 
1232   ROUND_TRIP_UNIT(Minutes, kint64min / 60, kint64min / 60 + kRange);
1233   ROUND_TRIP_UNIT(Minutes, -kRange, kRange);
1234   ROUND_TRIP_UNIT(Minutes, kint64max / 60 - kRange, kint64max / 60);
1235 
1236   ROUND_TRIP_UNIT(Hours, kint64min / 3600, kint64min / 3600 + kRange);
1237   ROUND_TRIP_UNIT(Hours, -kRange, kRange);
1238   ROUND_TRIP_UNIT(Hours, kint64max / 3600 - kRange, kint64max / 3600);
1239 
1240 #undef ROUND_TRIP_UNIT
1241 }
1242 
TEST(Duration,TruncConversions)1243 TEST(Duration, TruncConversions) {
1244   // Tests ToTimespec()/DurationFromTimespec()
1245   const struct {
1246     absl::Duration d;
1247     timespec ts;
1248   } to_ts[] = {
1249       {absl::Seconds(1) + absl::Nanoseconds(1), {1, 1}},
1250       {absl::Seconds(1) + absl::Nanoseconds(1) / 2, {1, 0}},
1251       {absl::Seconds(1) + absl::Nanoseconds(0), {1, 0}},
1252       {absl::Seconds(0) + absl::Nanoseconds(0), {0, 0}},
1253       {absl::Seconds(0) - absl::Nanoseconds(1) / 2, {0, 0}},
1254       {absl::Seconds(0) - absl::Nanoseconds(1), {-1, 999999999}},
1255       {absl::Seconds(-1) + absl::Nanoseconds(1), {-1, 1}},
1256       {absl::Seconds(-1) + absl::Nanoseconds(1) / 2, {-1, 1}},
1257       {absl::Seconds(-1) + absl::Nanoseconds(0), {-1, 0}},
1258       {absl::Seconds(-1) - absl::Nanoseconds(1) / 2, {-1, 0}},
1259   };
1260   for (const auto& test : to_ts) {
1261     EXPECT_THAT(absl::ToTimespec(test.d), TimespecMatcher(test.ts));
1262   }
1263   const struct {
1264     timespec ts;
1265     absl::Duration d;
1266   } from_ts[] = {
1267       {{1, 1}, absl::Seconds(1) + absl::Nanoseconds(1)},
1268       {{1, 0}, absl::Seconds(1) + absl::Nanoseconds(0)},
1269       {{0, 0}, absl::Seconds(0) + absl::Nanoseconds(0)},
1270       {{0, -1}, absl::Seconds(0) - absl::Nanoseconds(1)},
1271       {{-1, 999999999}, absl::Seconds(0) - absl::Nanoseconds(1)},
1272       {{-1, 1}, absl::Seconds(-1) + absl::Nanoseconds(1)},
1273       {{-1, 0}, absl::Seconds(-1) + absl::Nanoseconds(0)},
1274       {{-1, -1}, absl::Seconds(-1) - absl::Nanoseconds(1)},
1275       {{-2, 999999999}, absl::Seconds(-1) - absl::Nanoseconds(1)},
1276   };
1277   for (const auto& test : from_ts) {
1278     EXPECT_EQ(test.d, absl::DurationFromTimespec(test.ts));
1279   }
1280 
1281   // Tests ToTimeval()/DurationFromTimeval() (same as timespec above)
1282   const struct {
1283     absl::Duration d;
1284     timeval tv;
1285   } to_tv[] = {
1286       {absl::Seconds(1) + absl::Microseconds(1), {1, 1}},
1287       {absl::Seconds(1) + absl::Microseconds(1) / 2, {1, 0}},
1288       {absl::Seconds(1) + absl::Microseconds(0), {1, 0}},
1289       {absl::Seconds(0) + absl::Microseconds(0), {0, 0}},
1290       {absl::Seconds(0) - absl::Microseconds(1) / 2, {0, 0}},
1291       {absl::Seconds(0) - absl::Microseconds(1), {-1, 999999}},
1292       {absl::Seconds(-1) + absl::Microseconds(1), {-1, 1}},
1293       {absl::Seconds(-1) + absl::Microseconds(1) / 2, {-1, 1}},
1294       {absl::Seconds(-1) + absl::Microseconds(0), {-1, 0}},
1295       {absl::Seconds(-1) - absl::Microseconds(1) / 2, {-1, 0}},
1296   };
1297   for (const auto& test : to_tv) {
1298     EXPECT_THAT(absl::ToTimeval(test.d), TimevalMatcher(test.tv));
1299   }
1300   const struct {
1301     timeval tv;
1302     absl::Duration d;
1303   } from_tv[] = {
1304       {{1, 1}, absl::Seconds(1) + absl::Microseconds(1)},
1305       {{1, 0}, absl::Seconds(1) + absl::Microseconds(0)},
1306       {{0, 0}, absl::Seconds(0) + absl::Microseconds(0)},
1307       {{0, -1}, absl::Seconds(0) - absl::Microseconds(1)},
1308       {{-1, 999999}, absl::Seconds(0) - absl::Microseconds(1)},
1309       {{-1, 1}, absl::Seconds(-1) + absl::Microseconds(1)},
1310       {{-1, 0}, absl::Seconds(-1) + absl::Microseconds(0)},
1311       {{-1, -1}, absl::Seconds(-1) - absl::Microseconds(1)},
1312       {{-2, 999999}, absl::Seconds(-1) - absl::Microseconds(1)},
1313   };
1314   for (const auto& test : from_tv) {
1315     EXPECT_EQ(test.d, absl::DurationFromTimeval(test.tv));
1316   }
1317 }
1318 
TEST(Duration,SmallConversions)1319 TEST(Duration, SmallConversions) {
1320   // Special tests for conversions of small durations.
1321 
1322   EXPECT_EQ(absl::ZeroDuration(), absl::Seconds(0));
1323   // TODO(bww): Is the next one OK?
1324   EXPECT_EQ(absl::ZeroDuration(), absl::Seconds(std::nextafter(0.125e-9, 0)));
1325   EXPECT_EQ(absl::Nanoseconds(1) / 4, absl::Seconds(0.125e-9));
1326   EXPECT_EQ(absl::Nanoseconds(1) / 4, absl::Seconds(0.250e-9));
1327   EXPECT_EQ(absl::Nanoseconds(1) / 2, absl::Seconds(0.375e-9));
1328   EXPECT_EQ(absl::Nanoseconds(1) / 2, absl::Seconds(0.500e-9));
1329   EXPECT_EQ(absl::Nanoseconds(3) / 4, absl::Seconds(0.625e-9));
1330   EXPECT_EQ(absl::Nanoseconds(3) / 4, absl::Seconds(0.750e-9));
1331   EXPECT_EQ(absl::Nanoseconds(1), absl::Seconds(0.875e-9));
1332   EXPECT_EQ(absl::Nanoseconds(1), absl::Seconds(1.000e-9));
1333 
1334   EXPECT_EQ(absl::ZeroDuration(), absl::Seconds(std::nextafter(-0.125e-9, 0)));
1335   EXPECT_EQ(-absl::Nanoseconds(1) / 4, absl::Seconds(-0.125e-9));
1336   EXPECT_EQ(-absl::Nanoseconds(1) / 4, absl::Seconds(-0.250e-9));
1337   EXPECT_EQ(-absl::Nanoseconds(1) / 2, absl::Seconds(-0.375e-9));
1338   EXPECT_EQ(-absl::Nanoseconds(1) / 2, absl::Seconds(-0.500e-9));
1339   EXPECT_EQ(-absl::Nanoseconds(3) / 4, absl::Seconds(-0.625e-9));
1340   EXPECT_EQ(-absl::Nanoseconds(3) / 4, absl::Seconds(-0.750e-9));
1341   EXPECT_EQ(-absl::Nanoseconds(1), absl::Seconds(-0.875e-9));
1342   EXPECT_EQ(-absl::Nanoseconds(1), absl::Seconds(-1.000e-9));
1343 
1344   timespec ts;
1345   ts.tv_sec = 0;
1346   ts.tv_nsec = 0;
1347   EXPECT_THAT(ToTimespec(absl::Nanoseconds(0)), TimespecMatcher(ts));
1348   // TODO(bww): Are the next three OK?
1349   EXPECT_THAT(ToTimespec(absl::Nanoseconds(1) / 4), TimespecMatcher(ts));
1350   EXPECT_THAT(ToTimespec(absl::Nanoseconds(2) / 4), TimespecMatcher(ts));
1351   EXPECT_THAT(ToTimespec(absl::Nanoseconds(3) / 4), TimespecMatcher(ts));
1352   ts.tv_nsec = 1;
1353   EXPECT_THAT(ToTimespec(absl::Nanoseconds(4) / 4), TimespecMatcher(ts));
1354   EXPECT_THAT(ToTimespec(absl::Nanoseconds(5) / 4), TimespecMatcher(ts));
1355   EXPECT_THAT(ToTimespec(absl::Nanoseconds(6) / 4), TimespecMatcher(ts));
1356   EXPECT_THAT(ToTimespec(absl::Nanoseconds(7) / 4), TimespecMatcher(ts));
1357   ts.tv_nsec = 2;
1358   EXPECT_THAT(ToTimespec(absl::Nanoseconds(8) / 4), TimespecMatcher(ts));
1359 
1360   timeval tv;
1361   tv.tv_sec = 0;
1362   tv.tv_usec = 0;
1363   EXPECT_THAT(ToTimeval(absl::Nanoseconds(0)), TimevalMatcher(tv));
1364   // TODO(bww): Is the next one OK?
1365   EXPECT_THAT(ToTimeval(absl::Nanoseconds(999)), TimevalMatcher(tv));
1366   tv.tv_usec = 1;
1367   EXPECT_THAT(ToTimeval(absl::Nanoseconds(1000)), TimevalMatcher(tv));
1368   EXPECT_THAT(ToTimeval(absl::Nanoseconds(1999)), TimevalMatcher(tv));
1369   tv.tv_usec = 2;
1370   EXPECT_THAT(ToTimeval(absl::Nanoseconds(2000)), TimevalMatcher(tv));
1371 }
1372 
VerifyApproxSameAsMul(double time_as_seconds,int * const misses)1373 void VerifyApproxSameAsMul(double time_as_seconds, int* const misses) {
1374   auto direct_seconds = absl::Seconds(time_as_seconds);
1375   auto mul_by_one_second = time_as_seconds * absl::Seconds(1);
1376   // These are expected to differ by up to one tick due to fused multiply/add
1377   // contraction.
1378   if (absl::AbsDuration(direct_seconds - mul_by_one_second) >
1379       absl::time_internal::MakeDuration(0, 1u)) {
1380     if (*misses > 10) return;
1381     ASSERT_LE(++(*misses), 10) << "Too many errors, not reporting more.";
1382     EXPECT_EQ(direct_seconds, mul_by_one_second)
1383         << "given double time_as_seconds = " << std::setprecision(17)
1384         << time_as_seconds;
1385   }
1386 }
1387 
1388 // For a variety of interesting durations, we find the exact point
1389 // where one double converts to that duration, and the very next double
1390 // converts to the next duration.  For both of those points, verify that
1391 // Seconds(point) returns a duration near point * Seconds(1.0). (They may
1392 // not be exactly equal due to fused multiply/add contraction.)
TEST(Duration,ToDoubleSecondsCheckEdgeCases)1393 TEST(Duration, ToDoubleSecondsCheckEdgeCases) {
1394 #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0
1395   // We're using an x87-compatible FPU, and intermediate operations can be
1396   // performed with 80-bit floats. This means the edge cases are different than
1397   // what we expect here, so just skip this test.
1398   GTEST_SKIP()
1399       << "Skipping the test because we detected x87 floating-point semantics";
1400 #endif
1401 
1402   constexpr uint32_t kTicksPerSecond = absl::time_internal::kTicksPerSecond;
1403   constexpr auto duration_tick = absl::time_internal::MakeDuration(0, 1u);
1404   int misses = 0;
1405   for (int64_t seconds = 0; seconds < 99; ++seconds) {
1406     uint32_t tick_vals[] = {0, +999, +999999, +999999999, kTicksPerSecond - 1,
1407                             0, 1000, 1000000, 1000000000, kTicksPerSecond,
1408                             1, 1001, 1000001, 1000000001, kTicksPerSecond + 1,
1409                             2, 1002, 1000002, 1000000002, kTicksPerSecond + 2,
1410                             3, 1003, 1000003, 1000000003, kTicksPerSecond + 3,
1411                             4, 1004, 1000004, 1000000004, kTicksPerSecond + 4,
1412                             5, 6,    7,       8,          9};
1413     for (uint32_t ticks : tick_vals) {
1414       absl::Duration s_plus_t = absl::Seconds(seconds) + ticks * duration_tick;
1415       for (absl::Duration d : {s_plus_t, -s_plus_t}) {
1416         absl::Duration after_d = d + duration_tick;
1417         EXPECT_NE(d, after_d);
1418         EXPECT_EQ(after_d - d, duration_tick);
1419 
1420         double low_edge = ToDoubleSeconds(d);
1421         EXPECT_EQ(d, absl::Seconds(low_edge));
1422 
1423         double high_edge = ToDoubleSeconds(after_d);
1424         EXPECT_EQ(after_d, absl::Seconds(high_edge));
1425 
1426         for (;;) {
1427           double midpoint = low_edge + (high_edge - low_edge) / 2;
1428           if (midpoint == low_edge || midpoint == high_edge) break;
1429           absl::Duration mid_duration = absl::Seconds(midpoint);
1430           if (mid_duration == d) {
1431             low_edge = midpoint;
1432           } else {
1433             EXPECT_EQ(mid_duration, after_d);
1434             high_edge = midpoint;
1435           }
1436         }
1437         // Now low_edge is the highest double that converts to Duration d,
1438         // and high_edge is the lowest double that converts to Duration after_d.
1439         VerifyApproxSameAsMul(low_edge, &misses);
1440         VerifyApproxSameAsMul(high_edge, &misses);
1441       }
1442     }
1443   }
1444 }
1445 
TEST(Duration,ToDoubleSecondsCheckRandom)1446 TEST(Duration, ToDoubleSecondsCheckRandom) {
1447   std::random_device rd;
1448   std::seed_seq seed({rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()});
1449   std::mt19937_64 gen(seed);
1450   // We want doubles distributed from 1/8ns up to 2^63, where
1451   // as many values are tested from 1ns to 2ns as from 1sec to 2sec,
1452   // so even distribute along a log-scale of those values, and
1453   // exponentiate before using them.  (9.223377e+18 is just slightly
1454   // out of bounds for absl::Duration.)
1455   std::uniform_real_distribution<double> uniform(std::log(0.125e-9),
1456                                                  std::log(9.223377e+18));
1457   int misses = 0;
1458   for (int i = 0; i < 1000000; ++i) {
1459     double d = std::exp(uniform(gen));
1460     VerifyApproxSameAsMul(d, &misses);
1461     VerifyApproxSameAsMul(-d, &misses);
1462   }
1463 }
1464 
TEST(Duration,ConversionSaturation)1465 TEST(Duration, ConversionSaturation) {
1466   absl::Duration d;
1467 
1468   const auto max_timeval_sec =
1469       std::numeric_limits<decltype(timeval::tv_sec)>::max();
1470   const auto min_timeval_sec =
1471       std::numeric_limits<decltype(timeval::tv_sec)>::min();
1472   timeval tv;
1473   tv.tv_sec = max_timeval_sec;
1474   tv.tv_usec = 999998;
1475   d = absl::DurationFromTimeval(tv);
1476   tv = ToTimeval(d);
1477   EXPECT_EQ(max_timeval_sec, tv.tv_sec);
1478   EXPECT_EQ(999998, tv.tv_usec);
1479   d += absl::Microseconds(1);
1480   tv = ToTimeval(d);
1481   EXPECT_EQ(max_timeval_sec, tv.tv_sec);
1482   EXPECT_EQ(999999, tv.tv_usec);
1483   d += absl::Microseconds(1);  // no effect
1484   tv = ToTimeval(d);
1485   EXPECT_EQ(max_timeval_sec, tv.tv_sec);
1486   EXPECT_EQ(999999, tv.tv_usec);
1487 
1488   tv.tv_sec = min_timeval_sec;
1489   tv.tv_usec = 1;
1490   d = absl::DurationFromTimeval(tv);
1491   tv = ToTimeval(d);
1492   EXPECT_EQ(min_timeval_sec, tv.tv_sec);
1493   EXPECT_EQ(1, tv.tv_usec);
1494   d -= absl::Microseconds(1);
1495   tv = ToTimeval(d);
1496   EXPECT_EQ(min_timeval_sec, tv.tv_sec);
1497   EXPECT_EQ(0, tv.tv_usec);
1498   d -= absl::Microseconds(1);  // no effect
1499   tv = ToTimeval(d);
1500   EXPECT_EQ(min_timeval_sec, tv.tv_sec);
1501   EXPECT_EQ(0, tv.tv_usec);
1502 
1503   const auto max_timespec_sec =
1504       std::numeric_limits<decltype(timespec::tv_sec)>::max();
1505   const auto min_timespec_sec =
1506       std::numeric_limits<decltype(timespec::tv_sec)>::min();
1507   timespec ts;
1508   ts.tv_sec = max_timespec_sec;
1509   ts.tv_nsec = 999999998;
1510   d = absl::DurationFromTimespec(ts);
1511   ts = absl::ToTimespec(d);
1512   EXPECT_EQ(max_timespec_sec, ts.tv_sec);
1513   EXPECT_EQ(999999998, ts.tv_nsec);
1514   d += absl::Nanoseconds(1);
1515   ts = absl::ToTimespec(d);
1516   EXPECT_EQ(max_timespec_sec, ts.tv_sec);
1517   EXPECT_EQ(999999999, ts.tv_nsec);
1518   d += absl::Nanoseconds(1);  // no effect
1519   ts = absl::ToTimespec(d);
1520   EXPECT_EQ(max_timespec_sec, ts.tv_sec);
1521   EXPECT_EQ(999999999, ts.tv_nsec);
1522 
1523   ts.tv_sec = min_timespec_sec;
1524   ts.tv_nsec = 1;
1525   d = absl::DurationFromTimespec(ts);
1526   ts = absl::ToTimespec(d);
1527   EXPECT_EQ(min_timespec_sec, ts.tv_sec);
1528   EXPECT_EQ(1, ts.tv_nsec);
1529   d -= absl::Nanoseconds(1);
1530   ts = absl::ToTimespec(d);
1531   EXPECT_EQ(min_timespec_sec, ts.tv_sec);
1532   EXPECT_EQ(0, ts.tv_nsec);
1533   d -= absl::Nanoseconds(1);  // no effect
1534   ts = absl::ToTimespec(d);
1535   EXPECT_EQ(min_timespec_sec, ts.tv_sec);
1536   EXPECT_EQ(0, ts.tv_nsec);
1537 }
1538 
TEST(Duration,FormatDuration)1539 TEST(Duration, FormatDuration) {
1540   // Example from Go's docs.
1541   EXPECT_EQ("72h3m0.5s",
1542             absl::FormatDuration(absl::Hours(72) + absl::Minutes(3) +
1543                                  absl::Milliseconds(500)));
1544   // Go's largest time: 2540400h10m10.000000000s
1545   EXPECT_EQ("2540400h10m10s",
1546             absl::FormatDuration(absl::Hours(2540400) + absl::Minutes(10) +
1547                                  absl::Seconds(10)));
1548 
1549   EXPECT_EQ("0", absl::FormatDuration(absl::ZeroDuration()));
1550   EXPECT_EQ("0", absl::FormatDuration(absl::Seconds(0)));
1551   EXPECT_EQ("0", absl::FormatDuration(absl::Nanoseconds(0)));
1552 
1553   EXPECT_EQ("1ns", absl::FormatDuration(absl::Nanoseconds(1)));
1554   EXPECT_EQ("1us", absl::FormatDuration(absl::Microseconds(1)));
1555   EXPECT_EQ("1ms", absl::FormatDuration(absl::Milliseconds(1)));
1556   EXPECT_EQ("1s", absl::FormatDuration(absl::Seconds(1)));
1557   EXPECT_EQ("1m", absl::FormatDuration(absl::Minutes(1)));
1558   EXPECT_EQ("1h", absl::FormatDuration(absl::Hours(1)));
1559 
1560   EXPECT_EQ("1h1m", absl::FormatDuration(absl::Hours(1) + absl::Minutes(1)));
1561   EXPECT_EQ("1h1s", absl::FormatDuration(absl::Hours(1) + absl::Seconds(1)));
1562   EXPECT_EQ("1m1s", absl::FormatDuration(absl::Minutes(1) + absl::Seconds(1)));
1563 
1564   EXPECT_EQ("1h0.25s",
1565             absl::FormatDuration(absl::Hours(1) + absl::Milliseconds(250)));
1566   EXPECT_EQ("1m0.25s",
1567             absl::FormatDuration(absl::Minutes(1) + absl::Milliseconds(250)));
1568   EXPECT_EQ("1h1m0.25s",
1569             absl::FormatDuration(absl::Hours(1) + absl::Minutes(1) +
1570                                  absl::Milliseconds(250)));
1571   EXPECT_EQ("1h0.0005s",
1572             absl::FormatDuration(absl::Hours(1) + absl::Microseconds(500)));
1573   EXPECT_EQ("1h0.0000005s",
1574             absl::FormatDuration(absl::Hours(1) + absl::Nanoseconds(500)));
1575 
1576   // Subsecond special case.
1577   EXPECT_EQ("1.5ns", absl::FormatDuration(absl::Nanoseconds(1) +
1578                                           absl::Nanoseconds(1) / 2));
1579   EXPECT_EQ("1.25ns", absl::FormatDuration(absl::Nanoseconds(1) +
1580                                            absl::Nanoseconds(1) / 4));
1581   EXPECT_EQ("1ns", absl::FormatDuration(absl::Nanoseconds(1) +
1582                                         absl::Nanoseconds(1) / 9));
1583   EXPECT_EQ("1.2us", absl::FormatDuration(absl::Microseconds(1) +
1584                                           absl::Nanoseconds(200)));
1585   EXPECT_EQ("1.2ms", absl::FormatDuration(absl::Milliseconds(1) +
1586                                           absl::Microseconds(200)));
1587   EXPECT_EQ("1.0002ms", absl::FormatDuration(absl::Milliseconds(1) +
1588                                              absl::Nanoseconds(200)));
1589   EXPECT_EQ("1.00001ms", absl::FormatDuration(absl::Milliseconds(1) +
1590                                               absl::Nanoseconds(10)));
1591   EXPECT_EQ("1.000001ms",
1592             absl::FormatDuration(absl::Milliseconds(1) + absl::Nanoseconds(1)));
1593 
1594   // Negative durations.
1595   EXPECT_EQ("-1ns", absl::FormatDuration(absl::Nanoseconds(-1)));
1596   EXPECT_EQ("-1us", absl::FormatDuration(absl::Microseconds(-1)));
1597   EXPECT_EQ("-1ms", absl::FormatDuration(absl::Milliseconds(-1)));
1598   EXPECT_EQ("-1s", absl::FormatDuration(absl::Seconds(-1)));
1599   EXPECT_EQ("-1m", absl::FormatDuration(absl::Minutes(-1)));
1600   EXPECT_EQ("-1h", absl::FormatDuration(absl::Hours(-1)));
1601 
1602   EXPECT_EQ("-1h1m",
1603             absl::FormatDuration(-(absl::Hours(1) + absl::Minutes(1))));
1604   EXPECT_EQ("-1h1s",
1605             absl::FormatDuration(-(absl::Hours(1) + absl::Seconds(1))));
1606   EXPECT_EQ("-1m1s",
1607             absl::FormatDuration(-(absl::Minutes(1) + absl::Seconds(1))));
1608 
1609   EXPECT_EQ("-1ns", absl::FormatDuration(absl::Nanoseconds(-1)));
1610   EXPECT_EQ("-1.2us", absl::FormatDuration(
1611                           -(absl::Microseconds(1) + absl::Nanoseconds(200))));
1612   EXPECT_EQ("-1.2ms", absl::FormatDuration(
1613                           -(absl::Milliseconds(1) + absl::Microseconds(200))));
1614   EXPECT_EQ("-1.0002ms", absl::FormatDuration(-(absl::Milliseconds(1) +
1615                                                 absl::Nanoseconds(200))));
1616   EXPECT_EQ("-1.00001ms", absl::FormatDuration(-(absl::Milliseconds(1) +
1617                                                  absl::Nanoseconds(10))));
1618   EXPECT_EQ("-1.000001ms", absl::FormatDuration(-(absl::Milliseconds(1) +
1619                                                   absl::Nanoseconds(1))));
1620 
1621   //
1622   // Interesting corner cases.
1623   //
1624 
1625   const absl::Duration qns = absl::Nanoseconds(1) / 4;
1626   const absl::Duration max_dur =
1627       absl::Seconds(kint64max) + (absl::Seconds(1) - qns);
1628   const absl::Duration min_dur = absl::Seconds(kint64min);
1629 
1630   EXPECT_EQ("0.25ns", absl::FormatDuration(qns));
1631   EXPECT_EQ("-0.25ns", absl::FormatDuration(-qns));
1632   EXPECT_EQ("2562047788015215h30m7.99999999975s",
1633             absl::FormatDuration(max_dur));
1634   EXPECT_EQ("-2562047788015215h30m8s", absl::FormatDuration(min_dur));
1635 
1636   // Tests printing full precision from units that print using FDivDuration
1637   EXPECT_EQ("55.00000000025s", absl::FormatDuration(absl::Seconds(55) + qns));
1638   EXPECT_EQ("55.00000025ms",
1639             absl::FormatDuration(absl::Milliseconds(55) + qns));
1640   EXPECT_EQ("55.00025us", absl::FormatDuration(absl::Microseconds(55) + qns));
1641   EXPECT_EQ("55.25ns", absl::FormatDuration(absl::Nanoseconds(55) + qns));
1642 
1643   // Formatting infinity
1644   EXPECT_EQ("inf", absl::FormatDuration(absl::InfiniteDuration()));
1645   EXPECT_EQ("-inf", absl::FormatDuration(-absl::InfiniteDuration()));
1646 
1647   // Formatting approximately +/- 100 billion years
1648   const absl::Duration huge_range = ApproxYears(100000000000);
1649   EXPECT_EQ("876000000000000h", absl::FormatDuration(huge_range));
1650   EXPECT_EQ("-876000000000000h", absl::FormatDuration(-huge_range));
1651 
1652   EXPECT_EQ("876000000000000h0.999999999s",
1653             absl::FormatDuration(huge_range +
1654                                  (absl::Seconds(1) - absl::Nanoseconds(1))));
1655   EXPECT_EQ("876000000000000h0.9999999995s",
1656             absl::FormatDuration(
1657                 huge_range + (absl::Seconds(1) - absl::Nanoseconds(1) / 2)));
1658   EXPECT_EQ("876000000000000h0.99999999975s",
1659             absl::FormatDuration(
1660                 huge_range + (absl::Seconds(1) - absl::Nanoseconds(1) / 4)));
1661 
1662   EXPECT_EQ("-876000000000000h0.999999999s",
1663             absl::FormatDuration(-huge_range -
1664                                  (absl::Seconds(1) - absl::Nanoseconds(1))));
1665   EXPECT_EQ("-876000000000000h0.9999999995s",
1666             absl::FormatDuration(
1667                 -huge_range - (absl::Seconds(1) - absl::Nanoseconds(1) / 2)));
1668   EXPECT_EQ("-876000000000000h0.99999999975s",
1669             absl::FormatDuration(
1670                 -huge_range - (absl::Seconds(1) - absl::Nanoseconds(1) / 4)));
1671 }
1672 
TEST(Duration,ParseDuration)1673 TEST(Duration, ParseDuration) {
1674   absl::Duration d;
1675 
1676   // No specified unit. Should only work for zero and infinity.
1677   EXPECT_TRUE(absl::ParseDuration("0", &d));
1678   EXPECT_EQ(absl::ZeroDuration(), d);
1679   EXPECT_TRUE(absl::ParseDuration("+0", &d));
1680   EXPECT_EQ(absl::ZeroDuration(), d);
1681   EXPECT_TRUE(absl::ParseDuration("-0", &d));
1682   EXPECT_EQ(absl::ZeroDuration(), d);
1683 
1684   EXPECT_TRUE(absl::ParseDuration("inf", &d));
1685   EXPECT_EQ(absl::InfiniteDuration(), d);
1686   EXPECT_TRUE(absl::ParseDuration("+inf", &d));
1687   EXPECT_EQ(absl::InfiniteDuration(), d);
1688   EXPECT_TRUE(absl::ParseDuration("-inf", &d));
1689   EXPECT_EQ(-absl::InfiniteDuration(), d);
1690   EXPECT_FALSE(absl::ParseDuration("infBlah", &d));
1691 
1692   // Illegal input forms.
1693   EXPECT_FALSE(absl::ParseDuration("", &d));
1694   EXPECT_FALSE(absl::ParseDuration("0.0", &d));
1695   EXPECT_FALSE(absl::ParseDuration(".0", &d));
1696   EXPECT_FALSE(absl::ParseDuration(".", &d));
1697   EXPECT_FALSE(absl::ParseDuration("01", &d));
1698   EXPECT_FALSE(absl::ParseDuration("1", &d));
1699   EXPECT_FALSE(absl::ParseDuration("-1", &d));
1700   EXPECT_FALSE(absl::ParseDuration("2", &d));
1701   EXPECT_FALSE(absl::ParseDuration("2 s", &d));
1702   EXPECT_FALSE(absl::ParseDuration(".s", &d));
1703   EXPECT_FALSE(absl::ParseDuration("-.s", &d));
1704   EXPECT_FALSE(absl::ParseDuration("s", &d));
1705   EXPECT_FALSE(absl::ParseDuration(" 2s", &d));
1706   EXPECT_FALSE(absl::ParseDuration("2s ", &d));
1707   EXPECT_FALSE(absl::ParseDuration(" 2s ", &d));
1708   EXPECT_FALSE(absl::ParseDuration("2mt", &d));
1709   EXPECT_FALSE(absl::ParseDuration("1e3s", &d));
1710 
1711   // One unit type.
1712   EXPECT_TRUE(absl::ParseDuration("1ns", &d));
1713   EXPECT_EQ(absl::Nanoseconds(1), d);
1714   EXPECT_TRUE(absl::ParseDuration("1us", &d));
1715   EXPECT_EQ(absl::Microseconds(1), d);
1716   EXPECT_TRUE(absl::ParseDuration("1ms", &d));
1717   EXPECT_EQ(absl::Milliseconds(1), d);
1718   EXPECT_TRUE(absl::ParseDuration("1s", &d));
1719   EXPECT_EQ(absl::Seconds(1), d);
1720   EXPECT_TRUE(absl::ParseDuration("2m", &d));
1721   EXPECT_EQ(absl::Minutes(2), d);
1722   EXPECT_TRUE(absl::ParseDuration("2h", &d));
1723   EXPECT_EQ(absl::Hours(2), d);
1724 
1725   // Huge counts of a unit.
1726   EXPECT_TRUE(absl::ParseDuration("9223372036854775807us", &d));
1727   EXPECT_EQ(absl::Microseconds(9223372036854775807), d);
1728   EXPECT_TRUE(absl::ParseDuration("-9223372036854775807us", &d));
1729   EXPECT_EQ(absl::Microseconds(-9223372036854775807), d);
1730 
1731   // Multiple units.
1732   EXPECT_TRUE(absl::ParseDuration("2h3m4s", &d));
1733   EXPECT_EQ(absl::Hours(2) + absl::Minutes(3) + absl::Seconds(4), d);
1734   EXPECT_TRUE(absl::ParseDuration("3m4s5us", &d));
1735   EXPECT_EQ(absl::Minutes(3) + absl::Seconds(4) + absl::Microseconds(5), d);
1736   EXPECT_TRUE(absl::ParseDuration("2h3m4s5ms6us7ns", &d));
1737   EXPECT_EQ(absl::Hours(2) + absl::Minutes(3) + absl::Seconds(4) +
1738                 absl::Milliseconds(5) + absl::Microseconds(6) +
1739                 absl::Nanoseconds(7),
1740             d);
1741 
1742   // Multiple units out of order.
1743   EXPECT_TRUE(absl::ParseDuration("2us3m4s5h", &d));
1744   EXPECT_EQ(absl::Hours(5) + absl::Minutes(3) + absl::Seconds(4) +
1745                 absl::Microseconds(2),
1746             d);
1747 
1748   // Fractional values of units.
1749   EXPECT_TRUE(absl::ParseDuration("1.5ns", &d));
1750   EXPECT_EQ(1.5 * absl::Nanoseconds(1), d);
1751   EXPECT_TRUE(absl::ParseDuration("1.5us", &d));
1752   EXPECT_EQ(1.5 * absl::Microseconds(1), d);
1753   EXPECT_TRUE(absl::ParseDuration("1.5ms", &d));
1754   EXPECT_EQ(1.5 * absl::Milliseconds(1), d);
1755   EXPECT_TRUE(absl::ParseDuration("1.5s", &d));
1756   EXPECT_EQ(1.5 * absl::Seconds(1), d);
1757   EXPECT_TRUE(absl::ParseDuration("1.5m", &d));
1758   EXPECT_EQ(1.5 * absl::Minutes(1), d);
1759   EXPECT_TRUE(absl::ParseDuration("1.5h", &d));
1760   EXPECT_EQ(1.5 * absl::Hours(1), d);
1761 
1762   // Huge fractional counts of a unit.
1763   EXPECT_TRUE(absl::ParseDuration("0.4294967295s", &d));
1764   EXPECT_EQ(absl::Nanoseconds(429496729) + absl::Nanoseconds(1) / 2, d);
1765   EXPECT_TRUE(absl::ParseDuration("0.429496729501234567890123456789s", &d));
1766   EXPECT_EQ(absl::Nanoseconds(429496729) + absl::Nanoseconds(1) / 2, d);
1767 
1768   // Negative durations.
1769   EXPECT_TRUE(absl::ParseDuration("-1s", &d));
1770   EXPECT_EQ(absl::Seconds(-1), d);
1771   EXPECT_TRUE(absl::ParseDuration("-1m", &d));
1772   EXPECT_EQ(absl::Minutes(-1), d);
1773   EXPECT_TRUE(absl::ParseDuration("-1h", &d));
1774   EXPECT_EQ(absl::Hours(-1), d);
1775 
1776   EXPECT_TRUE(absl::ParseDuration("-1h2s", &d));
1777   EXPECT_EQ(-(absl::Hours(1) + absl::Seconds(2)), d);
1778   EXPECT_FALSE(absl::ParseDuration("1h-2s", &d));
1779   EXPECT_FALSE(absl::ParseDuration("-1h-2s", &d));
1780   EXPECT_FALSE(absl::ParseDuration("-1h -2s", &d));
1781 }
1782 
TEST(Duration,FormatParseRoundTrip)1783 TEST(Duration, FormatParseRoundTrip) {
1784 #define TEST_PARSE_ROUNDTRIP(d)                \
1785   do {                                         \
1786     std::string s = absl::FormatDuration(d);   \
1787     absl::Duration dur;                        \
1788     EXPECT_TRUE(absl::ParseDuration(s, &dur)); \
1789     EXPECT_EQ(d, dur);                         \
1790   } while (0)
1791 
1792   TEST_PARSE_ROUNDTRIP(absl::Nanoseconds(1));
1793   TEST_PARSE_ROUNDTRIP(absl::Microseconds(1));
1794   TEST_PARSE_ROUNDTRIP(absl::Milliseconds(1));
1795   TEST_PARSE_ROUNDTRIP(absl::Seconds(1));
1796   TEST_PARSE_ROUNDTRIP(absl::Minutes(1));
1797   TEST_PARSE_ROUNDTRIP(absl::Hours(1));
1798   TEST_PARSE_ROUNDTRIP(absl::Hours(1) + absl::Nanoseconds(2));
1799 
1800   TEST_PARSE_ROUNDTRIP(absl::Nanoseconds(-1));
1801   TEST_PARSE_ROUNDTRIP(absl::Microseconds(-1));
1802   TEST_PARSE_ROUNDTRIP(absl::Milliseconds(-1));
1803   TEST_PARSE_ROUNDTRIP(absl::Seconds(-1));
1804   TEST_PARSE_ROUNDTRIP(absl::Minutes(-1));
1805   TEST_PARSE_ROUNDTRIP(absl::Hours(-1));
1806 
1807   TEST_PARSE_ROUNDTRIP(absl::Hours(-1) + absl::Nanoseconds(2));
1808   TEST_PARSE_ROUNDTRIP(absl::Hours(1) + absl::Nanoseconds(-2));
1809   TEST_PARSE_ROUNDTRIP(absl::Hours(-1) + absl::Nanoseconds(-2));
1810 
1811   TEST_PARSE_ROUNDTRIP(absl::Nanoseconds(1) +
1812                        absl::Nanoseconds(1) / 4);  // 1.25ns
1813 
1814   const absl::Duration huge_range = ApproxYears(100000000000);
1815   TEST_PARSE_ROUNDTRIP(huge_range);
1816   TEST_PARSE_ROUNDTRIP(huge_range + (absl::Seconds(1) - absl::Nanoseconds(1)));
1817 
1818 #undef TEST_PARSE_ROUNDTRIP
1819 }
1820 
1821 }  // namespace
1822