duration.cc 30 KB

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