duration.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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 y_absl::Duration class, which is declared in
  15. // //y_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 y_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 <util/generic/string.h>
  64. #include "y_absl/base/attributes.h"
  65. #include "y_absl/base/casts.h"
  66. #include "y_absl/base/config.h"
  67. #include "y_absl/numeric/int128.h"
  68. #include "y_absl/strings/string_view.h"
  69. #include "y_absl/strings/strip.h"
  70. #include "y_absl/time/time.h"
  71. namespace y_absl {
  72. Y_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 y_absl::bit_cast<uint64_t>(v);
  171. }
  172. inline int64_t DecodeTwosComp(uint64_t v) { return y_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. Y_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 y_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 y_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. int64_t ToInt64Nanoseconds(Duration d) {
  495. if (time_internal::GetRepHi(d) >= 0 &&
  496. time_internal::GetRepHi(d) >> 33 == 0) {
  497. return (time_internal::GetRepHi(d) * 1000 * 1000 * 1000) +
  498. (time_internal::GetRepLo(d) / kTicksPerNanosecond);
  499. }
  500. return d / Nanoseconds(1);
  501. }
  502. int64_t ToInt64Microseconds(Duration d) {
  503. if (time_internal::GetRepHi(d) >= 0 &&
  504. time_internal::GetRepHi(d) >> 43 == 0) {
  505. return (time_internal::GetRepHi(d) * 1000 * 1000) +
  506. (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000));
  507. }
  508. return d / Microseconds(1);
  509. }
  510. int64_t ToInt64Milliseconds(Duration d) {
  511. if (time_internal::GetRepHi(d) >= 0 &&
  512. time_internal::GetRepHi(d) >> 53 == 0) {
  513. return (time_internal::GetRepHi(d) * 1000) +
  514. (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000 * 1000));
  515. }
  516. return d / Milliseconds(1);
  517. }
  518. int64_t ToInt64Seconds(Duration d) {
  519. int64_t hi = time_internal::GetRepHi(d);
  520. if (time_internal::IsInfiniteDuration(d)) return hi;
  521. if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
  522. return hi;
  523. }
  524. int64_t ToInt64Minutes(Duration d) {
  525. int64_t hi = time_internal::GetRepHi(d);
  526. if (time_internal::IsInfiniteDuration(d)) return hi;
  527. if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
  528. return hi / 60;
  529. }
  530. int64_t ToInt64Hours(Duration d) {
  531. int64_t hi = time_internal::GetRepHi(d);
  532. if (time_internal::IsInfiniteDuration(d)) return hi;
  533. if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
  534. return hi / (60 * 60);
  535. }
  536. double ToDoubleNanoseconds(Duration d) {
  537. return FDivDuration(d, Nanoseconds(1));
  538. }
  539. double ToDoubleMicroseconds(Duration d) {
  540. return FDivDuration(d, Microseconds(1));
  541. }
  542. double ToDoubleMilliseconds(Duration d) {
  543. return FDivDuration(d, Milliseconds(1));
  544. }
  545. double ToDoubleSeconds(Duration d) { return FDivDuration(d, Seconds(1)); }
  546. double ToDoubleMinutes(Duration d) { return FDivDuration(d, Minutes(1)); }
  547. double ToDoubleHours(Duration d) { return FDivDuration(d, Hours(1)); }
  548. timespec ToTimespec(Duration d) {
  549. timespec ts;
  550. if (!time_internal::IsInfiniteDuration(d)) {
  551. int64_t rep_hi = time_internal::GetRepHi(d);
  552. uint32_t rep_lo = time_internal::GetRepLo(d);
  553. if (rep_hi < 0) {
  554. // Tweak the fields so that unsigned division of rep_lo
  555. // maps to truncation (towards zero) for the timespec.
  556. rep_lo += kTicksPerNanosecond - 1;
  557. if (rep_lo >= kTicksPerSecond) {
  558. rep_hi += 1;
  559. rep_lo -= kTicksPerSecond;
  560. }
  561. }
  562. ts.tv_sec = static_cast<decltype(ts.tv_sec)>(rep_hi);
  563. if (ts.tv_sec == rep_hi) { // no time_t narrowing
  564. ts.tv_nsec = rep_lo / kTicksPerNanosecond;
  565. return ts;
  566. }
  567. }
  568. if (d >= ZeroDuration()) {
  569. ts.tv_sec = std::numeric_limits<time_t>::max();
  570. ts.tv_nsec = 1000 * 1000 * 1000 - 1;
  571. } else {
  572. ts.tv_sec = std::numeric_limits<time_t>::min();
  573. ts.tv_nsec = 0;
  574. }
  575. return ts;
  576. }
  577. timeval ToTimeval(Duration d) {
  578. timeval tv;
  579. timespec ts = ToTimespec(d);
  580. if (ts.tv_sec < 0) {
  581. // Tweak the fields so that positive division of tv_nsec
  582. // maps to truncation (towards zero) for the timeval.
  583. ts.tv_nsec += 1000 - 1;
  584. if (ts.tv_nsec >= 1000 * 1000 * 1000) {
  585. ts.tv_sec += 1;
  586. ts.tv_nsec -= 1000 * 1000 * 1000;
  587. }
  588. }
  589. tv.tv_sec = static_cast<decltype(tv.tv_sec)>(ts.tv_sec);
  590. if (tv.tv_sec != ts.tv_sec) { // narrowing
  591. if (ts.tv_sec < 0) {
  592. tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min();
  593. tv.tv_usec = 0;
  594. } else {
  595. tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max();
  596. tv.tv_usec = 1000 * 1000 - 1;
  597. }
  598. return tv;
  599. }
  600. tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000); // suseconds_t
  601. return tv;
  602. }
  603. std::chrono::nanoseconds ToChronoNanoseconds(Duration d) {
  604. return time_internal::ToChronoDuration<std::chrono::nanoseconds>(d);
  605. }
  606. std::chrono::microseconds ToChronoMicroseconds(Duration d) {
  607. return time_internal::ToChronoDuration<std::chrono::microseconds>(d);
  608. }
  609. std::chrono::milliseconds ToChronoMilliseconds(Duration d) {
  610. return time_internal::ToChronoDuration<std::chrono::milliseconds>(d);
  611. }
  612. std::chrono::seconds ToChronoSeconds(Duration d) {
  613. return time_internal::ToChronoDuration<std::chrono::seconds>(d);
  614. }
  615. std::chrono::minutes ToChronoMinutes(Duration d) {
  616. return time_internal::ToChronoDuration<std::chrono::minutes>(d);
  617. }
  618. std::chrono::hours ToChronoHours(Duration d) {
  619. return time_internal::ToChronoDuration<std::chrono::hours>(d);
  620. }
  621. //
  622. // To/From string formatting.
  623. //
  624. namespace {
  625. // Formats a positive 64-bit integer in the given field width. Note that
  626. // it is up to the caller of Format64() to ensure that there is sufficient
  627. // space before ep to hold the conversion.
  628. char* Format64(char* ep, int width, int64_t v) {
  629. do {
  630. --width;
  631. *--ep = static_cast<char>('0' + (v % 10)); // contiguous digits
  632. } while (v /= 10);
  633. while (--width >= 0) *--ep = '0'; // zero pad
  634. return ep;
  635. }
  636. // Helpers for FormatDuration() that format 'n' and append it to 'out'
  637. // followed by the given 'unit'. If 'n' formats to "0", nothing is
  638. // appended (not even the unit).
  639. // A type that encapsulates how to display a value of a particular unit. For
  640. // values that are displayed with fractional parts, the precision indicates
  641. // where to round the value. The precision varies with the display unit because
  642. // a Duration can hold only quarters of a nanosecond, so displaying information
  643. // beyond that is just noise.
  644. //
  645. // For example, a microsecond value of 42.00025xxxxx should not display beyond 5
  646. // fractional digits, because it is in the noise of what a Duration can
  647. // represent.
  648. struct DisplayUnit {
  649. y_absl::string_view abbr;
  650. int prec;
  651. double pow10;
  652. };
  653. Y_ABSL_CONST_INIT const DisplayUnit kDisplayNano = {"ns", 2, 1e2};
  654. Y_ABSL_CONST_INIT const DisplayUnit kDisplayMicro = {"us", 5, 1e5};
  655. Y_ABSL_CONST_INIT const DisplayUnit kDisplayMilli = {"ms", 8, 1e8};
  656. Y_ABSL_CONST_INIT const DisplayUnit kDisplaySec = {"s", 11, 1e11};
  657. Y_ABSL_CONST_INIT const DisplayUnit kDisplayMin = {"m", -1, 0.0}; // prec ignored
  658. Y_ABSL_CONST_INIT const DisplayUnit kDisplayHour = {"h", -1,
  659. 0.0}; // prec ignored
  660. void AppendNumberUnit(TString* out, int64_t n, DisplayUnit unit) {
  661. char buf[sizeof("2562047788015216")]; // hours in max duration
  662. char* const ep = buf + sizeof(buf);
  663. char* bp = Format64(ep, 0, n);
  664. if (*bp != '0' || bp + 1 != ep) {
  665. out->append(bp, static_cast<size_t>(ep - bp));
  666. out->append(unit.abbr.data(), unit.abbr.size());
  667. }
  668. }
  669. // Note: unit.prec is limited to double's digits10 value (typically 15) so it
  670. // always fits in buf[].
  671. void AppendNumberUnit(TString* out, double n, DisplayUnit unit) {
  672. constexpr int kBufferSize = std::numeric_limits<double>::digits10;
  673. const int prec = std::min(kBufferSize, unit.prec);
  674. char buf[kBufferSize]; // also large enough to hold integer part
  675. char* ep = buf + sizeof(buf);
  676. double d = 0;
  677. int64_t frac_part = std::round(std::modf(n, &d) * unit.pow10);
  678. int64_t int_part = d;
  679. if (int_part != 0 || frac_part != 0) {
  680. char* bp = Format64(ep, 0, int_part); // always < 1000
  681. out->append(bp, static_cast<size_t>(ep - bp));
  682. if (frac_part != 0) {
  683. out->push_back('.');
  684. bp = Format64(ep, prec, frac_part);
  685. while (ep[-1] == '0') --ep;
  686. out->append(bp, static_cast<size_t>(ep - bp));
  687. }
  688. out->append(unit.abbr.data(), unit.abbr.size());
  689. }
  690. }
  691. } // namespace
  692. // From Go's doc at https://golang.org/pkg/time/#Duration.String
  693. // [FormatDuration] returns a string representing the duration in the
  694. // form "72h3m0.5s". Leading zero units are omitted. As a special
  695. // case, durations less than one second format use a smaller unit
  696. // (milli-, micro-, or nanoseconds) to ensure that the leading digit
  697. // is non-zero.
  698. // Unlike Go, we format the zero duration as 0, with no unit.
  699. TString FormatDuration(Duration d) {
  700. constexpr Duration kMinDuration = Seconds(kint64min);
  701. TString s;
  702. if (d == kMinDuration) {
  703. // Avoid needing to negate kint64min by directly returning what the
  704. // following code should produce in that case.
  705. s = "-2562047788015215h30m8s";
  706. return s;
  707. }
  708. if (d < ZeroDuration()) {
  709. s.append("-");
  710. d = -d;
  711. }
  712. if (d == InfiniteDuration()) {
  713. s.append("inf");
  714. } else if (d < Seconds(1)) {
  715. // Special case for durations with a magnitude < 1 second. The duration
  716. // is printed as a fraction of a single unit, e.g., "1.2ms".
  717. if (d < Microseconds(1)) {
  718. AppendNumberUnit(&s, FDivDuration(d, Nanoseconds(1)), kDisplayNano);
  719. } else if (d < Milliseconds(1)) {
  720. AppendNumberUnit(&s, FDivDuration(d, Microseconds(1)), kDisplayMicro);
  721. } else {
  722. AppendNumberUnit(&s, FDivDuration(d, Milliseconds(1)), kDisplayMilli);
  723. }
  724. } else {
  725. AppendNumberUnit(&s, IDivDuration(d, Hours(1), &d), kDisplayHour);
  726. AppendNumberUnit(&s, IDivDuration(d, Minutes(1), &d), kDisplayMin);
  727. AppendNumberUnit(&s, FDivDuration(d, Seconds(1)), kDisplaySec);
  728. }
  729. if (s.empty() || s == "-") {
  730. s = "0";
  731. }
  732. return s;
  733. }
  734. namespace {
  735. // A helper for ParseDuration() that parses a leading number from the given
  736. // string and stores the result in *int_part/*frac_part/*frac_scale. The
  737. // given string pointer is modified to point to the first unconsumed char.
  738. bool ConsumeDurationNumber(const char** dpp, const char* ep, int64_t* int_part,
  739. int64_t* frac_part, int64_t* frac_scale) {
  740. *int_part = 0;
  741. *frac_part = 0;
  742. *frac_scale = 1; // invariant: *frac_part < *frac_scale
  743. const char* start = *dpp;
  744. for (; *dpp != ep; *dpp += 1) {
  745. const int d = **dpp - '0'; // contiguous digits
  746. if (d < 0 || 10 <= d) break;
  747. if (*int_part > kint64max / 10) return false;
  748. *int_part *= 10;
  749. if (*int_part > kint64max - d) return false;
  750. *int_part += d;
  751. }
  752. const bool int_part_empty = (*dpp == start);
  753. if (*dpp == ep || **dpp != '.') return !int_part_empty;
  754. for (*dpp += 1; *dpp != ep; *dpp += 1) {
  755. const int d = **dpp - '0'; // contiguous digits
  756. if (d < 0 || 10 <= d) break;
  757. if (*frac_scale <= kint64max / 10) {
  758. *frac_part *= 10;
  759. *frac_part += d;
  760. *frac_scale *= 10;
  761. }
  762. }
  763. return !int_part_empty || *frac_scale != 1;
  764. }
  765. // A helper for ParseDuration() that parses a leading unit designator (e.g.,
  766. // ns, us, ms, s, m, h) from the given string and stores the resulting unit
  767. // in "*unit". The given string pointer is modified to point to the first
  768. // unconsumed char.
  769. bool ConsumeDurationUnit(const char** start, const char* end, Duration* unit) {
  770. size_t size = static_cast<size_t>(end - *start);
  771. switch (size) {
  772. case 0:
  773. return false;
  774. default:
  775. switch (**start) {
  776. case 'n':
  777. if (*(*start + 1) == 's') {
  778. *start += 2;
  779. *unit = Nanoseconds(1);
  780. return true;
  781. }
  782. break;
  783. case 'u':
  784. if (*(*start + 1) == 's') {
  785. *start += 2;
  786. *unit = Microseconds(1);
  787. return true;
  788. }
  789. break;
  790. case 'm':
  791. if (*(*start + 1) == 's') {
  792. *start += 2;
  793. *unit = Milliseconds(1);
  794. return true;
  795. }
  796. break;
  797. default:
  798. break;
  799. }
  800. Y_ABSL_FALLTHROUGH_INTENDED;
  801. case 1:
  802. switch (**start) {
  803. case 's':
  804. *unit = Seconds(1);
  805. *start += 1;
  806. return true;
  807. case 'm':
  808. *unit = Minutes(1);
  809. *start += 1;
  810. return true;
  811. case 'h':
  812. *unit = Hours(1);
  813. *start += 1;
  814. return true;
  815. default:
  816. return false;
  817. }
  818. }
  819. }
  820. } // namespace
  821. // From Go's doc at https://golang.org/pkg/time/#ParseDuration
  822. // [ParseDuration] parses a duration string. A duration string is
  823. // a possibly signed sequence of decimal numbers, each with optional
  824. // fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
  825. // Valid time units are "ns", "us" "ms", "s", "m", "h".
  826. bool ParseDuration(y_absl::string_view dur_sv, Duration* d) {
  827. int sign = 1;
  828. if (y_absl::ConsumePrefix(&dur_sv, "-")) {
  829. sign = -1;
  830. } else {
  831. y_absl::ConsumePrefix(&dur_sv, "+");
  832. }
  833. if (dur_sv.empty()) return false;
  834. // Special case for a string of "0".
  835. if (dur_sv == "0") {
  836. *d = ZeroDuration();
  837. return true;
  838. }
  839. if (dur_sv == "inf") {
  840. *d = sign * InfiniteDuration();
  841. return true;
  842. }
  843. const char* start = dur_sv.data();
  844. const char* end = start + dur_sv.size();
  845. Duration dur;
  846. while (start != end) {
  847. int64_t int_part;
  848. int64_t frac_part;
  849. int64_t frac_scale;
  850. Duration unit;
  851. if (!ConsumeDurationNumber(&start, end, &int_part, &frac_part,
  852. &frac_scale) ||
  853. !ConsumeDurationUnit(&start, end, &unit)) {
  854. return false;
  855. }
  856. if (int_part != 0) dur += sign * int_part * unit;
  857. if (frac_part != 0) dur += sign * frac_part * unit / frac_scale;
  858. }
  859. *d = dur;
  860. return true;
  861. }
  862. bool AbslParseFlag(y_absl::string_view text, Duration* dst, TString*) {
  863. return ParseDuration(text, dst);
  864. }
  865. TString AbslUnparseFlag(Duration d) { return FormatDuration(d); }
  866. bool ParseFlag(const TString& text, Duration* dst, TString* ) {
  867. return ParseDuration(text, dst);
  868. }
  869. TString UnparseFlag(Duration d) { return FormatDuration(d); }
  870. Y_ABSL_NAMESPACE_END
  871. } // namespace y_absl