duration.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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 <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 <util/generic/string.h>
  65. #include "y_absl/base/casts.h"
  66. #include "y_absl/base/macros.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 > kuint128max / b) ? kuint128max : 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 && den_lo == kTicksPerNanosecond) {
  257. // Dividing by 1ns
  258. if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000000000) {
  259. *q = num_hi * 1000000000 + num_lo / kTicksPerNanosecond;
  260. *rem = time_internal::MakeDuration(0, num_lo % den_lo);
  261. return true;
  262. }
  263. } else if (den_hi == 0 && den_lo == 100 * kTicksPerNanosecond) {
  264. // Dividing by 100ns (common when converting to Universal time)
  265. if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 10000000) {
  266. *q = num_hi * 10000000 + num_lo / (100 * kTicksPerNanosecond);
  267. *rem = time_internal::MakeDuration(0, num_lo % den_lo);
  268. return true;
  269. }
  270. } else if (den_hi == 0 && den_lo == 1000 * kTicksPerNanosecond) {
  271. // Dividing by 1us
  272. if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000000) {
  273. *q = num_hi * 1000000 + num_lo / (1000 * kTicksPerNanosecond);
  274. *rem = time_internal::MakeDuration(0, num_lo % den_lo);
  275. return true;
  276. }
  277. } else if (den_hi == 0 && den_lo == 1000000 * kTicksPerNanosecond) {
  278. // Dividing by 1ms
  279. if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000) {
  280. *q = num_hi * 1000 + num_lo / (1000000 * kTicksPerNanosecond);
  281. *rem = time_internal::MakeDuration(0, num_lo % den_lo);
  282. return true;
  283. }
  284. } else if (den_hi > 0 && den_lo == 0) {
  285. // Dividing by positive multiple of 1s
  286. if (num_hi >= 0) {
  287. if (den_hi == 1) {
  288. *q = num_hi;
  289. *rem = time_internal::MakeDuration(0, num_lo);
  290. return true;
  291. }
  292. *q = num_hi / den_hi;
  293. *rem = time_internal::MakeDuration(num_hi % den_hi, num_lo);
  294. return true;
  295. }
  296. if (num_lo != 0) {
  297. num_hi += 1;
  298. }
  299. int64_t quotient = num_hi / den_hi;
  300. int64_t rem_sec = num_hi % den_hi;
  301. if (rem_sec > 0) {
  302. rem_sec -= den_hi;
  303. quotient += 1;
  304. }
  305. if (num_lo != 0) {
  306. rem_sec -= 1;
  307. }
  308. *q = quotient;
  309. *rem = time_internal::MakeDuration(rem_sec, num_lo);
  310. return true;
  311. }
  312. return false;
  313. }
  314. } // namespace
  315. namespace time_internal {
  316. // The 'satq' argument indicates whether the quotient should saturate at the
  317. // bounds of int64_t. If it does saturate, the difference will spill over to
  318. // the remainder. If it does not saturate, the remainder remain accurate,
  319. // but the returned quotient will over/underflow int64_t and should not be used.
  320. int64_t IDivDuration(bool satq, const Duration num, const Duration den,
  321. Duration* rem) {
  322. int64_t q = 0;
  323. if (IDivFastPath(num, den, &q, rem)) {
  324. return q;
  325. }
  326. const bool num_neg = num < ZeroDuration();
  327. const bool den_neg = den < ZeroDuration();
  328. const bool quotient_neg = num_neg != den_neg;
  329. if (time_internal::IsInfiniteDuration(num) || den == ZeroDuration()) {
  330. *rem = num_neg ? -InfiniteDuration() : InfiniteDuration();
  331. return quotient_neg ? kint64min : kint64max;
  332. }
  333. if (time_internal::IsInfiniteDuration(den)) {
  334. *rem = num;
  335. return 0;
  336. }
  337. const uint128 a = MakeU128Ticks(num);
  338. const uint128 b = MakeU128Ticks(den);
  339. uint128 quotient128 = a / b;
  340. if (satq) {
  341. // Limits the quotient to the range of int64_t.
  342. if (quotient128 > uint128(static_cast<uint64_t>(kint64max))) {
  343. quotient128 = quotient_neg ? uint128(static_cast<uint64_t>(kint64min))
  344. : uint128(static_cast<uint64_t>(kint64max));
  345. }
  346. }
  347. const uint128 remainder128 = a - quotient128 * b;
  348. *rem = MakeDurationFromU128(remainder128, num_neg);
  349. if (!quotient_neg || quotient128 == 0) {
  350. return Uint128Low64(quotient128) & kint64max;
  351. }
  352. // The quotient needs to be negated, but we need to carefully handle
  353. // quotient128s with the top bit on.
  354. return -static_cast<int64_t>(Uint128Low64(quotient128 - 1) & kint64max) - 1;
  355. }
  356. } // namespace time_internal
  357. //
  358. // Additive operators.
  359. //
  360. Duration& Duration::operator+=(Duration rhs) {
  361. if (time_internal::IsInfiniteDuration(*this)) return *this;
  362. if (time_internal::IsInfiniteDuration(rhs)) return *this = rhs;
  363. const int64_t orig_rep_hi = rep_hi_.Get();
  364. rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) +
  365. EncodeTwosComp(rhs.rep_hi_.Get()));
  366. if (rep_lo_ >= kTicksPerSecond - rhs.rep_lo_) {
  367. rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) + 1);
  368. rep_lo_ -= kTicksPerSecond;
  369. }
  370. rep_lo_ += rhs.rep_lo_;
  371. if (rhs.rep_hi_.Get() < 0 ? rep_hi_.Get() > orig_rep_hi
  372. : rep_hi_.Get() < orig_rep_hi) {
  373. return *this =
  374. rhs.rep_hi_.Get() < 0 ? -InfiniteDuration() : InfiniteDuration();
  375. }
  376. return *this;
  377. }
  378. Duration& Duration::operator-=(Duration rhs) {
  379. if (time_internal::IsInfiniteDuration(*this)) return *this;
  380. if (time_internal::IsInfiniteDuration(rhs)) {
  381. return *this = rhs.rep_hi_.Get() >= 0 ? -InfiniteDuration()
  382. : InfiniteDuration();
  383. }
  384. const int64_t orig_rep_hi = rep_hi_.Get();
  385. rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) -
  386. EncodeTwosComp(rhs.rep_hi_.Get()));
  387. if (rep_lo_ < rhs.rep_lo_) {
  388. rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) - 1);
  389. rep_lo_ += kTicksPerSecond;
  390. }
  391. rep_lo_ -= rhs.rep_lo_;
  392. if (rhs.rep_hi_.Get() < 0 ? rep_hi_.Get() < orig_rep_hi
  393. : rep_hi_.Get() > orig_rep_hi) {
  394. return *this = rhs.rep_hi_.Get() >= 0 ? -InfiniteDuration()
  395. : InfiniteDuration();
  396. }
  397. return *this;
  398. }
  399. //
  400. // Multiplicative operators.
  401. //
  402. Duration& Duration::operator*=(int64_t r) {
  403. if (time_internal::IsInfiniteDuration(*this)) {
  404. const bool is_neg = (r < 0) != (rep_hi_.Get() < 0);
  405. return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
  406. }
  407. return *this = ScaleFixed<SafeMultiply>(*this, r);
  408. }
  409. Duration& Duration::operator*=(double r) {
  410. if (time_internal::IsInfiniteDuration(*this) || !IsFinite(r)) {
  411. const bool is_neg = std::signbit(r) != (rep_hi_.Get() < 0);
  412. return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
  413. }
  414. return *this = ScaleDouble<std::multiplies>(*this, r);
  415. }
  416. Duration& Duration::operator/=(int64_t r) {
  417. if (time_internal::IsInfiniteDuration(*this) || r == 0) {
  418. const bool is_neg = (r < 0) != (rep_hi_.Get() < 0);
  419. return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
  420. }
  421. return *this = ScaleFixed<std::divides>(*this, r);
  422. }
  423. Duration& Duration::operator/=(double r) {
  424. if (time_internal::IsInfiniteDuration(*this) || !IsValidDivisor(r)) {
  425. const bool is_neg = std::signbit(r) != (rep_hi_.Get() < 0);
  426. return *this = is_neg ? -InfiniteDuration() : InfiniteDuration();
  427. }
  428. return *this = ScaleDouble<std::divides>(*this, r);
  429. }
  430. Duration& Duration::operator%=(Duration rhs) {
  431. time_internal::IDivDuration(false, *this, rhs, this);
  432. return *this;
  433. }
  434. double FDivDuration(Duration num, Duration den) {
  435. // Arithmetic with infinity is sticky.
  436. if (time_internal::IsInfiniteDuration(num) || den == ZeroDuration()) {
  437. return (num < ZeroDuration()) == (den < ZeroDuration())
  438. ? std::numeric_limits<double>::infinity()
  439. : -std::numeric_limits<double>::infinity();
  440. }
  441. if (time_internal::IsInfiniteDuration(den)) return 0.0;
  442. double a =
  443. static_cast<double>(time_internal::GetRepHi(num)) * kTicksPerSecond +
  444. time_internal::GetRepLo(num);
  445. double b =
  446. static_cast<double>(time_internal::GetRepHi(den)) * kTicksPerSecond +
  447. time_internal::GetRepLo(den);
  448. return a / b;
  449. }
  450. //
  451. // Trunc/Floor/Ceil.
  452. //
  453. Duration Trunc(Duration d, Duration unit) {
  454. return d - (d % unit);
  455. }
  456. Duration Floor(const Duration d, const Duration unit) {
  457. const y_absl::Duration td = Trunc(d, unit);
  458. return td <= d ? td : td - AbsDuration(unit);
  459. }
  460. Duration Ceil(const Duration d, const Duration unit) {
  461. const y_absl::Duration td = Trunc(d, unit);
  462. return td >= d ? td : td + AbsDuration(unit);
  463. }
  464. //
  465. // Factory functions.
  466. //
  467. Duration DurationFromTimespec(timespec ts) {
  468. if (static_cast<uint64_t>(ts.tv_nsec) < 1000 * 1000 * 1000) {
  469. int64_t ticks = ts.tv_nsec * kTicksPerNanosecond;
  470. return time_internal::MakeDuration(ts.tv_sec, ticks);
  471. }
  472. return Seconds(ts.tv_sec) + Nanoseconds(ts.tv_nsec);
  473. }
  474. Duration DurationFromTimeval(timeval tv) {
  475. if (static_cast<uint64_t>(tv.tv_usec) < 1000 * 1000) {
  476. int64_t ticks = tv.tv_usec * 1000 * kTicksPerNanosecond;
  477. return time_internal::MakeDuration(tv.tv_sec, ticks);
  478. }
  479. return Seconds(tv.tv_sec) + Microseconds(tv.tv_usec);
  480. }
  481. //
  482. // Conversion to other duration types.
  483. //
  484. int64_t ToInt64Nanoseconds(Duration d) {
  485. if (time_internal::GetRepHi(d) >= 0 &&
  486. time_internal::GetRepHi(d) >> 33 == 0) {
  487. return (time_internal::GetRepHi(d) * 1000 * 1000 * 1000) +
  488. (time_internal::GetRepLo(d) / kTicksPerNanosecond);
  489. }
  490. return d / Nanoseconds(1);
  491. }
  492. int64_t ToInt64Microseconds(Duration d) {
  493. if (time_internal::GetRepHi(d) >= 0 &&
  494. time_internal::GetRepHi(d) >> 43 == 0) {
  495. return (time_internal::GetRepHi(d) * 1000 * 1000) +
  496. (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000));
  497. }
  498. return d / Microseconds(1);
  499. }
  500. int64_t ToInt64Milliseconds(Duration d) {
  501. if (time_internal::GetRepHi(d) >= 0 &&
  502. time_internal::GetRepHi(d) >> 53 == 0) {
  503. return (time_internal::GetRepHi(d) * 1000) +
  504. (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000 * 1000));
  505. }
  506. return d / Milliseconds(1);
  507. }
  508. int64_t ToInt64Seconds(Duration d) {
  509. int64_t hi = time_internal::GetRepHi(d);
  510. if (time_internal::IsInfiniteDuration(d)) return hi;
  511. if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
  512. return hi;
  513. }
  514. int64_t ToInt64Minutes(Duration d) {
  515. int64_t hi = time_internal::GetRepHi(d);
  516. if (time_internal::IsInfiniteDuration(d)) return hi;
  517. if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
  518. return hi / 60;
  519. }
  520. int64_t ToInt64Hours(Duration d) {
  521. int64_t hi = time_internal::GetRepHi(d);
  522. if (time_internal::IsInfiniteDuration(d)) return hi;
  523. if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi;
  524. return hi / (60 * 60);
  525. }
  526. double ToDoubleNanoseconds(Duration d) {
  527. return FDivDuration(d, Nanoseconds(1));
  528. }
  529. double ToDoubleMicroseconds(Duration d) {
  530. return FDivDuration(d, Microseconds(1));
  531. }
  532. double ToDoubleMilliseconds(Duration d) {
  533. return FDivDuration(d, Milliseconds(1));
  534. }
  535. double ToDoubleSeconds(Duration d) {
  536. return FDivDuration(d, Seconds(1));
  537. }
  538. double ToDoubleMinutes(Duration d) {
  539. return FDivDuration(d, Minutes(1));
  540. }
  541. double ToDoubleHours(Duration d) {
  542. return FDivDuration(d, Hours(1));
  543. }
  544. timespec ToTimespec(Duration d) {
  545. timespec ts;
  546. if (!time_internal::IsInfiniteDuration(d)) {
  547. int64_t rep_hi = time_internal::GetRepHi(d);
  548. uint32_t rep_lo = time_internal::GetRepLo(d);
  549. if (rep_hi < 0) {
  550. // Tweak the fields so that unsigned division of rep_lo
  551. // maps to truncation (towards zero) for the timespec.
  552. rep_lo += kTicksPerNanosecond - 1;
  553. if (rep_lo >= kTicksPerSecond) {
  554. rep_hi += 1;
  555. rep_lo -= kTicksPerSecond;
  556. }
  557. }
  558. ts.tv_sec = static_cast<decltype(ts.tv_sec)>(rep_hi);
  559. if (ts.tv_sec == rep_hi) { // no time_t narrowing
  560. ts.tv_nsec = rep_lo / kTicksPerNanosecond;
  561. return ts;
  562. }
  563. }
  564. if (d >= ZeroDuration()) {
  565. ts.tv_sec = std::numeric_limits<time_t>::max();
  566. ts.tv_nsec = 1000 * 1000 * 1000 - 1;
  567. } else {
  568. ts.tv_sec = std::numeric_limits<time_t>::min();
  569. ts.tv_nsec = 0;
  570. }
  571. return ts;
  572. }
  573. timeval ToTimeval(Duration d) {
  574. timeval tv;
  575. timespec ts = ToTimespec(d);
  576. if (ts.tv_sec < 0) {
  577. // Tweak the fields so that positive division of tv_nsec
  578. // maps to truncation (towards zero) for the timeval.
  579. ts.tv_nsec += 1000 - 1;
  580. if (ts.tv_nsec >= 1000 * 1000 * 1000) {
  581. ts.tv_sec += 1;
  582. ts.tv_nsec -= 1000 * 1000 * 1000;
  583. }
  584. }
  585. tv.tv_sec = static_cast<decltype(tv.tv_sec)>(ts.tv_sec);
  586. if (tv.tv_sec != ts.tv_sec) { // narrowing
  587. if (ts.tv_sec < 0) {
  588. tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min();
  589. tv.tv_usec = 0;
  590. } else {
  591. tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max();
  592. tv.tv_usec = 1000 * 1000 - 1;
  593. }
  594. return tv;
  595. }
  596. tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000); // suseconds_t
  597. return tv;
  598. }
  599. std::chrono::nanoseconds ToChronoNanoseconds(Duration d) {
  600. return time_internal::ToChronoDuration<std::chrono::nanoseconds>(d);
  601. }
  602. std::chrono::microseconds ToChronoMicroseconds(Duration d) {
  603. return time_internal::ToChronoDuration<std::chrono::microseconds>(d);
  604. }
  605. std::chrono::milliseconds ToChronoMilliseconds(Duration d) {
  606. return time_internal::ToChronoDuration<std::chrono::milliseconds>(d);
  607. }
  608. std::chrono::seconds ToChronoSeconds(Duration d) {
  609. return time_internal::ToChronoDuration<std::chrono::seconds>(d);
  610. }
  611. std::chrono::minutes ToChronoMinutes(Duration d) {
  612. return time_internal::ToChronoDuration<std::chrono::minutes>(d);
  613. }
  614. std::chrono::hours ToChronoHours(Duration d) {
  615. return time_internal::ToChronoDuration<std::chrono::hours>(d);
  616. }
  617. //
  618. // To/From string formatting.
  619. //
  620. namespace {
  621. // Formats a positive 64-bit integer in the given field width. Note that
  622. // it is up to the caller of Format64() to ensure that there is sufficient
  623. // space before ep to hold the conversion.
  624. char* Format64(char* ep, int width, int64_t v) {
  625. do {
  626. --width;
  627. *--ep = static_cast<char>('0' + (v % 10)); // contiguous digits
  628. } while (v /= 10);
  629. while (--width >= 0) *--ep = '0'; // zero pad
  630. return ep;
  631. }
  632. // Helpers for FormatDuration() that format 'n' and append it to 'out'
  633. // followed by the given 'unit'. If 'n' formats to "0", nothing is
  634. // appended (not even the unit).
  635. // A type that encapsulates how to display a value of a particular unit. For
  636. // values that are displayed with fractional parts, the precision indicates
  637. // where to round the value. The precision varies with the display unit because
  638. // a Duration can hold only quarters of a nanosecond, so displaying information
  639. // beyond that is just noise.
  640. //
  641. // For example, a microsecond value of 42.00025xxxxx should not display beyond 5
  642. // fractional digits, because it is in the noise of what a Duration can
  643. // represent.
  644. struct DisplayUnit {
  645. y_absl::string_view abbr;
  646. int prec;
  647. double pow10;
  648. };
  649. Y_ABSL_CONST_INIT const DisplayUnit kDisplayNano = {"ns", 2, 1e2};
  650. Y_ABSL_CONST_INIT const DisplayUnit kDisplayMicro = {"us", 5, 1e5};
  651. Y_ABSL_CONST_INIT const DisplayUnit kDisplayMilli = {"ms", 8, 1e8};
  652. Y_ABSL_CONST_INIT const DisplayUnit kDisplaySec = {"s", 11, 1e11};
  653. Y_ABSL_CONST_INIT const DisplayUnit kDisplayMin = {"m", -1, 0.0}; // prec ignored
  654. Y_ABSL_CONST_INIT const DisplayUnit kDisplayHour = {"h", -1,
  655. 0.0}; // prec ignored
  656. void AppendNumberUnit(TString* out, int64_t n, DisplayUnit unit) {
  657. char buf[sizeof("2562047788015216")]; // hours in max duration
  658. char* const ep = buf + sizeof(buf);
  659. char* bp = Format64(ep, 0, n);
  660. if (*bp != '0' || bp + 1 != ep) {
  661. out->append(bp, static_cast<size_t>(ep - bp));
  662. out->append(unit.abbr.data(), unit.abbr.size());
  663. }
  664. }
  665. // Note: unit.prec is limited to double's digits10 value (typically 15) so it
  666. // always fits in buf[].
  667. void AppendNumberUnit(TString* out, double n, DisplayUnit unit) {
  668. constexpr int kBufferSize = std::numeric_limits<double>::digits10;
  669. const int prec = std::min(kBufferSize, unit.prec);
  670. char buf[kBufferSize]; // also large enough to hold integer part
  671. char* ep = buf + sizeof(buf);
  672. double d = 0;
  673. int64_t frac_part = std::round(std::modf(n, &d) * unit.pow10);
  674. int64_t int_part = d;
  675. if (int_part != 0 || frac_part != 0) {
  676. char* bp = Format64(ep, 0, int_part); // always < 1000
  677. out->append(bp, static_cast<size_t>(ep - bp));
  678. if (frac_part != 0) {
  679. out->push_back('.');
  680. bp = Format64(ep, prec, frac_part);
  681. while (ep[-1] == '0') --ep;
  682. out->append(bp, static_cast<size_t>(ep - bp));
  683. }
  684. out->append(unit.abbr.data(), unit.abbr.size());
  685. }
  686. }
  687. } // namespace
  688. // From Go's doc at https://golang.org/pkg/time/#Duration.String
  689. // [FormatDuration] returns a string representing the duration in the
  690. // form "72h3m0.5s". Leading zero units are omitted. As a special
  691. // case, durations less than one second format use a smaller unit
  692. // (milli-, micro-, or nanoseconds) to ensure that the leading digit
  693. // is non-zero.
  694. // Unlike Go, we format the zero duration as 0, with no unit.
  695. TString FormatDuration(Duration d) {
  696. constexpr Duration kMinDuration = Seconds(kint64min);
  697. TString s;
  698. if (d == kMinDuration) {
  699. // Avoid needing to negate kint64min by directly returning what the
  700. // following code should produce in that case.
  701. s = "-2562047788015215h30m8s";
  702. return s;
  703. }
  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 = static_cast<size_t>(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. Y_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(y_absl::string_view dur_sv, Duration* d) {
  823. int sign = 1;
  824. if (y_absl::ConsumePrefix(&dur_sv, "-")) {
  825. sign = -1;
  826. } else {
  827. y_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(y_absl::string_view text, Duration* dst, TString*) {
  859. return ParseDuration(text, dst);
  860. }
  861. TString AbslUnparseFlag(Duration d) { return FormatDuration(d); }
  862. bool ParseFlag(const TString& text, Duration* dst, TString* ) {
  863. return ParseDuration(text, dst);
  864. }
  865. TString UnparseFlag(Duration d) { return FormatDuration(d); }
  866. Y_ABSL_NAMESPACE_END
  867. } // namespace y_absl