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