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


abseil_cpp
Author(s):
autogenerated on Tue Jun 18 2019 19:44:35