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 // The implementation of the absl::Duration class, which is declared in
16 // //absl/time.h. This class behaves like a numeric type; it has no public
17 // methods and is used only through the operators defined here.
18 //
19 // Implementation notes:
20 //
21 // An absl::Duration is represented as
22 //
23 // rep_hi_ : (int64_t) Whole seconds
24 // rep_lo_ : (uint32_t) Fractions of a second
25 //
26 // The seconds value (rep_hi_) may be positive or negative as appropriate.
27 // The fractional seconds (rep_lo_) is always a positive offset from rep_hi_.
28 // The API for Duration guarantees at least nanosecond resolution, which
29 // means rep_lo_ could have a max value of 1B - 1 if it stored nanoseconds.
30 // However, to utilize more of the available 32 bits of space in rep_lo_,
31 // we instead store quarters of a nanosecond in rep_lo_ resulting in a max
32 // value of 4B - 1. This allows us to correctly handle calculations like
33 // 0.5 nanos + 0.5 nanos = 1 nano. The following example shows the actual
34 // Duration rep using quarters of a nanosecond.
35 //
36 // 2.5 sec = {rep_hi_=2, rep_lo_=2000000000} // lo = 4 * 500000000
37 // -2.5 sec = {rep_hi_=-3, rep_lo_=2000000000}
38 //
39 // Infinite durations are represented as Durations with the rep_lo_ field set
40 // to all 1s.
41 //
42 // +InfiniteDuration:
43 // rep_hi_ : kint64max
44 // rep_lo_ : ~0U
45 //
46 // -InfiniteDuration:
47 // rep_hi_ : kint64min
48 // rep_lo_ : ~0U
49 //
50 // Arithmetic overflows/underflows to +/- infinity and saturates.
51
52 #if defined(_MSC_VER)
53 #include <winsock2.h> // for timeval
54 #endif
55
56 #include <algorithm>
57 #include <cassert>
58 #include <cctype>
59 #include <cerrno>
60 #include <cmath>
61 #include <cstdint>
62 #include <cstdlib>
63 #include <cstring>
64 #include <ctime>
65 #include <functional>
66 #include <limits>
67 #include <string>
68
69 #include "absl/base/casts.h"
70 #include "absl/numeric/int128.h"
71 #include "absl/time/time.h"
72
73 namespace absl {
74 ABSL_NAMESPACE_BEGIN
75
76 namespace {
77
78 using time_internal::kTicksPerNanosecond;
79 using time_internal::kTicksPerSecond;
80
81 constexpr int64_t kint64max = std::numeric_limits<int64_t>::max();
82 constexpr int64_t kint64min = std::numeric_limits<int64_t>::min();
83
84 // Can't use std::isinfinite() because it doesn't exist on windows.
IsFinite(double d)85 inline bool IsFinite(double d) {
86 if (std::isnan(d)) return false;
87 return d != std::numeric_limits<double>::infinity() &&
88 d != -std::numeric_limits<double>::infinity();
89 }
90
IsValidDivisor(double d)91 inline bool IsValidDivisor(double d) {
92 if (std::isnan(d)) return false;
93 return d != 0.0;
94 }
95
96 // Can't use std::round() because it is only available in C++11.
97 // Note that we ignore the possibility of floating-point over/underflow.
98 template <typename Double>
Round(Double d)99 inline double Round(Double d) {
100 return d < 0 ? std::ceil(d - 0.5) : std::floor(d + 0.5);
101 }
102
103 // *sec may be positive or negative. *ticks must be in the range
104 // -kTicksPerSecond < *ticks < kTicksPerSecond. If *ticks is negative it
105 // will be normalized to a positive value by adjusting *sec accordingly.
NormalizeTicks(int64_t * sec,int64_t * ticks)106 inline void NormalizeTicks(int64_t* sec, int64_t* ticks) {
107 if (*ticks < 0) {
108 --*sec;
109 *ticks += kTicksPerSecond;
110 }
111 }
112
113 // Makes a uint128 from the absolute value of the given scalar.
MakeU128(int64_t a)114 inline uint128 MakeU128(int64_t a) {
115 uint128 u128 = 0;
116 if (a < 0) {
117 ++u128;
118 ++a; // Makes it safe to negate 'a'
119 a = -a;
120 }
121 u128 += static_cast<uint64_t>(a);
122 return u128;
123 }
124
125 // Makes a uint128 count of ticks out of the absolute value of the Duration.
MakeU128Ticks(Duration d)126 inline uint128 MakeU128Ticks(Duration d) {
127 int64_t rep_hi = time_internal::GetRepHi(d);
128 uint32_t rep_lo = time_internal::GetRepLo(d);
129 if (rep_hi < 0) {
130 ++rep_hi;
131 rep_hi = -rep_hi;
132 rep_lo = kTicksPerSecond - rep_lo;
133 }
134 uint128 u128 = static_cast<uint64_t>(rep_hi);
135 u128 *= static_cast<uint64_t>(kTicksPerSecond);
136 u128 += rep_lo;
137 return u128;
138 }
139
140 // Breaks a uint128 of ticks into a Duration.
MakeDurationFromU128(uint128 u128,bool is_neg)141 inline Duration MakeDurationFromU128(uint128 u128, bool is_neg) {
142 int64_t rep_hi;
143 uint32_t rep_lo;
144 const uint64_t h64 = Uint128High64(u128);
145 const uint64_t l64 = Uint128Low64(u128);
146 if (h64 == 0) { // fastpath
147 const uint64_t hi = l64 / kTicksPerSecond;
148 rep_hi = static_cast<int64_t>(hi);
149 rep_lo = static_cast<uint32_t>(l64 - hi * kTicksPerSecond);
150 } else {
151 // kMaxRepHi64 is the high 64 bits of (2^63 * kTicksPerSecond).
152 // Any positive tick count whose high 64 bits are >= kMaxRepHi64
153 // is not representable as a Duration. A negative tick count can
154 // have its high 64 bits == kMaxRepHi64 but only when the low 64
155 // bits are all zero, otherwise it is not representable either.
156 const uint64_t kMaxRepHi64 = 0x77359400UL;
157 if (h64 >= kMaxRepHi64) {
158 if (is_neg && h64 == kMaxRepHi64 && l64 == 0) {
159 // Avoid trying to represent -kint64min below.
160 return time_internal::MakeDuration(kint64min);
161 }
162 return is_neg ? -InfiniteDuration() : InfiniteDuration();
163 }
164 const uint128 kTicksPerSecond128 = static_cast<uint64_t>(kTicksPerSecond);
165 const uint128 hi = u128 / kTicksPerSecond128;
166 rep_hi = static_cast<int64_t>(Uint128Low64(hi));
167 rep_lo =
168 static_cast<uint32_t>(Uint128Low64(u128 - hi * kTicksPerSecond128));
169 }
170 if (is_neg) {
171 rep_hi = -rep_hi;
172 if (rep_lo != 0) {
173 --rep_hi;
174 rep_lo = kTicksPerSecond - rep_lo;
175 }
176 }
177 return time_internal::MakeDuration(rep_hi, rep_lo);
178 }
179
180 // Convert between int64_t and uint64_t, preserving representation. This
181 // allows us to do arithmetic in the unsigned domain, where overflow has
182 // well-defined behavior. See operator+=() and operator-=().
183 //
184 // C99 7.20.1.1.1, as referenced by C++11 18.4.1.2, says, "The typedef
185 // name intN_t designates a signed integer type with width N, no padding
186 // bits, and a two's complement representation." So, we can convert to
187 // and from the corresponding uint64_t value using a bit cast.
EncodeTwosComp(int64_t v)188 inline uint64_t EncodeTwosComp(int64_t v) {
189 return absl::bit_cast<uint64_t>(v);
190 }
DecodeTwosComp(uint64_t v)191 inline int64_t DecodeTwosComp(uint64_t v) { return absl::bit_cast<int64_t>(v); }
192
193 // Note: The overflow detection in this function is done using greater/less *or
194 // equal* because kint64max/min is too large to be represented exactly in a
195 // double (which only has 53 bits of precision). In order to avoid assigning to
196 // rep->hi a double value that is too large for an int64_t (and therefore is
197 // undefined), we must consider computations that equal kint64max/min as a
198 // double as overflow cases.
SafeAddRepHi(double a_hi,double b_hi,Duration * d)199 inline bool SafeAddRepHi(double a_hi, double b_hi, Duration* d) {
200 double c = a_hi + b_hi;
201 if (c >= static_cast<double>(kint64max)) {
202 *d = InfiniteDuration();
203 return false;
204 }
205 if (c <= static_cast<double>(kint64min)) {
206 *d = -InfiniteDuration();
207 return false;
208 }
209 *d = time_internal::MakeDuration(c, time_internal::GetRepLo(*d));
210 return true;
211 }
212
213 // A functor that's similar to std::multiplies<T>, except this returns the max
214 // T value instead of overflowing. This is only defined for uint128.
215 template <typename Ignored>
216 struct SafeMultiply {
operator ()absl::__anon8531abf80111::SafeMultiply217 uint128 operator()(uint128 a, uint128 b) const {
218 // b hi is always zero because it originated as an int64_t.
219 assert(Uint128High64(b) == 0);
220 // Fastpath to avoid the expensive overflow check with division.
221 if (Uint128High64(a) == 0) {
222 return (((Uint128Low64(a) | Uint128Low64(b)) >> 32) == 0)
223 ? static_cast<uint128>(Uint128Low64(a) * Uint128Low64(b))
224 : a * b;
225 }
226 return b == 0 ? b : (a > kuint128max / b) ? kuint128max : a * b;
227 }
228 };
229
230 // Scales (i.e., multiplies or divides, depending on the Operation template)
231 // the Duration d by the int64_t r.
232 template <template <typename> class Operation>
ScaleFixed(Duration d,int64_t r)233 inline Duration ScaleFixed(Duration d, int64_t r) {
234 const uint128 a = MakeU128Ticks(d);
235 const uint128 b = MakeU128(r);
236 const uint128 q = Operation<uint128>()(a, b);
237 const bool is_neg = (time_internal::GetRepHi(d) < 0) != (r < 0);
238 return MakeDurationFromU128(q, is_neg);
239 }
240
241 // Scales (i.e., multiplies or divides, depending on the Operation template)
242 // the Duration d by the double r.
243 template <template <typename> class Operation>
ScaleDouble(Duration d,double r)244 inline Duration ScaleDouble(Duration d, double r) {
245 Operation<double> op;
246 double hi_doub = op(time_internal::GetRepHi(d), r);
247 double lo_doub = op(time_internal::GetRepLo(d), r);
248
249 double hi_int = 0;
250 double hi_frac = std::modf(hi_doub, &hi_int);
251
252 // Moves hi's fractional bits to lo.
253 lo_doub /= kTicksPerSecond;
254 lo_doub += hi_frac;
255
256 double lo_int = 0;
257 double lo_frac = std::modf(lo_doub, &lo_int);
258
259 // Rolls lo into hi if necessary.
260 int64_t lo64 = Round(lo_frac * kTicksPerSecond);
261
262 Duration ans;
263 if (!SafeAddRepHi(hi_int, lo_int, &ans)) return ans;
264 int64_t hi64 = time_internal::GetRepHi(ans);
265 if (!SafeAddRepHi(hi64, lo64 / kTicksPerSecond, &ans)) return ans;
266 hi64 = time_internal::GetRepHi(ans);
267 lo64 %= kTicksPerSecond;
268 NormalizeTicks(&hi64, &lo64);
269 return time_internal::MakeDuration(hi64, lo64);
270 }
271
272 // Tries to divide num by den as fast as possible by looking for common, easy
273 // cases. If the division was done, the quotient is in *q and the remainder is
274 // in *rem and true will be returned.
IDivFastPath(const Duration num,const Duration den,int64_t * q,Duration * rem)275 inline bool IDivFastPath(const Duration num, const Duration den, int64_t* q,
276 Duration* rem) {
277 // Bail if num or den is an infinity.
278 if (time_internal::IsInfiniteDuration(num) ||
279 time_internal::IsInfiniteDuration(den))
280 return false;
281
282 int64_t num_hi = time_internal::GetRepHi(num);
283 uint32_t num_lo = time_internal::GetRepLo(num);
284 int64_t den_hi = time_internal::GetRepHi(den);
285 uint32_t den_lo = time_internal::GetRepLo(den);
286
287 if (den_hi == 0 && den_lo == kTicksPerNanosecond) {
288 // Dividing by 1ns
289 if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000000000) {
290 *q = num_hi * 1000000000 + num_lo / kTicksPerNanosecond;
291 *rem = time_internal::MakeDuration(0, num_lo % den_lo);
292 return true;
293 }
294 } else if (den_hi == 0 && den_lo == 100 * kTicksPerNanosecond) {
295 // Dividing by 100ns (common when converting to Universal time)
296 if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 10000000) {
297 *q = num_hi * 10000000 + num_lo / (100 * kTicksPerNanosecond);
298 *rem = time_internal::MakeDuration(0, num_lo % den_lo);
299 return true;
300 }
301 } else if (den_hi == 0 && den_lo == 1000 * kTicksPerNanosecond) {
302 // Dividing by 1us
303 if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000000) {
304 *q = num_hi * 1000000 + num_lo / (1000 * kTicksPerNanosecond);
305 *rem = time_internal::MakeDuration(0, num_lo % den_lo);
306 return true;
307 }
308 } else if (den_hi == 0 && den_lo == 1000000 * kTicksPerNanosecond) {
309 // Dividing by 1ms
310 if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000) {
311 *q = num_hi * 1000 + num_lo / (1000000 * kTicksPerNanosecond);
312 *rem = time_internal::MakeDuration(0, num_lo % den_lo);
313 return true;
314 }
315 } else if (den_hi > 0 && den_lo == 0) {
316 // Dividing by positive multiple of 1s
317 if (num_hi >= 0) {
318 if (den_hi == 1) {
319 *q = num_hi;
320 *rem = time_internal::MakeDuration(0, num_lo);
321 return true;
322 }
323 *q = num_hi / den_hi;
324 *rem = time_internal::MakeDuration(num_hi % den_hi, num_lo);
325 return true;
326 }
327 if (num_lo != 0) {
328 num_hi += 1;
329 }
330 int64_t quotient = num_hi / den_hi;
331 int64_t rem_sec = num_hi % den_hi;
332 if (rem_sec > 0) {
333 rem_sec -= den_hi;
334 quotient += 1;
335 }
336 if (num_lo != 0) {
337 rem_sec -= 1;
338 }
339 *q = quotient;
340 *rem = time_internal::MakeDuration(rem_sec, num_lo);
341 return true;
342 }
343
344 return false;
345 }
346
347 } // namespace
348
349 namespace time_internal {
350
351 // The 'satq' argument indicates whether the quotient should saturate at the
352 // bounds of int64_t. If it does saturate, the difference will spill over to
353 // the remainder. If it does not saturate, the remainder remain accurate,
354 // but the returned quotient will over/underflow int64_t and should not be used.
IDivDuration(bool satq,const Duration num,const Duration den,Duration * rem)355 int64_t IDivDuration(bool satq, const Duration num, const Duration den,
356 Duration* rem) {
357 int64_t q = 0;
358 if (IDivFastPath(num, den, &q, rem)) {
359 return q;
360 }
361
362 const bool num_neg = num < ZeroDuration();
363 const bool den_neg = den < ZeroDuration();
364 const bool quotient_neg = num_neg != den_neg;
365
366 if (time_internal::IsInfiniteDuration(num) || den == ZeroDuration()) {
367 *rem = num_neg ? -InfiniteDuration() : InfiniteDuration();
368 return quotient_neg ? kint64min : kint64max;
369 }
370 if (time_internal::IsInfiniteDuration(den)) {
371 *rem = num;
372 return 0;
373 }
374
375 const uint128 a = MakeU128Ticks(num);
376 const uint128 b = MakeU128Ticks(den);
377 uint128 quotient128 = a / b;
378
379 if (satq) {
380 // Limits the quotient to the range of int64_t.
381 if (quotient128 > uint128(static_cast<uint64_t>(kint64max))) {
382 quotient128 = quotient_neg ? uint128(static_cast<uint64_t>(kint64min))
383 : uint128(static_cast<uint64_t>(kint64max));
384 }
385 }
386
387 const uint128 remainder128 = a - quotient128 * b;
388 *rem = MakeDurationFromU128(remainder128, num_neg);
389
390 if (!quotient_neg || quotient128 == 0) {
391 return Uint128Low64(quotient128) & kint64max;
392 }
393 // The quotient needs to be negated, but we need to carefully handle
394 // quotient128s with the top bit on.
395 return -static_cast<int64_t>(Uint128Low64(quotient128 - 1) & kint64max) - 1;
396 }
397
398 } // namespace time_internal
399
400 //
401 // Additive operators.
402 //
403
operator +=(Duration rhs)404 Duration& Duration::operator+=(Duration rhs) {
405 if (time_internal::IsInfiniteDuration(*this)) return *this;
406 if (time_internal::IsInfiniteDuration(rhs)) return *this = rhs;
407 const int64_t orig_rep_hi = rep_hi_;
408 rep_hi_ =
409 DecodeTwosComp(EncodeTwosComp(rep_hi_) + EncodeTwosComp(rhs.rep_hi_));
410 if (rep_lo_ >= kTicksPerSecond - rhs.rep_lo_) {
411 rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_) + 1);
412 rep_lo_ -= kTicksPerSecond;
413 }
414 rep_lo_ += rhs.rep_lo_;
415 if (rhs.rep_hi_ < 0 ? rep_hi_ > orig_rep_hi : rep_hi_ < orig_rep_hi) {
416 return *this = rhs.rep_hi_ < 0 ? -InfiniteDuration() : InfiniteDuration();
417 }
418 return *this;
419 }
420
operator -=(Duration rhs)421 Duration& Duration::operator-=(Duration rhs) {
422 if (time_internal::IsInfiniteDuration(*this)) return *this;
423 if (time_internal::IsInfiniteDuration(rhs)) {
424 return *this = rhs.rep_hi_ >= 0 ? -InfiniteDuration() : InfiniteDuration();
425 }
426 const int64_t orig_rep_hi = rep_hi_;
427 rep_hi_ =
428 DecodeTwosComp(EncodeTwosComp(rep_hi_) - EncodeTwosComp(rhs.rep_hi_));
429 if (rep_lo_ < rhs.rep_lo_) {
430 rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_) - 1);
431 rep_lo_ += kTicksPerSecond;
432 }
433 rep_lo_ -= rhs.rep_lo_;
434 if (rhs.rep_hi_ < 0 ? rep_hi_ < orig_rep_hi : rep_hi_ > orig_rep_hi) {
435 return *this = rhs.rep_hi_ >= 0 ? -InfiniteDuration() : InfiniteDuration();
436 }
437 return *this;
438 }
439
440 //
441 // Multiplicative operators.
442 //
443
operator *=(int64_t r)444 Duration& Duration::operator*=(int64_t r) {
445 if (time_internal::IsInfiniteDuration(*this)) {
446 const bool is_neg = (r < 0) != (rep_hi_ < 0);
447 return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
448 }
449 return *this = ScaleFixed<SafeMultiply>(*this, r);
450 }
451
operator *=(double r)452 Duration& Duration::operator*=(double r) {
453 if (time_internal::IsInfiniteDuration(*this) || !IsFinite(r)) {
454 const bool is_neg = (std::signbit(r) != 0) != (rep_hi_ < 0);
455 return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
456 }
457 return *this = ScaleDouble<std::multiplies>(*this, r);
458 }
459
operator /=(int64_t r)460 Duration& Duration::operator/=(int64_t r) {
461 if (time_internal::IsInfiniteDuration(*this) || r == 0) {
462 const bool is_neg = (r < 0) != (rep_hi_ < 0);
463 return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
464 }
465 return *this = ScaleFixed<std::divides>(*this, r);
466 }
467
operator /=(double r)468 Duration& Duration::operator/=(double r) {
469 if (time_internal::IsInfiniteDuration(*this) || !IsValidDivisor(r)) {
470 const bool is_neg = (std::signbit(r) != 0) != (rep_hi_ < 0);
471 return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
472 }
473 return *this = ScaleDouble<std::divides>(*this, r);
474 }
475
operator %=(Duration rhs)476 Duration& Duration::operator%=(Duration rhs) {
477 time_internal::IDivDuration(false, *this, rhs, this);
478 return *this;
479 }
480
FDivDuration(Duration num,Duration den)481 double FDivDuration(Duration num, Duration den) {
482 // Arithmetic with infinity is sticky.
483 if (time_internal::IsInfiniteDuration(num) || den == ZeroDuration()) {
484 return (num < ZeroDuration()) == (den < ZeroDuration())
485 ? std::numeric_limits<double>::infinity()
486 : -std::numeric_limits<double>::infinity();
487 }
488 if (time_internal::IsInfiniteDuration(den)) return 0.0;
489
490 double a =
491 static_cast<double>(time_internal::GetRepHi(num)) * kTicksPerSecond +
492 time_internal::GetRepLo(num);
493 double b =
494 static_cast<double>(time_internal::GetRepHi(den)) * kTicksPerSecond +
495 time_internal::GetRepLo(den);
496 return a / b;
497 }
498
499 //
500 // Trunc/Floor/Ceil.
501 //
502
Trunc(Duration d,Duration unit)503 Duration Trunc(Duration d, Duration unit) {
504 return d - (d % unit);
505 }
506
Floor(const Duration d,const Duration unit)507 Duration Floor(const Duration d, const Duration unit) {
508 const absl::Duration td = Trunc(d, unit);
509 return td <= d ? td : td - AbsDuration(unit);
510 }
511
Ceil(const Duration d,const Duration unit)512 Duration Ceil(const Duration d, const Duration unit) {
513 const absl::Duration td = Trunc(d, unit);
514 return td >= d ? td : td + AbsDuration(unit);
515 }
516
517 //
518 // Factory functions.
519 //
520
DurationFromTimespec(timespec ts)521 Duration DurationFromTimespec(timespec ts) {
522 if (static_cast<uint64_t>(ts.tv_nsec) < 1000 * 1000 * 1000) {
523 int64_t ticks = ts.tv_nsec * kTicksPerNanosecond;
524 return time_internal::MakeDuration(ts.tv_sec, ticks);
525 }
526 return Seconds(ts.tv_sec) + Nanoseconds(ts.tv_nsec);
527 }
528
DurationFromTimeval(timeval tv)529 Duration DurationFromTimeval(timeval tv) {
530 if (static_cast<uint64_t>(tv.tv_usec) < 1000 * 1000) {
531 int64_t ticks = tv.tv_usec * 1000 * kTicksPerNanosecond;
532 return time_internal::MakeDuration(tv.tv_sec, ticks);
533 }
534 return Seconds(tv.tv_sec) + Microseconds(tv.tv_usec);
535 }
536
537 //
538 // Conversion to other duration types.
539 //
540
ToInt64Nanoseconds(Duration d)541 int64_t ToInt64Nanoseconds(Duration d) {
542 if (time_internal::GetRepHi(d) >= 0 &&
543 time_internal::GetRepHi(d) >> 33 == 0) {
544 return (time_internal::GetRepHi(d) * 1000 * 1000 * 1000) +
545 (time_internal::GetRepLo(d) / kTicksPerNanosecond);
546 }
547 return d / Nanoseconds(1);
548 }
ToInt64Microseconds(Duration d)549 int64_t ToInt64Microseconds(Duration d) {
550 if (time_internal::GetRepHi(d) >= 0 &&
551 time_internal::GetRepHi(d) >> 43 == 0) {
552 return (time_internal::GetRepHi(d) * 1000 * 1000) +
553 (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000));
554 }
555 return d / Microseconds(1);
556 }
ToInt64Milliseconds(Duration d)557 int64_t ToInt64Milliseconds(Duration d) {
558 if (time_internal::GetRepHi(d) >= 0 &&
559 time_internal::GetRepHi(d) >> 53 == 0) {
560 return (time_internal::GetRepHi(d) * 1000) +
561 (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000 * 1000));
562 }
563 return d / Milliseconds(1);
564 }
ToInt64Seconds(Duration d)565 int64_t ToInt64Seconds(Duration d) {
566 int64_t hi = time_internal::GetRepHi(d);
567 if (time_internal::IsInfiniteDuration(d)) return hi;
568 if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
569 return hi;
570 }
ToInt64Minutes(Duration d)571 int64_t ToInt64Minutes(Duration d) {
572 int64_t hi = time_internal::GetRepHi(d);
573 if (time_internal::IsInfiniteDuration(d)) return hi;
574 if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
575 return hi / 60;
576 }
ToInt64Hours(Duration d)577 int64_t ToInt64Hours(Duration d) {
578 int64_t hi = time_internal::GetRepHi(d);
579 if (time_internal::IsInfiniteDuration(d)) return hi;
580 if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
581 return hi / (60 * 60);
582 }
583
ToDoubleNanoseconds(Duration d)584 double ToDoubleNanoseconds(Duration d) {
585 return FDivDuration(d, Nanoseconds(1));
586 }
ToDoubleMicroseconds(Duration d)587 double ToDoubleMicroseconds(Duration d) {
588 return FDivDuration(d, Microseconds(1));
589 }
ToDoubleMilliseconds(Duration d)590 double ToDoubleMilliseconds(Duration d) {
591 return FDivDuration(d, Milliseconds(1));
592 }
ToDoubleSeconds(Duration d)593 double ToDoubleSeconds(Duration d) {
594 return FDivDuration(d, Seconds(1));
595 }
ToDoubleMinutes(Duration d)596 double ToDoubleMinutes(Duration d) {
597 return FDivDuration(d, Minutes(1));
598 }
ToDoubleHours(Duration d)599 double ToDoubleHours(Duration d) {
600 return FDivDuration(d, Hours(1));
601 }
602
ToTimespec(Duration d)603 timespec ToTimespec(Duration d) {
604 timespec ts;
605 if (!time_internal::IsInfiniteDuration(d)) {
606 int64_t rep_hi = time_internal::GetRepHi(d);
607 uint32_t rep_lo = time_internal::GetRepLo(d);
608 if (rep_hi < 0) {
609 // Tweak the fields so that unsigned division of rep_lo
610 // maps to truncation (towards zero) for the timespec.
611 rep_lo += kTicksPerNanosecond - 1;
612 if (rep_lo >= kTicksPerSecond) {
613 rep_hi += 1;
614 rep_lo -= kTicksPerSecond;
615 }
616 }
617 ts.tv_sec = rep_hi;
618 if (ts.tv_sec == rep_hi) { // no time_t narrowing
619 ts.tv_nsec = rep_lo / kTicksPerNanosecond;
620 return ts;
621 }
622 }
623 if (d >= ZeroDuration()) {
624 ts.tv_sec = std::numeric_limits<time_t>::max();
625 ts.tv_nsec = 1000 * 1000 * 1000 - 1;
626 } else {
627 ts.tv_sec = std::numeric_limits<time_t>::min();
628 ts.tv_nsec = 0;
629 }
630 return ts;
631 }
632
ToTimeval(Duration d)633 timeval ToTimeval(Duration d) {
634 timeval tv;
635 timespec ts = ToTimespec(d);
636 if (ts.tv_sec < 0) {
637 // Tweak the fields so that positive division of tv_nsec
638 // maps to truncation (towards zero) for the timeval.
639 ts.tv_nsec += 1000 - 1;
640 if (ts.tv_nsec >= 1000 * 1000 * 1000) {
641 ts.tv_sec += 1;
642 ts.tv_nsec -= 1000 * 1000 * 1000;
643 }
644 }
645 tv.tv_sec = ts.tv_sec;
646 if (tv.tv_sec != ts.tv_sec) { // narrowing
647 if (ts.tv_sec < 0) {
648 tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min();
649 tv.tv_usec = 0;
650 } else {
651 tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max();
652 tv.tv_usec = 1000 * 1000 - 1;
653 }
654 return tv;
655 }
656 tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000); // suseconds_t
657 return tv;
658 }
659
ToChronoNanoseconds(Duration d)660 std::chrono::nanoseconds ToChronoNanoseconds(Duration d) {
661 return time_internal::ToChronoDuration<std::chrono::nanoseconds>(d);
662 }
ToChronoMicroseconds(Duration d)663 std::chrono::microseconds ToChronoMicroseconds(Duration d) {
664 return time_internal::ToChronoDuration<std::chrono::microseconds>(d);
665 }
ToChronoMilliseconds(Duration d)666 std::chrono::milliseconds ToChronoMilliseconds(Duration d) {
667 return time_internal::ToChronoDuration<std::chrono::milliseconds>(d);
668 }
ToChronoSeconds(Duration d)669 std::chrono::seconds ToChronoSeconds(Duration d) {
670 return time_internal::ToChronoDuration<std::chrono::seconds>(d);
671 }
ToChronoMinutes(Duration d)672 std::chrono::minutes ToChronoMinutes(Duration d) {
673 return time_internal::ToChronoDuration<std::chrono::minutes>(d);
674 }
ToChronoHours(Duration d)675 std::chrono::hours ToChronoHours(Duration d) {
676 return time_internal::ToChronoDuration<std::chrono::hours>(d);
677 }
678
679 //
680 // To/From string formatting.
681 //
682
683 namespace {
684
685 // Formats a positive 64-bit integer in the given field width. Note that
686 // it is up to the caller of Format64() to ensure that there is sufficient
687 // space before ep to hold the conversion.
Format64(char * ep,int width,int64_t v)688 char* Format64(char* ep, int width, int64_t v) {
689 do {
690 --width;
691 *--ep = '0' + (v % 10); // contiguous digits
692 } while (v /= 10);
693 while (--width >= 0) *--ep = '0'; // zero pad
694 return ep;
695 }
696
697 // Helpers for FormatDuration() that format 'n' and append it to 'out'
698 // followed by the given 'unit'. If 'n' formats to "0", nothing is
699 // appended (not even the unit).
700
701 // A type that encapsulates how to display a value of a particular unit. For
702 // values that are displayed with fractional parts, the precision indicates
703 // where to round the value. The precision varies with the display unit because
704 // a Duration can hold only quarters of a nanosecond, so displaying information
705 // beyond that is just noise.
706 //
707 // For example, a microsecond value of 42.00025xxxxx should not display beyond 5
708 // fractional digits, because it is in the noise of what a Duration can
709 // represent.
710 struct DisplayUnit {
711 const char* abbr;
712 int prec;
713 double pow10;
714 };
715 const DisplayUnit kDisplayNano = {"ns", 2, 1e2};
716 const DisplayUnit kDisplayMicro = {"us", 5, 1e5};
717 const DisplayUnit kDisplayMilli = {"ms", 8, 1e8};
718 const DisplayUnit kDisplaySec = {"s", 11, 1e11};
719 const DisplayUnit kDisplayMin = {"m", -1, 0.0}; // prec ignored
720 const DisplayUnit kDisplayHour = {"h", -1, 0.0}; // prec ignored
721
AppendNumberUnit(std::string * out,int64_t n,DisplayUnit unit)722 void AppendNumberUnit(std::string* out, int64_t n, DisplayUnit unit) {
723 char buf[sizeof("2562047788015216")]; // hours in max duration
724 char* const ep = buf + sizeof(buf);
725 char* bp = Format64(ep, 0, n);
726 if (*bp != '0' || bp + 1 != ep) {
727 out->append(bp, ep - bp);
728 out->append(unit.abbr);
729 }
730 }
731
732 // Note: unit.prec is limited to double's digits10 value (typically 15) so it
733 // always fits in buf[].
AppendNumberUnit(std::string * out,double n,DisplayUnit unit)734 void AppendNumberUnit(std::string* out, double n, DisplayUnit unit) {
735 const int buf_size = std::numeric_limits<double>::digits10;
736 const int prec = std::min(buf_size, unit.prec);
737 char buf[buf_size]; // also large enough to hold integer part
738 char* ep = buf + sizeof(buf);
739 double d = 0;
740 int64_t frac_part = Round(std::modf(n, &d) * unit.pow10);
741 int64_t int_part = d;
742 if (int_part != 0 || frac_part != 0) {
743 char* bp = Format64(ep, 0, int_part); // always < 1000
744 out->append(bp, ep - bp);
745 if (frac_part != 0) {
746 out->push_back('.');
747 bp = Format64(ep, prec, frac_part);
748 while (ep[-1] == '0') --ep;
749 out->append(bp, ep - bp);
750 }
751 out->append(unit.abbr);
752 }
753 }
754
755 } // namespace
756
757 // From Go's doc at https://golang.org/pkg/time/#Duration.String
758 // [FormatDuration] returns a string representing the duration in the
759 // form "72h3m0.5s". Leading zero units are omitted. As a special
760 // case, durations less than one second format use a smaller unit
761 // (milli-, micro-, or nanoseconds) to ensure that the leading digit
762 // is non-zero. The zero duration formats as 0, with no unit.
FormatDuration(Duration d)763 std::string FormatDuration(Duration d) {
764 const Duration min_duration = Seconds(kint64min);
765 if (d == min_duration) {
766 // Avoid needing to negate kint64min by directly returning what the
767 // following code should produce in that case.
768 return "-2562047788015215h30m8s";
769 }
770 std::string s;
771 if (d < ZeroDuration()) {
772 s.append("-");
773 d = -d;
774 }
775 if (d == InfiniteDuration()) {
776 s.append("inf");
777 } else if (d < Seconds(1)) {
778 // Special case for durations with a magnitude < 1 second. The duration
779 // is printed as a fraction of a single unit, e.g., "1.2ms".
780 if (d < Microseconds(1)) {
781 AppendNumberUnit(&s, FDivDuration(d, Nanoseconds(1)), kDisplayNano);
782 } else if (d < Milliseconds(1)) {
783 AppendNumberUnit(&s, FDivDuration(d, Microseconds(1)), kDisplayMicro);
784 } else {
785 AppendNumberUnit(&s, FDivDuration(d, Milliseconds(1)), kDisplayMilli);
786 }
787 } else {
788 AppendNumberUnit(&s, IDivDuration(d, Hours(1), &d), kDisplayHour);
789 AppendNumberUnit(&s, IDivDuration(d, Minutes(1), &d), kDisplayMin);
790 AppendNumberUnit(&s, FDivDuration(d, Seconds(1)), kDisplaySec);
791 }
792 if (s.empty() || s == "-") {
793 s = "0";
794 }
795 return s;
796 }
797
798 namespace {
799
800 // A helper for ParseDuration() that parses a leading number from the given
801 // string and stores the result in *int_part/*frac_part/*frac_scale. The
802 // given string pointer is modified to point to the first unconsumed char.
ConsumeDurationNumber(const char ** dpp,int64_t * int_part,int64_t * frac_part,int64_t * frac_scale)803 bool ConsumeDurationNumber(const char** dpp, int64_t* int_part,
804 int64_t* frac_part, int64_t* frac_scale) {
805 *int_part = 0;
806 *frac_part = 0;
807 *frac_scale = 1; // invariant: *frac_part < *frac_scale
808 const char* start = *dpp;
809 for (; std::isdigit(**dpp); *dpp += 1) {
810 const int d = **dpp - '0'; // contiguous digits
811 if (*int_part > kint64max / 10) return false;
812 *int_part *= 10;
813 if (*int_part > kint64max - d) return false;
814 *int_part += d;
815 }
816 const bool int_part_empty = (*dpp == start);
817 if (**dpp != '.') return !int_part_empty;
818 for (*dpp += 1; std::isdigit(**dpp); *dpp += 1) {
819 const int d = **dpp - '0'; // contiguous digits
820 if (*frac_scale <= kint64max / 10) {
821 *frac_part *= 10;
822 *frac_part += d;
823 *frac_scale *= 10;
824 }
825 }
826 return !int_part_empty || *frac_scale != 1;
827 }
828
829 // A helper for ParseDuration() that parses a leading unit designator (e.g.,
830 // ns, us, ms, s, m, h) from the given string and stores the resulting unit
831 // in "*unit". The given string pointer is modified to point to the first
832 // unconsumed char.
ConsumeDurationUnit(const char ** start,Duration * unit)833 bool ConsumeDurationUnit(const char** start, Duration* unit) {
834 const char *s = *start;
835 bool ok = true;
836 if (strncmp(s, "ns", 2) == 0) {
837 s += 2;
838 *unit = Nanoseconds(1);
839 } else if (strncmp(s, "us", 2) == 0) {
840 s += 2;
841 *unit = Microseconds(1);
842 } else if (strncmp(s, "ms", 2) == 0) {
843 s += 2;
844 *unit = Milliseconds(1);
845 } else if (strncmp(s, "s", 1) == 0) {
846 s += 1;
847 *unit = Seconds(1);
848 } else if (strncmp(s, "m", 1) == 0) {
849 s += 1;
850 *unit = Minutes(1);
851 } else if (strncmp(s, "h", 1) == 0) {
852 s += 1;
853 *unit = Hours(1);
854 } else {
855 ok = false;
856 }
857 *start = s;
858 return ok;
859 }
860
861 } // namespace
862
863 // From Go's doc at https://golang.org/pkg/time/#ParseDuration
864 // [ParseDuration] parses a duration string. A duration string is
865 // a possibly signed sequence of decimal numbers, each with optional
866 // fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
867 // Valid time units are "ns", "us" "ms", "s", "m", "h".
ParseDuration(const std::string & dur_string,Duration * d)868 bool ParseDuration(const std::string& dur_string, Duration* d) {
869 const char* start = dur_string.c_str();
870 int sign = 1;
871
872 if (*start == '-' || *start == '+') {
873 sign = *start == '-' ? -1 : 1;
874 ++start;
875 }
876
877 // Can't parse a duration from an empty std::string.
878 if (*start == '\0') {
879 return false;
880 }
881
882 // Special case for a std::string of "0".
883 if (*start == '0' && *(start + 1) == '\0') {
884 *d = ZeroDuration();
885 return true;
886 }
887
888 if (strcmp(start, "inf") == 0) {
889 *d = sign * InfiniteDuration();
890 return true;
891 }
892
893 Duration dur;
894 while (*start != '\0') {
895 int64_t int_part;
896 int64_t frac_part;
897 int64_t frac_scale;
898 Duration unit;
899 if (!ConsumeDurationNumber(&start, &int_part, &frac_part, &frac_scale) ||
900 !ConsumeDurationUnit(&start, &unit)) {
901 return false;
902 }
903 if (int_part != 0) dur += sign * int_part * unit;
904 if (frac_part != 0) dur += sign * frac_part * unit / frac_scale;
905 }
906 *d = dur;
907 return true;
908 }
909
AbslParseFlag(absl::string_view text,Duration * dst,std::string *)910 bool AbslParseFlag(absl::string_view text, Duration* dst, std::string*) {
911 return ParseDuration(std::string(text), dst);
912 }
913
AbslUnparseFlag(Duration d)914 std::string AbslUnparseFlag(Duration d) { return FormatDuration(d); }
ParseFlag(const std::string & text,Duration * dst,std::string *)915 bool ParseFlag(const std::string& text, Duration* dst, std::string* ) {
916 return ParseDuration(text, dst);
917 }
918
UnparseFlag(Duration d)919 std::string UnparseFlag(Duration d) { return FormatDuration(d); }
920
921 ABSL_NAMESPACE_END
922 } // namespace absl
923