duration.cc 31 KB

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