Coverage Report

Created: 2026-10-28 06:49

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