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