time.h 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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. //
  15. // -----------------------------------------------------------------------------
  16. // File: time.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines abstractions for computing with absolute points
  20. // in time, durations of time, and formatting and parsing time within a given
  21. // time zone. The following abstractions are defined:
  22. //
  23. // * `y_absl::Time` defines an absolute, specific instance in time
  24. // * `y_absl::Duration` defines a signed, fixed-length span of time
  25. // * `y_absl::TimeZone` defines geopolitical time zone regions (as collected
  26. // within the IANA Time Zone database (https://www.iana.org/time-zones)).
  27. //
  28. // Note: Absolute times are distinct from civil times, which refer to the
  29. // human-scale time commonly represented by `YYYY-MM-DD hh:mm:ss`. The mapping
  30. // between absolute and civil times can be specified by use of time zones
  31. // (`y_absl::TimeZone` within this API). That is:
  32. //
  33. // Civil Time = F(Absolute Time, Time Zone)
  34. // Absolute Time = G(Civil Time, Time Zone)
  35. //
  36. // See civil_time.h for abstractions related to constructing and manipulating
  37. // civil time.
  38. //
  39. // Example:
  40. //
  41. // y_absl::TimeZone nyc;
  42. // // LoadTimeZone() may fail so it's always better to check for success.
  43. // if (!y_absl::LoadTimeZone("America/New_York", &nyc)) {
  44. // // handle error case
  45. // }
  46. //
  47. // // My flight leaves NYC on Jan 2, 2017 at 03:04:05
  48. // y_absl::CivilSecond cs(2017, 1, 2, 3, 4, 5);
  49. // y_absl::Time takeoff = y_absl::FromCivil(cs, nyc);
  50. //
  51. // y_absl::Duration flight_duration = y_absl::Hours(21) + y_absl::Minutes(35);
  52. // y_absl::Time landing = takeoff + flight_duration;
  53. //
  54. // y_absl::TimeZone syd;
  55. // if (!y_absl::LoadTimeZone("Australia/Sydney", &syd)) {
  56. // // handle error case
  57. // }
  58. // TString s = y_absl::FormatTime(
  59. // "My flight will land in Sydney on %Y-%m-%d at %H:%M:%S",
  60. // landing, syd);
  61. #ifndef Y_ABSL_TIME_TIME_H_
  62. #define Y_ABSL_TIME_TIME_H_
  63. #if !defined(_MSC_VER)
  64. #include <sys/time.h>
  65. #else
  66. // We don't include `winsock2.h` because it drags in `windows.h` and friends,
  67. // and they define conflicting macros like OPAQUE, ERROR, and more. This has the
  68. // potential to break Abseil users.
  69. //
  70. // Instead we only forward declare `timeval` and require Windows users include
  71. // `winsock2.h` themselves. This is both inconsistent and troublesome, but so is
  72. // including 'windows.h' so we are picking the lesser of two evils here.
  73. struct timeval;
  74. #endif
  75. #include <chrono> // NOLINT(build/c++11)
  76. #include <cmath>
  77. #include <cstdint>
  78. #include <ctime>
  79. #include <ostream>
  80. #include <util/generic/string.h>
  81. #include <type_traits>
  82. #include <utility>
  83. #include "y_absl/base/macros.h"
  84. #include "y_absl/strings/string_view.h"
  85. #include "y_absl/time/civil_time.h"
  86. #include "y_absl/time/internal/cctz/include/cctz/time_zone.h"
  87. namespace y_absl {
  88. Y_ABSL_NAMESPACE_BEGIN
  89. class Duration; // Defined below
  90. class Time; // Defined below
  91. class TimeZone; // Defined below
  92. namespace time_internal {
  93. int64_t IDivDuration(bool satq, Duration num, Duration den, Duration* rem);
  94. constexpr Time FromUnixDuration(Duration d);
  95. constexpr Duration ToUnixDuration(Time t);
  96. constexpr int64_t GetRepHi(Duration d);
  97. constexpr uint32_t GetRepLo(Duration d);
  98. constexpr Duration MakeDuration(int64_t hi, uint32_t lo);
  99. constexpr Duration MakeDuration(int64_t hi, int64_t lo);
  100. inline Duration MakePosDoubleDuration(double n);
  101. constexpr int64_t kTicksPerNanosecond = 4;
  102. constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond;
  103. template <std::intmax_t N>
  104. constexpr Duration FromInt64(int64_t v, std::ratio<1, N>);
  105. constexpr Duration FromInt64(int64_t v, std::ratio<60>);
  106. constexpr Duration FromInt64(int64_t v, std::ratio<3600>);
  107. template <typename T>
  108. using EnableIfIntegral = typename std::enable_if<
  109. std::is_integral<T>::value || std::is_enum<T>::value, int>::type;
  110. template <typename T>
  111. using EnableIfFloat =
  112. typename std::enable_if<std::is_floating_point<T>::value, int>::type;
  113. } // namespace time_internal
  114. // Duration
  115. //
  116. // The `y_absl::Duration` class represents a signed, fixed-length span of time.
  117. // A `Duration` is generated using a unit-specific factory function, or is
  118. // the result of subtracting one `y_absl::Time` from another. Durations behave
  119. // like unit-safe integers and they support all the natural integer-like
  120. // arithmetic operations. Arithmetic overflows and saturates at +/- infinity.
  121. // `Duration` should be passed by value rather than const reference.
  122. //
  123. // Factory functions `Nanoseconds()`, `Microseconds()`, `Milliseconds()`,
  124. // `Seconds()`, `Minutes()`, `Hours()` and `InfiniteDuration()` allow for
  125. // creation of constexpr `Duration` values
  126. //
  127. // Examples:
  128. //
  129. // constexpr y_absl::Duration ten_ns = y_absl::Nanoseconds(10);
  130. // constexpr y_absl::Duration min = y_absl::Minutes(1);
  131. // constexpr y_absl::Duration hour = y_absl::Hours(1);
  132. // y_absl::Duration dur = 60 * min; // dur == hour
  133. // y_absl::Duration half_sec = y_absl::Milliseconds(500);
  134. // y_absl::Duration quarter_sec = 0.25 * y_absl::Seconds(1);
  135. //
  136. // `Duration` values can be easily converted to an integral number of units
  137. // using the division operator.
  138. //
  139. // Example:
  140. //
  141. // constexpr y_absl::Duration dur = y_absl::Milliseconds(1500);
  142. // int64_t ns = dur / y_absl::Nanoseconds(1); // ns == 1500000000
  143. // int64_t ms = dur / y_absl::Milliseconds(1); // ms == 1500
  144. // int64_t sec = dur / y_absl::Seconds(1); // sec == 1 (subseconds truncated)
  145. // int64_t min = dur / y_absl::Minutes(1); // min == 0
  146. //
  147. // See the `IDivDuration()` and `FDivDuration()` functions below for details on
  148. // how to access the fractional parts of the quotient.
  149. //
  150. // Alternatively, conversions can be performed using helpers such as
  151. // `ToInt64Microseconds()` and `ToDoubleSeconds()`.
  152. class Duration {
  153. public:
  154. // Value semantics.
  155. constexpr Duration() : rep_hi_(0), rep_lo_(0) {} // zero-length duration
  156. // Copyable.
  157. #if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1910
  158. // Explicitly defining the constexpr copy constructor avoids an MSVC bug.
  159. constexpr Duration(const Duration& d)
  160. : rep_hi_(d.rep_hi_), rep_lo_(d.rep_lo_) {}
  161. #else
  162. constexpr Duration(const Duration& d) = default;
  163. #endif
  164. Duration& operator=(const Duration& d) = default;
  165. // Compound assignment operators.
  166. Duration& operator+=(Duration d);
  167. Duration& operator-=(Duration d);
  168. Duration& operator*=(int64_t r);
  169. Duration& operator*=(double r);
  170. Duration& operator/=(int64_t r);
  171. Duration& operator/=(double r);
  172. Duration& operator%=(Duration rhs);
  173. // Overloads that forward to either the int64_t or double overloads above.
  174. // Integer operands must be representable as int64_t.
  175. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  176. Duration& operator*=(T r) {
  177. int64_t x = r;
  178. return *this *= x;
  179. }
  180. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  181. Duration& operator/=(T r) {
  182. int64_t x = r;
  183. return *this /= x;
  184. }
  185. template <typename T, time_internal::EnableIfFloat<T> = 0>
  186. Duration& operator*=(T r) {
  187. double x = r;
  188. return *this *= x;
  189. }
  190. template <typename T, time_internal::EnableIfFloat<T> = 0>
  191. Duration& operator/=(T r) {
  192. double x = r;
  193. return *this /= x;
  194. }
  195. template <typename H>
  196. friend H AbslHashValue(H h, Duration d) {
  197. return H::combine(std::move(h), d.rep_hi_, d.rep_lo_);
  198. }
  199. private:
  200. friend constexpr int64_t time_internal::GetRepHi(Duration d);
  201. friend constexpr uint32_t time_internal::GetRepLo(Duration d);
  202. friend constexpr Duration time_internal::MakeDuration(int64_t hi,
  203. uint32_t lo);
  204. constexpr Duration(int64_t hi, uint32_t lo) : rep_hi_(hi), rep_lo_(lo) {}
  205. int64_t rep_hi_;
  206. uint32_t rep_lo_;
  207. };
  208. // Relational Operators
  209. constexpr bool operator<(Duration lhs, Duration rhs);
  210. constexpr bool operator>(Duration lhs, Duration rhs) { return rhs < lhs; }
  211. constexpr bool operator>=(Duration lhs, Duration rhs) { return !(lhs < rhs); }
  212. constexpr bool operator<=(Duration lhs, Duration rhs) { return !(rhs < lhs); }
  213. constexpr bool operator==(Duration lhs, Duration rhs);
  214. constexpr bool operator!=(Duration lhs, Duration rhs) { return !(lhs == rhs); }
  215. // Additive Operators
  216. constexpr Duration operator-(Duration d);
  217. inline Duration operator+(Duration lhs, Duration rhs) { return lhs += rhs; }
  218. inline Duration operator-(Duration lhs, Duration rhs) { return lhs -= rhs; }
  219. // Multiplicative Operators
  220. // Integer operands must be representable as int64_t.
  221. template <typename T>
  222. Duration operator*(Duration lhs, T rhs) {
  223. return lhs *= rhs;
  224. }
  225. template <typename T>
  226. Duration operator*(T lhs, Duration rhs) {
  227. return rhs *= lhs;
  228. }
  229. template <typename T>
  230. Duration operator/(Duration lhs, T rhs) {
  231. return lhs /= rhs;
  232. }
  233. inline int64_t operator/(Duration lhs, Duration rhs) {
  234. return time_internal::IDivDuration(true, lhs, rhs,
  235. &lhs); // trunc towards zero
  236. }
  237. inline Duration operator%(Duration lhs, Duration rhs) { return lhs %= rhs; }
  238. // IDivDuration()
  239. //
  240. // Divides a numerator `Duration` by a denominator `Duration`, returning the
  241. // quotient and remainder. The remainder always has the same sign as the
  242. // numerator. The returned quotient and remainder respect the identity:
  243. //
  244. // numerator = denominator * quotient + remainder
  245. //
  246. // Returned quotients are capped to the range of `int64_t`, with the difference
  247. // spilling into the remainder to uphold the above identity. This means that the
  248. // remainder returned could differ from the remainder returned by
  249. // `Duration::operator%` for huge quotients.
  250. //
  251. // See also the notes on `InfiniteDuration()` below regarding the behavior of
  252. // division involving zero and infinite durations.
  253. //
  254. // Example:
  255. //
  256. // constexpr y_absl::Duration a =
  257. // y_absl::Seconds(std::numeric_limits<int64_t>::max()); // big
  258. // constexpr y_absl::Duration b = y_absl::Nanoseconds(1); // small
  259. //
  260. // y_absl::Duration rem = a % b;
  261. // // rem == y_absl::ZeroDuration()
  262. //
  263. // // Here, q would overflow int64_t, so rem accounts for the difference.
  264. // int64_t q = y_absl::IDivDuration(a, b, &rem);
  265. // // q == std::numeric_limits<int64_t>::max(), rem == a - b * q
  266. inline int64_t IDivDuration(Duration num, Duration den, Duration* rem) {
  267. return time_internal::IDivDuration(true, num, den,
  268. rem); // trunc towards zero
  269. }
  270. // FDivDuration()
  271. //
  272. // Divides a `Duration` numerator into a fractional number of units of a
  273. // `Duration` denominator.
  274. //
  275. // See also the notes on `InfiniteDuration()` below regarding the behavior of
  276. // division involving zero and infinite durations.
  277. //
  278. // Example:
  279. //
  280. // double d = y_absl::FDivDuration(y_absl::Milliseconds(1500), y_absl::Seconds(1));
  281. // // d == 1.5
  282. double FDivDuration(Duration num, Duration den);
  283. // ZeroDuration()
  284. //
  285. // Returns a zero-length duration. This function behaves just like the default
  286. // constructor, but the name helps make the semantics clear at call sites.
  287. constexpr Duration ZeroDuration() { return Duration(); }
  288. // AbsDuration()
  289. //
  290. // Returns the absolute value of a duration.
  291. inline Duration AbsDuration(Duration d) {
  292. return (d < ZeroDuration()) ? -d : d;
  293. }
  294. // Trunc()
  295. //
  296. // Truncates a duration (toward zero) to a multiple of a non-zero unit.
  297. //
  298. // Example:
  299. //
  300. // y_absl::Duration d = y_absl::Nanoseconds(123456789);
  301. // y_absl::Duration a = y_absl::Trunc(d, y_absl::Microseconds(1)); // 123456us
  302. Duration Trunc(Duration d, Duration unit);
  303. // Floor()
  304. //
  305. // Floors a duration using the passed duration unit to its largest value not
  306. // greater than the duration.
  307. //
  308. // Example:
  309. //
  310. // y_absl::Duration d = y_absl::Nanoseconds(123456789);
  311. // y_absl::Duration b = y_absl::Floor(d, y_absl::Microseconds(1)); // 123456us
  312. Duration Floor(Duration d, Duration unit);
  313. // Ceil()
  314. //
  315. // Returns the ceiling of a duration using the passed duration unit to its
  316. // smallest value not less than the duration.
  317. //
  318. // Example:
  319. //
  320. // y_absl::Duration d = y_absl::Nanoseconds(123456789);
  321. // y_absl::Duration c = y_absl::Ceil(d, y_absl::Microseconds(1)); // 123457us
  322. Duration Ceil(Duration d, Duration unit);
  323. // InfiniteDuration()
  324. //
  325. // Returns an infinite `Duration`. To get a `Duration` representing negative
  326. // infinity, use `-InfiniteDuration()`.
  327. //
  328. // Duration arithmetic overflows to +/- infinity and saturates. In general,
  329. // arithmetic with `Duration` infinities is similar to IEEE 754 infinities
  330. // except where IEEE 754 NaN would be involved, in which case +/-
  331. // `InfiniteDuration()` is used in place of a "nan" Duration.
  332. //
  333. // Examples:
  334. //
  335. // constexpr y_absl::Duration inf = y_absl::InfiniteDuration();
  336. // const y_absl::Duration d = ... any finite duration ...
  337. //
  338. // inf == inf + inf
  339. // inf == inf + d
  340. // inf == inf - inf
  341. // -inf == d - inf
  342. //
  343. // inf == d * 1e100
  344. // inf == inf / 2
  345. // 0 == d / inf
  346. // INT64_MAX == inf / d
  347. //
  348. // d < inf
  349. // -inf < d
  350. //
  351. // // Division by zero returns infinity, or INT64_MIN/MAX where appropriate.
  352. // inf == d / 0
  353. // INT64_MAX == d / y_absl::ZeroDuration()
  354. //
  355. // The examples involving the `/` operator above also apply to `IDivDuration()`
  356. // and `FDivDuration()`.
  357. constexpr Duration InfiniteDuration();
  358. // Nanoseconds()
  359. // Microseconds()
  360. // Milliseconds()
  361. // Seconds()
  362. // Minutes()
  363. // Hours()
  364. //
  365. // Factory functions for constructing `Duration` values from an integral number
  366. // of the unit indicated by the factory function's name. The number must be
  367. // representable as int64_t.
  368. //
  369. // NOTE: no "Days()" factory function exists because "a day" is ambiguous.
  370. // Civil days are not always 24 hours long, and a 24-hour duration often does
  371. // not correspond with a civil day. If a 24-hour duration is needed, use
  372. // `y_absl::Hours(24)`. If you actually want a civil day, use y_absl::CivilDay
  373. // from civil_time.h.
  374. //
  375. // Example:
  376. //
  377. // y_absl::Duration a = y_absl::Seconds(60);
  378. // y_absl::Duration b = y_absl::Minutes(1); // b == a
  379. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  380. constexpr Duration Nanoseconds(T n) {
  381. return time_internal::FromInt64(n, std::nano{});
  382. }
  383. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  384. constexpr Duration Microseconds(T n) {
  385. return time_internal::FromInt64(n, std::micro{});
  386. }
  387. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  388. constexpr Duration Milliseconds(T n) {
  389. return time_internal::FromInt64(n, std::milli{});
  390. }
  391. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  392. constexpr Duration Seconds(T n) {
  393. return time_internal::FromInt64(n, std::ratio<1>{});
  394. }
  395. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  396. constexpr Duration Minutes(T n) {
  397. return time_internal::FromInt64(n, std::ratio<60>{});
  398. }
  399. template <typename T, time_internal::EnableIfIntegral<T> = 0>
  400. constexpr Duration Hours(T n) {
  401. return time_internal::FromInt64(n, std::ratio<3600>{});
  402. }
  403. // Factory overloads for constructing `Duration` values from a floating-point
  404. // number of the unit indicated by the factory function's name. These functions
  405. // exist for convenience, but they are not as efficient as the integral
  406. // factories, which should be preferred.
  407. //
  408. // Example:
  409. //
  410. // auto a = y_absl::Seconds(1.5); // OK
  411. // auto b = y_absl::Milliseconds(1500); // BETTER
  412. template <typename T, time_internal::EnableIfFloat<T> = 0>
  413. Duration Nanoseconds(T n) {
  414. return n * Nanoseconds(1);
  415. }
  416. template <typename T, time_internal::EnableIfFloat<T> = 0>
  417. Duration Microseconds(T n) {
  418. return n * Microseconds(1);
  419. }
  420. template <typename T, time_internal::EnableIfFloat<T> = 0>
  421. Duration Milliseconds(T n) {
  422. return n * Milliseconds(1);
  423. }
  424. template <typename T, time_internal::EnableIfFloat<T> = 0>
  425. Duration Seconds(T n) {
  426. if (n >= 0) { // Note: `NaN >= 0` is false.
  427. if (n >= static_cast<T>((std::numeric_limits<int64_t>::max)())) {
  428. return InfiniteDuration();
  429. }
  430. return time_internal::MakePosDoubleDuration(n);
  431. } else {
  432. if (std::isnan(n))
  433. return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration();
  434. if (n <= (std::numeric_limits<int64_t>::min)()) return -InfiniteDuration();
  435. return -time_internal::MakePosDoubleDuration(-n);
  436. }
  437. }
  438. template <typename T, time_internal::EnableIfFloat<T> = 0>
  439. Duration Minutes(T n) {
  440. return n * Minutes(1);
  441. }
  442. template <typename T, time_internal::EnableIfFloat<T> = 0>
  443. Duration Hours(T n) {
  444. return n * Hours(1);
  445. }
  446. // ToInt64Nanoseconds()
  447. // ToInt64Microseconds()
  448. // ToInt64Milliseconds()
  449. // ToInt64Seconds()
  450. // ToInt64Minutes()
  451. // ToInt64Hours()
  452. //
  453. // Helper functions that convert a Duration to an integral count of the
  454. // indicated unit. These return the same results as the `IDivDuration()`
  455. // function, though they usually do so more efficiently; see the
  456. // documentation of `IDivDuration()` for details about overflow, etc.
  457. //
  458. // Example:
  459. //
  460. // y_absl::Duration d = y_absl::Milliseconds(1500);
  461. // int64_t isec = y_absl::ToInt64Seconds(d); // isec == 1
  462. Y_ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Nanoseconds(Duration d);
  463. Y_ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Microseconds(Duration d);
  464. Y_ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Milliseconds(Duration d);
  465. Y_ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Seconds(Duration d);
  466. Y_ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Minutes(Duration d);
  467. Y_ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Hours(Duration d);
  468. // ToDoubleNanoSeconds()
  469. // ToDoubleMicroseconds()
  470. // ToDoubleMilliseconds()
  471. // ToDoubleSeconds()
  472. // ToDoubleMinutes()
  473. // ToDoubleHours()
  474. //
  475. // Helper functions that convert a Duration to a floating point count of the
  476. // indicated unit. These functions are shorthand for the `FDivDuration()`
  477. // function above; see its documentation for details about overflow, etc.
  478. //
  479. // Example:
  480. //
  481. // y_absl::Duration d = y_absl::Milliseconds(1500);
  482. // double dsec = y_absl::ToDoubleSeconds(d); // dsec == 1.5
  483. Y_ABSL_ATTRIBUTE_PURE_FUNCTION double ToDoubleNanoseconds(Duration d);
  484. Y_ABSL_ATTRIBUTE_PURE_FUNCTION double ToDoubleMicroseconds(Duration d);
  485. Y_ABSL_ATTRIBUTE_PURE_FUNCTION double ToDoubleMilliseconds(Duration d);
  486. Y_ABSL_ATTRIBUTE_PURE_FUNCTION double ToDoubleSeconds(Duration d);
  487. Y_ABSL_ATTRIBUTE_PURE_FUNCTION double ToDoubleMinutes(Duration d);
  488. Y_ABSL_ATTRIBUTE_PURE_FUNCTION double ToDoubleHours(Duration d);
  489. // FromChrono()
  490. //
  491. // Converts any of the pre-defined std::chrono durations to an y_absl::Duration.
  492. //
  493. // Example:
  494. //
  495. // std::chrono::milliseconds ms(123);
  496. // y_absl::Duration d = y_absl::FromChrono(ms);
  497. constexpr Duration FromChrono(const std::chrono::nanoseconds& d);
  498. constexpr Duration FromChrono(const std::chrono::microseconds& d);
  499. constexpr Duration FromChrono(const std::chrono::milliseconds& d);
  500. constexpr Duration FromChrono(const std::chrono::seconds& d);
  501. constexpr Duration FromChrono(const std::chrono::minutes& d);
  502. constexpr Duration FromChrono(const std::chrono::hours& d);
  503. // ToChronoNanoseconds()
  504. // ToChronoMicroseconds()
  505. // ToChronoMilliseconds()
  506. // ToChronoSeconds()
  507. // ToChronoMinutes()
  508. // ToChronoHours()
  509. //
  510. // Converts an y_absl::Duration to any of the pre-defined std::chrono durations.
  511. // If overflow would occur, the returned value will saturate at the min/max
  512. // chrono duration value instead.
  513. //
  514. // Example:
  515. //
  516. // y_absl::Duration d = y_absl::Microseconds(123);
  517. // auto x = y_absl::ToChronoMicroseconds(d);
  518. // auto y = y_absl::ToChronoNanoseconds(d); // x == y
  519. // auto z = y_absl::ToChronoSeconds(y_absl::InfiniteDuration());
  520. // // z == std::chrono::seconds::max()
  521. std::chrono::nanoseconds ToChronoNanoseconds(Duration d);
  522. std::chrono::microseconds ToChronoMicroseconds(Duration d);
  523. std::chrono::milliseconds ToChronoMilliseconds(Duration d);
  524. std::chrono::seconds ToChronoSeconds(Duration d);
  525. std::chrono::minutes ToChronoMinutes(Duration d);
  526. std::chrono::hours ToChronoHours(Duration d);
  527. // FormatDuration()
  528. //
  529. // Returns a string representing the duration in the form "72h3m0.5s".
  530. // Returns "inf" or "-inf" for +/- `InfiniteDuration()`.
  531. TString FormatDuration(Duration d);
  532. // Output stream operator.
  533. inline std::ostream& operator<<(std::ostream& os, Duration d) {
  534. return os << FormatDuration(d);
  535. }
  536. // ParseDuration()
  537. //
  538. // Parses a duration string consisting of a possibly signed sequence of
  539. // decimal numbers, each with an optional fractional part and a unit
  540. // suffix. The valid suffixes are "ns", "us" "ms", "s", "m", and "h".
  541. // Simple examples include "300ms", "-1.5h", and "2h45m". Parses "0" as
  542. // `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`.
  543. bool ParseDuration(y_absl::string_view dur_string, Duration* d);
  544. // AbslParseFlag()
  545. //
  546. // Parses a command-line flag string representation `text` into a a Duration
  547. // value. Duration flags must be specified in a format that is valid input for
  548. // `y_absl::ParseDuration()`.
  549. bool AbslParseFlag(y_absl::string_view text, Duration* dst, TString* error);
  550. // AbslUnparseFlag()
  551. //
  552. // Unparses a Duration value into a command-line string representation using
  553. // the format specified by `y_absl::ParseDuration()`.
  554. TString AbslUnparseFlag(Duration d);
  555. Y_ABSL_DEPRECATED("Use AbslParseFlag() instead.")
  556. bool ParseFlag(const TString& text, Duration* dst, TString* error);
  557. Y_ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
  558. TString UnparseFlag(Duration d);
  559. // Time
  560. //
  561. // An `y_absl::Time` represents a specific instant in time. Arithmetic operators
  562. // are provided for naturally expressing time calculations. Instances are
  563. // created using `y_absl::Now()` and the `y_absl::From*()` factory functions that
  564. // accept the gamut of other time representations. Formatting and parsing
  565. // functions are provided for conversion to and from strings. `y_absl::Time`
  566. // should be passed by value rather than const reference.
  567. //
  568. // `y_absl::Time` assumes there are 60 seconds in a minute, which means the
  569. // underlying time scales must be "smeared" to eliminate leap seconds.
  570. // See https://developers.google.com/time/smear.
  571. //
  572. // Even though `y_absl::Time` supports a wide range of timestamps, exercise
  573. // caution when using values in the distant past. `y_absl::Time` uses the
  574. // Proleptic Gregorian calendar, which extends the Gregorian calendar backward
  575. // to dates before its introduction in 1582.
  576. // See https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar
  577. // for more information. Use the ICU calendar classes to convert a date in
  578. // some other calendar (http://userguide.icu-project.org/datetime/calendar).
  579. //
  580. // Similarly, standardized time zones are a reasonably recent innovation, with
  581. // the Greenwich prime meridian being established in 1884. The TZ database
  582. // itself does not profess accurate offsets for timestamps prior to 1970. The
  583. // breakdown of future timestamps is subject to the whim of regional
  584. // governments.
  585. //
  586. // The `y_absl::Time` class represents an instant in time as a count of clock
  587. // ticks of some granularity (resolution) from some starting point (epoch).
  588. //
  589. // `y_absl::Time` uses a resolution that is high enough to avoid loss in
  590. // precision, and a range that is wide enough to avoid overflow, when
  591. // converting between tick counts in most Google time scales (i.e., resolution
  592. // of at least one nanosecond, and range +/-100 billion years). Conversions
  593. // between the time scales are performed by truncating (towards negative
  594. // infinity) to the nearest representable point.
  595. //
  596. // Examples:
  597. //
  598. // y_absl::Time t1 = ...;
  599. // y_absl::Time t2 = t1 + y_absl::Minutes(2);
  600. // y_absl::Duration d = t2 - t1; // == y_absl::Minutes(2)
  601. //
  602. class Time {
  603. public:
  604. // Value semantics.
  605. // Returns the Unix epoch. However, those reading your code may not know
  606. // or expect the Unix epoch as the default value, so make your code more
  607. // readable by explicitly initializing all instances before use.
  608. //
  609. // Example:
  610. // y_absl::Time t = y_absl::UnixEpoch();
  611. // y_absl::Time t = y_absl::Now();
  612. // y_absl::Time t = y_absl::TimeFromTimeval(tv);
  613. // y_absl::Time t = y_absl::InfinitePast();
  614. constexpr Time() = default;
  615. // Copyable.
  616. constexpr Time(const Time& t) = default;
  617. Time& operator=(const Time& t) = default;
  618. // Assignment operators.
  619. Time& operator+=(Duration d) {
  620. rep_ += d;
  621. return *this;
  622. }
  623. Time& operator-=(Duration d) {
  624. rep_ -= d;
  625. return *this;
  626. }
  627. // Time::Breakdown
  628. //
  629. // The calendar and wall-clock (aka "civil time") components of an
  630. // `y_absl::Time` in a certain `y_absl::TimeZone`. This struct is not
  631. // intended to represent an instant in time. So, rather than passing
  632. // a `Time::Breakdown` to a function, pass an `y_absl::Time` and an
  633. // `y_absl::TimeZone`.
  634. //
  635. // Deprecated. Use `y_absl::TimeZone::CivilInfo`.
  636. struct
  637. Breakdown {
  638. int64_t year; // year (e.g., 2013)
  639. int month; // month of year [1:12]
  640. int day; // day of month [1:31]
  641. int hour; // hour of day [0:23]
  642. int minute; // minute of hour [0:59]
  643. int second; // second of minute [0:59]
  644. Duration subsecond; // [Seconds(0):Seconds(1)) if finite
  645. int weekday; // 1==Mon, ..., 7=Sun
  646. int yearday; // day of year [1:366]
  647. // Note: The following fields exist for backward compatibility
  648. // with older APIs. Accessing these fields directly is a sign of
  649. // imprudent logic in the calling code. Modern time-related code
  650. // should only access this data indirectly by way of FormatTime().
  651. // These fields are undefined for InfiniteFuture() and InfinitePast().
  652. int offset; // seconds east of UTC
  653. bool is_dst; // is offset non-standard?
  654. const char* zone_abbr; // time-zone abbreviation (e.g., "PST")
  655. };
  656. // Time::In()
  657. //
  658. // Returns the breakdown of this instant in the given TimeZone.
  659. //
  660. // Deprecated. Use `y_absl::TimeZone::At(Time)`.
  661. Breakdown In(TimeZone tz) const;
  662. template <typename H>
  663. friend H AbslHashValue(H h, Time t) {
  664. return H::combine(std::move(h), t.rep_);
  665. }
  666. private:
  667. friend constexpr Time time_internal::FromUnixDuration(Duration d);
  668. friend constexpr Duration time_internal::ToUnixDuration(Time t);
  669. friend constexpr bool operator<(Time lhs, Time rhs);
  670. friend constexpr bool operator==(Time lhs, Time rhs);
  671. friend Duration operator-(Time lhs, Time rhs);
  672. friend constexpr Time UniversalEpoch();
  673. friend constexpr Time InfiniteFuture();
  674. friend constexpr Time InfinitePast();
  675. constexpr explicit Time(Duration rep) : rep_(rep) {}
  676. Duration rep_;
  677. };
  678. // Relational Operators
  679. constexpr bool operator<(Time lhs, Time rhs) { return lhs.rep_ < rhs.rep_; }
  680. constexpr bool operator>(Time lhs, Time rhs) { return rhs < lhs; }
  681. constexpr bool operator>=(Time lhs, Time rhs) { return !(lhs < rhs); }
  682. constexpr bool operator<=(Time lhs, Time rhs) { return !(rhs < lhs); }
  683. constexpr bool operator==(Time lhs, Time rhs) { return lhs.rep_ == rhs.rep_; }
  684. constexpr bool operator!=(Time lhs, Time rhs) { return !(lhs == rhs); }
  685. // Additive Operators
  686. inline Time operator+(Time lhs, Duration rhs) { return lhs += rhs; }
  687. inline Time operator+(Duration lhs, Time rhs) { return rhs += lhs; }
  688. inline Time operator-(Time lhs, Duration rhs) { return lhs -= rhs; }
  689. inline Duration operator-(Time lhs, Time rhs) { return lhs.rep_ - rhs.rep_; }
  690. // UnixEpoch()
  691. //
  692. // Returns the `y_absl::Time` representing "1970-01-01 00:00:00.0 +0000".
  693. constexpr Time UnixEpoch() { return Time(); }
  694. // UniversalEpoch()
  695. //
  696. // Returns the `y_absl::Time` representing "0001-01-01 00:00:00.0 +0000", the
  697. // epoch of the ICU Universal Time Scale.
  698. constexpr Time UniversalEpoch() {
  699. // 719162 is the number of days from 0001-01-01 to 1970-01-01,
  700. // assuming the Gregorian calendar.
  701. return Time(time_internal::MakeDuration(-24 * 719162 * int64_t{3600}, 0U));
  702. }
  703. // InfiniteFuture()
  704. //
  705. // Returns an `y_absl::Time` that is infinitely far in the future.
  706. constexpr Time InfiniteFuture() {
  707. return Time(
  708. time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(), ~0U));
  709. }
  710. // InfinitePast()
  711. //
  712. // Returns an `y_absl::Time` that is infinitely far in the past.
  713. constexpr Time InfinitePast() {
  714. return Time(
  715. time_internal::MakeDuration((std::numeric_limits<int64_t>::min)(), ~0U));
  716. }
  717. // FromUnixNanos()
  718. // FromUnixMicros()
  719. // FromUnixMillis()
  720. // FromUnixSeconds()
  721. // FromTimeT()
  722. // FromUDate()
  723. // FromUniversal()
  724. //
  725. // Creates an `y_absl::Time` from a variety of other representations.
  726. constexpr Time FromUnixNanos(int64_t ns);
  727. constexpr Time FromUnixMicros(int64_t us);
  728. constexpr Time FromUnixMillis(int64_t ms);
  729. constexpr Time FromUnixSeconds(int64_t s);
  730. constexpr Time FromTimeT(time_t t);
  731. Time FromUDate(double udate);
  732. Time FromUniversal(int64_t universal);
  733. // ToUnixNanos()
  734. // ToUnixMicros()
  735. // ToUnixMillis()
  736. // ToUnixSeconds()
  737. // ToTimeT()
  738. // ToUDate()
  739. // ToUniversal()
  740. //
  741. // Converts an `y_absl::Time` to a variety of other representations. Note that
  742. // these operations round down toward negative infinity where necessary to
  743. // adjust to the resolution of the result type. Beware of possible time_t
  744. // over/underflow in ToTime{T,val,spec}() on 32-bit platforms.
  745. int64_t ToUnixNanos(Time t);
  746. int64_t ToUnixMicros(Time t);
  747. int64_t ToUnixMillis(Time t);
  748. int64_t ToUnixSeconds(Time t);
  749. time_t ToTimeT(Time t);
  750. double ToUDate(Time t);
  751. int64_t ToUniversal(Time t);
  752. // DurationFromTimespec()
  753. // DurationFromTimeval()
  754. // ToTimespec()
  755. // ToTimeval()
  756. // TimeFromTimespec()
  757. // TimeFromTimeval()
  758. // ToTimespec()
  759. // ToTimeval()
  760. //
  761. // Some APIs use a timespec or a timeval as a Duration (e.g., nanosleep(2)
  762. // and select(2)), while others use them as a Time (e.g. clock_gettime(2)
  763. // and gettimeofday(2)), so conversion functions are provided for both cases.
  764. // The "to timespec/val" direction is easily handled via overloading, but
  765. // for "from timespec/val" the desired type is part of the function name.
  766. Duration DurationFromTimespec(timespec ts);
  767. Duration DurationFromTimeval(timeval tv);
  768. timespec ToTimespec(Duration d);
  769. timeval ToTimeval(Duration d);
  770. Time TimeFromTimespec(timespec ts);
  771. Time TimeFromTimeval(timeval tv);
  772. timespec ToTimespec(Time t);
  773. timeval ToTimeval(Time t);
  774. // FromChrono()
  775. //
  776. // Converts a std::chrono::system_clock::time_point to an y_absl::Time.
  777. //
  778. // Example:
  779. //
  780. // auto tp = std::chrono::system_clock::from_time_t(123);
  781. // y_absl::Time t = y_absl::FromChrono(tp);
  782. // // t == y_absl::FromTimeT(123)
  783. Time FromChrono(const std::chrono::system_clock::time_point& tp);
  784. // ToChronoTime()
  785. //
  786. // Converts an y_absl::Time to a std::chrono::system_clock::time_point. If
  787. // overflow would occur, the returned value will saturate at the min/max time
  788. // point value instead.
  789. //
  790. // Example:
  791. //
  792. // y_absl::Time t = y_absl::FromTimeT(123);
  793. // auto tp = y_absl::ToChronoTime(t);
  794. // // tp == std::chrono::system_clock::from_time_t(123);
  795. std::chrono::system_clock::time_point ToChronoTime(Time);
  796. // AbslParseFlag()
  797. //
  798. // Parses the command-line flag string representation `text` into a Time value.
  799. // Time flags must be specified in a format that matches y_absl::RFC3339_full.
  800. //
  801. // For example:
  802. //
  803. // --start_time=2016-01-02T03:04:05.678+08:00
  804. //
  805. // Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required.
  806. //
  807. // Additionally, if you'd like to specify a time as a count of
  808. // seconds/milliseconds/etc from the Unix epoch, use an y_absl::Duration flag
  809. // and add that duration to y_absl::UnixEpoch() to get an y_absl::Time.
  810. bool AbslParseFlag(y_absl::string_view text, Time* t, TString* error);
  811. // AbslUnparseFlag()
  812. //
  813. // Unparses a Time value into a command-line string representation using
  814. // the format specified by `y_absl::ParseTime()`.
  815. TString AbslUnparseFlag(Time t);
  816. Y_ABSL_DEPRECATED("Use AbslParseFlag() instead.")
  817. bool ParseFlag(const TString& text, Time* t, TString* error);
  818. Y_ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
  819. TString UnparseFlag(Time t);
  820. // TimeZone
  821. //
  822. // The `y_absl::TimeZone` is an opaque, small, value-type class representing a
  823. // geo-political region within which particular rules are used for converting
  824. // between absolute and civil times (see https://git.io/v59Ly). `y_absl::TimeZone`
  825. // values are named using the TZ identifiers from the IANA Time Zone Database,
  826. // such as "America/Los_Angeles" or "Australia/Sydney". `y_absl::TimeZone` values
  827. // are created from factory functions such as `y_absl::LoadTimeZone()`. Note:
  828. // strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by
  829. // value rather than const reference.
  830. //
  831. // For more on the fundamental concepts of time zones, absolute times, and civil
  832. // times, see https://github.com/google/cctz#fundamental-concepts
  833. //
  834. // Examples:
  835. //
  836. // y_absl::TimeZone utc = y_absl::UTCTimeZone();
  837. // y_absl::TimeZone pst = y_absl::FixedTimeZone(-8 * 60 * 60);
  838. // y_absl::TimeZone loc = y_absl::LocalTimeZone();
  839. // y_absl::TimeZone lax;
  840. // if (!y_absl::LoadTimeZone("America/Los_Angeles", &lax)) {
  841. // // handle error case
  842. // }
  843. //
  844. // See also:
  845. // - https://github.com/google/cctz
  846. // - https://www.iana.org/time-zones
  847. // - https://en.wikipedia.org/wiki/Zoneinfo
  848. class TimeZone {
  849. public:
  850. explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {}
  851. TimeZone() = default; // UTC, but prefer UTCTimeZone() to be explicit.
  852. // Copyable.
  853. TimeZone(const TimeZone&) = default;
  854. TimeZone& operator=(const TimeZone&) = default;
  855. explicit operator time_internal::cctz::time_zone() const { return cz_; }
  856. TString name() const { return cz_.name(); }
  857. // TimeZone::CivilInfo
  858. //
  859. // Information about the civil time corresponding to an absolute time.
  860. // This struct is not intended to represent an instant in time. So, rather
  861. // than passing a `TimeZone::CivilInfo` to a function, pass an `y_absl::Time`
  862. // and an `y_absl::TimeZone`.
  863. struct CivilInfo {
  864. CivilSecond cs;
  865. Duration subsecond;
  866. // Note: The following fields exist for backward compatibility
  867. // with older APIs. Accessing these fields directly is a sign of
  868. // imprudent logic in the calling code. Modern time-related code
  869. // should only access this data indirectly by way of FormatTime().
  870. // These fields are undefined for InfiniteFuture() and InfinitePast().
  871. int offset; // seconds east of UTC
  872. bool is_dst; // is offset non-standard?
  873. const char* zone_abbr; // time-zone abbreviation (e.g., "PST")
  874. };
  875. // TimeZone::At(Time)
  876. //
  877. // Returns the civil time for this TimeZone at a certain `y_absl::Time`.
  878. // If the input time is infinite, the output civil second will be set to
  879. // CivilSecond::max() or min(), and the subsecond will be infinite.
  880. //
  881. // Example:
  882. //
  883. // const auto epoch = lax.At(y_absl::UnixEpoch());
  884. // // epoch.cs == 1969-12-31 16:00:00
  885. // // epoch.subsecond == y_absl::ZeroDuration()
  886. // // epoch.offset == -28800
  887. // // epoch.is_dst == false
  888. // // epoch.abbr == "PST"
  889. CivilInfo At(Time t) const;
  890. // TimeZone::TimeInfo
  891. //
  892. // Information about the absolute times corresponding to a civil time.
  893. // (Subseconds must be handled separately.)
  894. //
  895. // It is possible for a caller to pass a civil-time value that does
  896. // not represent an actual or unique instant in time (due to a shift
  897. // in UTC offset in the TimeZone, which results in a discontinuity in
  898. // the civil-time components). For example, a daylight-saving-time
  899. // transition skips or repeats civil times---in the United States,
  900. // March 13, 2011 02:15 never occurred, while November 6, 2011 01:15
  901. // occurred twice---so requests for such times are not well-defined.
  902. // To account for these possibilities, `y_absl::TimeZone::TimeInfo` is
  903. // richer than just a single `y_absl::Time`.
  904. struct TimeInfo {
  905. enum CivilKind {
  906. UNIQUE, // the civil time was singular (pre == trans == post)
  907. SKIPPED, // the civil time did not exist (pre >= trans > post)
  908. REPEATED, // the civil time was ambiguous (pre < trans <= post)
  909. } kind;
  910. Time pre; // time calculated using the pre-transition offset
  911. Time trans; // when the civil-time discontinuity occurred
  912. Time post; // time calculated using the post-transition offset
  913. };
  914. // TimeZone::At(CivilSecond)
  915. //
  916. // Returns an `y_absl::TimeInfo` containing the absolute time(s) for this
  917. // TimeZone at an `y_absl::CivilSecond`. When the civil time is skipped or
  918. // repeated, returns times calculated using the pre-transition and post-
  919. // transition UTC offsets, plus the transition time itself.
  920. //
  921. // Examples:
  922. //
  923. // // A unique civil time
  924. // const auto jan01 = lax.At(y_absl::CivilSecond(2011, 1, 1, 0, 0, 0));
  925. // // jan01.kind == TimeZone::TimeInfo::UNIQUE
  926. // // jan01.pre is 2011-01-01 00:00:00 -0800
  927. // // jan01.trans is 2011-01-01 00:00:00 -0800
  928. // // jan01.post is 2011-01-01 00:00:00 -0800
  929. //
  930. // // A Spring DST transition, when there is a gap in civil time
  931. // const auto mar13 = lax.At(y_absl::CivilSecond(2011, 3, 13, 2, 15, 0));
  932. // // mar13.kind == TimeZone::TimeInfo::SKIPPED
  933. // // mar13.pre is 2011-03-13 03:15:00 -0700
  934. // // mar13.trans is 2011-03-13 03:00:00 -0700
  935. // // mar13.post is 2011-03-13 01:15:00 -0800
  936. //
  937. // // A Fall DST transition, when civil times are repeated
  938. // const auto nov06 = lax.At(y_absl::CivilSecond(2011, 11, 6, 1, 15, 0));
  939. // // nov06.kind == TimeZone::TimeInfo::REPEATED
  940. // // nov06.pre is 2011-11-06 01:15:00 -0700
  941. // // nov06.trans is 2011-11-06 01:00:00 -0800
  942. // // nov06.post is 2011-11-06 01:15:00 -0800
  943. TimeInfo At(CivilSecond ct) const;
  944. // TimeZone::NextTransition()
  945. // TimeZone::PrevTransition()
  946. //
  947. // Finds the time of the next/previous offset change in this time zone.
  948. //
  949. // By definition, `NextTransition(t, &trans)` returns false when `t` is
  950. // `InfiniteFuture()`, and `PrevTransition(t, &trans)` returns false
  951. // when `t` is `InfinitePast()`. If the zone has no transitions, the
  952. // result will also be false no matter what the argument.
  953. //
  954. // Otherwise, when `t` is `InfinitePast()`, `NextTransition(t, &trans)`
  955. // returns true and sets `trans` to the first recorded transition. Chains
  956. // of calls to `NextTransition()/PrevTransition()` will eventually return
  957. // false, but it is unspecified exactly when `NextTransition(t, &trans)`
  958. // jumps to false, or what time is set by `PrevTransition(t, &trans)` for
  959. // a very distant `t`.
  960. //
  961. // Note: Enumeration of time-zone transitions is for informational purposes
  962. // only. Modern time-related code should not care about when offset changes
  963. // occur.
  964. //
  965. // Example:
  966. // y_absl::TimeZone nyc;
  967. // if (!y_absl::LoadTimeZone("America/New_York", &nyc)) { ... }
  968. // const auto now = y_absl::Now();
  969. // auto t = y_absl::InfinitePast();
  970. // y_absl::TimeZone::CivilTransition trans;
  971. // while (t <= now && nyc.NextTransition(t, &trans)) {
  972. // // transition: trans.from -> trans.to
  973. // t = nyc.At(trans.to).trans;
  974. // }
  975. struct CivilTransition {
  976. CivilSecond from; // the civil time we jump from
  977. CivilSecond to; // the civil time we jump to
  978. };
  979. bool NextTransition(Time t, CivilTransition* trans) const;
  980. bool PrevTransition(Time t, CivilTransition* trans) const;
  981. template <typename H>
  982. friend H AbslHashValue(H h, TimeZone tz) {
  983. return H::combine(std::move(h), tz.cz_);
  984. }
  985. private:
  986. friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; }
  987. friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; }
  988. friend std::ostream& operator<<(std::ostream& os, TimeZone tz) {
  989. return os << tz.name();
  990. }
  991. time_internal::cctz::time_zone cz_;
  992. };
  993. // LoadTimeZone()
  994. //
  995. // Loads the named zone. May perform I/O on the initial load of the named
  996. // zone. If the name is invalid, or some other kind of error occurs, returns
  997. // `false` and `*tz` is set to the UTC time zone.
  998. inline bool LoadTimeZone(y_absl::string_view name, TimeZone* tz) {
  999. if (name == "localtime") {
  1000. *tz = TimeZone(time_internal::cctz::local_time_zone());
  1001. return true;
  1002. }
  1003. time_internal::cctz::time_zone cz;
  1004. const bool b = time_internal::cctz::load_time_zone(TString(name), &cz);
  1005. *tz = TimeZone(cz);
  1006. return b;
  1007. }
  1008. // FixedTimeZone()
  1009. //
  1010. // Returns a TimeZone that is a fixed offset (seconds east) from UTC.
  1011. // Note: If the absolute value of the offset is greater than 24 hours
  1012. // you'll get UTC (i.e., no offset) instead.
  1013. inline TimeZone FixedTimeZone(int seconds) {
  1014. return TimeZone(
  1015. time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds)));
  1016. }
  1017. // UTCTimeZone()
  1018. //
  1019. // Convenience method returning the UTC time zone.
  1020. inline TimeZone UTCTimeZone() {
  1021. return TimeZone(time_internal::cctz::utc_time_zone());
  1022. }
  1023. // LocalTimeZone()
  1024. //
  1025. // Convenience method returning the local time zone, or UTC if there is
  1026. // no configured local zone. Warning: Be wary of using LocalTimeZone(),
  1027. // and particularly so in a server process, as the zone configured for the
  1028. // local machine should be irrelevant. Prefer an explicit zone name.
  1029. inline TimeZone LocalTimeZone() {
  1030. return TimeZone(time_internal::cctz::local_time_zone());
  1031. }
  1032. // ToCivilSecond()
  1033. // ToCivilMinute()
  1034. // ToCivilHour()
  1035. // ToCivilDay()
  1036. // ToCivilMonth()
  1037. // ToCivilYear()
  1038. //
  1039. // Helpers for TimeZone::At(Time) to return particularly aligned civil times.
  1040. //
  1041. // Example:
  1042. //
  1043. // y_absl::Time t = ...;
  1044. // y_absl::TimeZone tz = ...;
  1045. // const auto cd = y_absl::ToCivilDay(t, tz);
  1046. inline CivilSecond ToCivilSecond(Time t, TimeZone tz) {
  1047. return tz.At(t).cs; // already a CivilSecond
  1048. }
  1049. inline CivilMinute ToCivilMinute(Time t, TimeZone tz) {
  1050. return CivilMinute(tz.At(t).cs);
  1051. }
  1052. inline CivilHour ToCivilHour(Time t, TimeZone tz) {
  1053. return CivilHour(tz.At(t).cs);
  1054. }
  1055. inline CivilDay ToCivilDay(Time t, TimeZone tz) {
  1056. return CivilDay(tz.At(t).cs);
  1057. }
  1058. inline CivilMonth ToCivilMonth(Time t, TimeZone tz) {
  1059. return CivilMonth(tz.At(t).cs);
  1060. }
  1061. inline CivilYear ToCivilYear(Time t, TimeZone tz) {
  1062. return CivilYear(tz.At(t).cs);
  1063. }
  1064. // FromCivil()
  1065. //
  1066. // Helper for TimeZone::At(CivilSecond) that provides "order-preserving
  1067. // semantics." If the civil time maps to a unique time, that time is
  1068. // returned. If the civil time is repeated in the given time zone, the
  1069. // time using the pre-transition offset is returned. Otherwise, the
  1070. // civil time is skipped in the given time zone, and the transition time
  1071. // is returned. This means that for any two civil times, ct1 and ct2,
  1072. // (ct1 < ct2) => (FromCivil(ct1) <= FromCivil(ct2)), the equal case
  1073. // being when two non-existent civil times map to the same transition time.
  1074. //
  1075. // Note: Accepts civil times of any alignment.
  1076. inline Time FromCivil(CivilSecond ct, TimeZone tz) {
  1077. const auto ti = tz.At(ct);
  1078. if (ti.kind == TimeZone::TimeInfo::SKIPPED) return ti.trans;
  1079. return ti.pre;
  1080. }
  1081. // TimeConversion
  1082. //
  1083. // An `y_absl::TimeConversion` represents the conversion of year, month, day,
  1084. // hour, minute, and second values (i.e., a civil time), in a particular
  1085. // `y_absl::TimeZone`, to a time instant (an absolute time), as returned by
  1086. // `y_absl::ConvertDateTime()`. Legacy version of `y_absl::TimeZone::TimeInfo`.
  1087. //
  1088. // Deprecated. Use `y_absl::TimeZone::TimeInfo`.
  1089. struct
  1090. TimeConversion {
  1091. Time pre; // time calculated using the pre-transition offset
  1092. Time trans; // when the civil-time discontinuity occurred
  1093. Time post; // time calculated using the post-transition offset
  1094. enum Kind {
  1095. UNIQUE, // the civil time was singular (pre == trans == post)
  1096. SKIPPED, // the civil time did not exist
  1097. REPEATED, // the civil time was ambiguous
  1098. };
  1099. Kind kind;
  1100. bool normalized; // input values were outside their valid ranges
  1101. };
  1102. // ConvertDateTime()
  1103. //
  1104. // Legacy version of `y_absl::TimeZone::At(y_absl::CivilSecond)` that takes
  1105. // the civil time as six, separate values (YMDHMS).
  1106. //
  1107. // The input month, day, hour, minute, and second values can be outside
  1108. // of their valid ranges, in which case they will be "normalized" during
  1109. // the conversion.
  1110. //
  1111. // Example:
  1112. //
  1113. // // "October 32" normalizes to "November 1".
  1114. // y_absl::TimeConversion tc =
  1115. // y_absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, lax);
  1116. // // tc.kind == TimeConversion::UNIQUE && tc.normalized == true
  1117. // // y_absl::ToCivilDay(tc.pre, tz).month() == 11
  1118. // // y_absl::ToCivilDay(tc.pre, tz).day() == 1
  1119. //
  1120. // Deprecated. Use `y_absl::TimeZone::At(CivilSecond)`.
  1121. TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour,
  1122. int min, int sec, TimeZone tz);
  1123. // FromDateTime()
  1124. //
  1125. // A convenience wrapper for `y_absl::ConvertDateTime()` that simply returns
  1126. // the "pre" `y_absl::Time`. That is, the unique result, or the instant that
  1127. // is correct using the pre-transition offset (as if the transition never
  1128. // happened).
  1129. //
  1130. // Example:
  1131. //
  1132. // y_absl::Time t = y_absl::FromDateTime(2017, 9, 26, 9, 30, 0, lax);
  1133. // // t = 2017-09-26 09:30:00 -0700
  1134. //
  1135. // Deprecated. Use `y_absl::FromCivil(CivilSecond, TimeZone)`. Note that the
  1136. // behavior of `FromCivil()` differs from `FromDateTime()` for skipped civil
  1137. // times. If you care about that see `y_absl::TimeZone::At(y_absl::CivilSecond)`.
  1138. inline Time FromDateTime(int64_t year, int mon, int day, int hour,
  1139. int min, int sec, TimeZone tz) {
  1140. return ConvertDateTime(year, mon, day, hour, min, sec, tz).pre;
  1141. }
  1142. // FromTM()
  1143. //
  1144. // Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and
  1145. // `tm_sec` fields to an `y_absl::Time` using the given time zone. See ctime(3)
  1146. // for a description of the expected values of the tm fields. If the civil time
  1147. // is unique (see `y_absl::TimeZone::At(y_absl::CivilSecond)` above), the matching
  1148. // time instant is returned. Otherwise, the `tm_isdst` field is consulted to
  1149. // choose between the possible results. For a repeated civil time, `tm_isdst !=
  1150. // 0` returns the matching DST instant, while `tm_isdst == 0` returns the
  1151. // matching non-DST instant. For a skipped civil time there is no matching
  1152. // instant, so `tm_isdst != 0` returns the DST instant, and `tm_isdst == 0`
  1153. // returns the non-DST instant, that would have matched if the transition never
  1154. // happened.
  1155. Time FromTM(const struct tm& tm, TimeZone tz);
  1156. // ToTM()
  1157. //
  1158. // Converts the given `y_absl::Time` to a struct tm using the given time zone.
  1159. // See ctime(3) for a description of the values of the tm fields.
  1160. struct tm ToTM(Time t, TimeZone tz);
  1161. // RFC3339_full
  1162. // RFC3339_sec
  1163. //
  1164. // FormatTime()/ParseTime() format specifiers for RFC3339 date/time strings,
  1165. // with trailing zeros trimmed or with fractional seconds omitted altogether.
  1166. //
  1167. // Note that RFC3339_sec[] matches an ISO 8601 extended format for date and
  1168. // time with UTC offset. Also note the use of "%Y": RFC3339 mandates that
  1169. // years have exactly four digits, but we allow them to take their natural
  1170. // width.
  1171. Y_ABSL_DLL extern const char RFC3339_full[]; // %Y-%m-%d%ET%H:%M:%E*S%Ez
  1172. Y_ABSL_DLL extern const char RFC3339_sec[]; // %Y-%m-%d%ET%H:%M:%S%Ez
  1173. // RFC1123_full
  1174. // RFC1123_no_wday
  1175. //
  1176. // FormatTime()/ParseTime() format specifiers for RFC1123 date/time strings.
  1177. Y_ABSL_DLL extern const char RFC1123_full[]; // %a, %d %b %E4Y %H:%M:%S %z
  1178. Y_ABSL_DLL extern const char RFC1123_no_wday[]; // %d %b %E4Y %H:%M:%S %z
  1179. // FormatTime()
  1180. //
  1181. // Formats the given `y_absl::Time` in the `y_absl::TimeZone` according to the
  1182. // provided format string. Uses strftime()-like formatting options, with
  1183. // the following extensions:
  1184. //
  1185. // - %Ez - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm)
  1186. // - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss)
  1187. // - %E#S - Seconds with # digits of fractional precision
  1188. // - %E*S - Seconds with full fractional precision (a literal '*')
  1189. // - %E#f - Fractional seconds with # digits of precision
  1190. // - %E*f - Fractional seconds with full precision (a literal '*')
  1191. // - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999)
  1192. // - %ET - The RFC3339 "date-time" separator "T"
  1193. //
  1194. // Note that %E0S behaves like %S, and %E0f produces no characters. In
  1195. // contrast %E*f always produces at least one digit, which may be '0'.
  1196. //
  1197. // Note that %Y produces as many characters as it takes to fully render the
  1198. // year. A year outside of [-999:9999] when formatted with %E4Y will produce
  1199. // more than four characters, just like %Y.
  1200. //
  1201. // We recommend that format strings include the UTC offset (%z, %Ez, or %E*z)
  1202. // so that the result uniquely identifies a time instant.
  1203. //
  1204. // Example:
  1205. //
  1206. // y_absl::CivilSecond cs(2013, 1, 2, 3, 4, 5);
  1207. // y_absl::Time t = y_absl::FromCivil(cs, lax);
  1208. // TString f = y_absl::FormatTime("%H:%M:%S", t, lax); // "03:04:05"
  1209. // f = y_absl::FormatTime("%H:%M:%E3S", t, lax); // "03:04:05.000"
  1210. //
  1211. // Note: If the given `y_absl::Time` is `y_absl::InfiniteFuture()`, the returned
  1212. // string will be exactly "infinite-future". If the given `y_absl::Time` is
  1213. // `y_absl::InfinitePast()`, the returned string will be exactly "infinite-past".
  1214. // In both cases the given format string and `y_absl::TimeZone` are ignored.
  1215. //
  1216. TString FormatTime(y_absl::string_view format, Time t, TimeZone tz);
  1217. // Convenience functions that format the given time using the RFC3339_full
  1218. // format. The first overload uses the provided TimeZone, while the second
  1219. // uses LocalTimeZone().
  1220. TString FormatTime(Time t, TimeZone tz);
  1221. TString FormatTime(Time t);
  1222. // Output stream operator.
  1223. inline std::ostream& operator<<(std::ostream& os, Time t) {
  1224. return os << FormatTime(t);
  1225. }
  1226. // ParseTime()
  1227. //
  1228. // Parses an input string according to the provided format string and
  1229. // returns the corresponding `y_absl::Time`. Uses strftime()-like formatting
  1230. // options, with the same extensions as FormatTime(), but with the
  1231. // exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f. %Ez
  1232. // and %E*z also accept the same inputs, which (along with %z) includes
  1233. // 'z' and 'Z' as synonyms for +00:00. %ET accepts either 'T' or 't'.
  1234. //
  1235. // %Y consumes as many numeric characters as it can, so the matching data
  1236. // should always be terminated with a non-numeric. %E4Y always consumes
  1237. // exactly four characters, including any sign.
  1238. //
  1239. // Unspecified fields are taken from the default date and time of ...
  1240. //
  1241. // "1970-01-01 00:00:00.0 +0000"
  1242. //
  1243. // For example, parsing a string of "15:45" (%H:%M) will return an y_absl::Time
  1244. // that represents "1970-01-01 15:45:00.0 +0000".
  1245. //
  1246. // Note that since ParseTime() returns time instants, it makes the most sense
  1247. // to parse fully-specified date/time strings that include a UTC offset (%z,
  1248. // %Ez, or %E*z).
  1249. //
  1250. // Note also that `y_absl::ParseTime()` only heeds the fields year, month, day,
  1251. // hour, minute, (fractional) second, and UTC offset. Other fields, like
  1252. // weekday (%a or %A), while parsed for syntactic validity, are ignored
  1253. // in the conversion.
  1254. //
  1255. // Date and time fields that are out-of-range will be treated as errors
  1256. // rather than normalizing them like `y_absl::CivilSecond` does. For example,
  1257. // it is an error to parse the date "Oct 32, 2013" because 32 is out of range.
  1258. //
  1259. // A leap second of ":60" is normalized to ":00" of the following minute
  1260. // with fractional seconds discarded. The following table shows how the
  1261. // given seconds and subseconds will be parsed:
  1262. //
  1263. // "59.x" -> 59.x // exact
  1264. // "60.x" -> 00.0 // normalized
  1265. // "00.x" -> 00.x // exact
  1266. //
  1267. // Errors are indicated by returning false and assigning an error message
  1268. // to the "err" out param if it is non-null.
  1269. //
  1270. // Note: If the input string is exactly "infinite-future", the returned
  1271. // `y_absl::Time` will be `y_absl::InfiniteFuture()` and `true` will be returned.
  1272. // If the input string is "infinite-past", the returned `y_absl::Time` will be
  1273. // `y_absl::InfinitePast()` and `true` will be returned.
  1274. //
  1275. bool ParseTime(y_absl::string_view format, y_absl::string_view input, Time* time,
  1276. TString* err);
  1277. // Like ParseTime() above, but if the format string does not contain a UTC
  1278. // offset specification (%z/%Ez/%E*z) then the input is interpreted in the
  1279. // given TimeZone. This means that the input, by itself, does not identify a
  1280. // unique instant. Being time-zone dependent, it also admits the possibility
  1281. // of ambiguity or non-existence, in which case the "pre" time (as defined
  1282. // by TimeZone::TimeInfo) is returned. For these reasons we recommend that
  1283. // all date/time strings include a UTC offset so they're context independent.
  1284. bool ParseTime(y_absl::string_view format, y_absl::string_view input, TimeZone tz,
  1285. Time* time, TString* err);
  1286. // ============================================================================
  1287. // Implementation Details Follow
  1288. // ============================================================================
  1289. namespace time_internal {
  1290. // Creates a Duration with a given representation.
  1291. // REQUIRES: hi,lo is a valid representation of a Duration as specified
  1292. // in time/duration.cc.
  1293. constexpr Duration MakeDuration(int64_t hi, uint32_t lo = 0) {
  1294. return Duration(hi, lo);
  1295. }
  1296. constexpr Duration MakeDuration(int64_t hi, int64_t lo) {
  1297. return MakeDuration(hi, static_cast<uint32_t>(lo));
  1298. }
  1299. // Make a Duration value from a floating-point number, as long as that number
  1300. // is in the range [ 0 .. numeric_limits<int64_t>::max ), that is, as long as
  1301. // it's positive and can be converted to int64_t without risk of UB.
  1302. inline Duration MakePosDoubleDuration(double n) {
  1303. const int64_t int_secs = static_cast<int64_t>(n);
  1304. const uint32_t ticks = static_cast<uint32_t>(
  1305. std::round((n - static_cast<double>(int_secs)) * kTicksPerSecond));
  1306. return ticks < kTicksPerSecond
  1307. ? MakeDuration(int_secs, ticks)
  1308. : MakeDuration(int_secs + 1, ticks - kTicksPerSecond);
  1309. }
  1310. // Creates a normalized Duration from an almost-normalized (sec,ticks)
  1311. // pair. sec may be positive or negative. ticks must be in the range
  1312. // -kTicksPerSecond < *ticks < kTicksPerSecond. If ticks is negative it
  1313. // will be normalized to a positive value in the resulting Duration.
  1314. constexpr Duration MakeNormalizedDuration(int64_t sec, int64_t ticks) {
  1315. return (ticks < 0) ? MakeDuration(sec - 1, ticks + kTicksPerSecond)
  1316. : MakeDuration(sec, ticks);
  1317. }
  1318. // Provide access to the Duration representation.
  1319. constexpr int64_t GetRepHi(Duration d) { return d.rep_hi_; }
  1320. constexpr uint32_t GetRepLo(Duration d) { return d.rep_lo_; }
  1321. // Returns true iff d is positive or negative infinity.
  1322. constexpr bool IsInfiniteDuration(Duration d) { return GetRepLo(d) == ~0U; }
  1323. // Returns an infinite Duration with the opposite sign.
  1324. // REQUIRES: IsInfiniteDuration(d)
  1325. constexpr Duration OppositeInfinity(Duration d) {
  1326. return GetRepHi(d) < 0
  1327. ? MakeDuration((std::numeric_limits<int64_t>::max)(), ~0U)
  1328. : MakeDuration((std::numeric_limits<int64_t>::min)(), ~0U);
  1329. }
  1330. // Returns (-n)-1 (equivalently -(n+1)) without avoidable overflow.
  1331. constexpr int64_t NegateAndSubtractOne(int64_t n) {
  1332. // Note: Good compilers will optimize this expression to ~n when using
  1333. // a two's-complement representation (which is required for int64_t).
  1334. return (n < 0) ? -(n + 1) : (-n) - 1;
  1335. }
  1336. // Map between a Time and a Duration since the Unix epoch. Note that these
  1337. // functions depend on the above mentioned choice of the Unix epoch for the
  1338. // Time representation (and both need to be Time friends). Without this
  1339. // knowledge, we would need to add-in/subtract-out UnixEpoch() respectively.
  1340. constexpr Time FromUnixDuration(Duration d) { return Time(d); }
  1341. constexpr Duration ToUnixDuration(Time t) { return t.rep_; }
  1342. template <std::intmax_t N>
  1343. constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) {
  1344. static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  1345. // Subsecond ratios cannot overflow.
  1346. return MakeNormalizedDuration(
  1347. v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
  1348. }
  1349. constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
  1350. return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
  1351. v >= (std::numeric_limits<int64_t>::min)() / 60)
  1352. ? MakeDuration(v * 60)
  1353. : v > 0 ? InfiniteDuration() : -InfiniteDuration();
  1354. }
  1355. constexpr Duration FromInt64(int64_t v, std::ratio<3600>) {
  1356. return (v <= (std::numeric_limits<int64_t>::max)() / 3600 &&
  1357. v >= (std::numeric_limits<int64_t>::min)() / 3600)
  1358. ? MakeDuration(v * 3600)
  1359. : v > 0 ? InfiniteDuration() : -InfiniteDuration();
  1360. }
  1361. // IsValidRep64<T>(0) is true if the expression `int64_t{std::declval<T>()}` is
  1362. // valid. That is, if a T can be assigned to an int64_t without narrowing.
  1363. template <typename T>
  1364. constexpr auto IsValidRep64(int) -> decltype(int64_t{std::declval<T>()} == 0) {
  1365. return true;
  1366. }
  1367. template <typename T>
  1368. constexpr auto IsValidRep64(char) -> bool {
  1369. return false;
  1370. }
  1371. // Converts a std::chrono::duration to an y_absl::Duration.
  1372. template <typename Rep, typename Period>
  1373. constexpr Duration FromChrono(const std::chrono::duration<Rep, Period>& d) {
  1374. static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
  1375. return FromInt64(int64_t{d.count()}, Period{});
  1376. }
  1377. template <typename Ratio>
  1378. int64_t ToInt64(Duration d, Ratio) {
  1379. // Note: This may be used on MSVC, which may have a system_clock period of
  1380. // std::ratio<1, 10 * 1000 * 1000>
  1381. return ToInt64Seconds(d * Ratio::den / Ratio::num);
  1382. }
  1383. // Fastpath implementations for the 6 common duration units.
  1384. inline int64_t ToInt64(Duration d, std::nano) {
  1385. return ToInt64Nanoseconds(d);
  1386. }
  1387. inline int64_t ToInt64(Duration d, std::micro) {
  1388. return ToInt64Microseconds(d);
  1389. }
  1390. inline int64_t ToInt64(Duration d, std::milli) {
  1391. return ToInt64Milliseconds(d);
  1392. }
  1393. inline int64_t ToInt64(Duration d, std::ratio<1>) {
  1394. return ToInt64Seconds(d);
  1395. }
  1396. inline int64_t ToInt64(Duration d, std::ratio<60>) {
  1397. return ToInt64Minutes(d);
  1398. }
  1399. inline int64_t ToInt64(Duration d, std::ratio<3600>) {
  1400. return ToInt64Hours(d);
  1401. }
  1402. // Converts an y_absl::Duration to a chrono duration of type T.
  1403. template <typename T>
  1404. T ToChronoDuration(Duration d) {
  1405. using Rep = typename T::rep;
  1406. using Period = typename T::period;
  1407. static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
  1408. if (time_internal::IsInfiniteDuration(d))
  1409. return d < ZeroDuration() ? (T::min)() : (T::max)();
  1410. const auto v = ToInt64(d, Period{});
  1411. if (v > (std::numeric_limits<Rep>::max)()) return (T::max)();
  1412. if (v < (std::numeric_limits<Rep>::min)()) return (T::min)();
  1413. return T{v};
  1414. }
  1415. } // namespace time_internal
  1416. constexpr bool operator<(Duration lhs, Duration rhs) {
  1417. return time_internal::GetRepHi(lhs) != time_internal::GetRepHi(rhs)
  1418. ? time_internal::GetRepHi(lhs) < time_internal::GetRepHi(rhs)
  1419. : time_internal::GetRepHi(lhs) == (std::numeric_limits<int64_t>::min)()
  1420. ? time_internal::GetRepLo(lhs) + 1 <
  1421. time_internal::GetRepLo(rhs) + 1
  1422. : time_internal::GetRepLo(lhs) < time_internal::GetRepLo(rhs);
  1423. }
  1424. constexpr bool operator==(Duration lhs, Duration rhs) {
  1425. return time_internal::GetRepHi(lhs) == time_internal::GetRepHi(rhs) &&
  1426. time_internal::GetRepLo(lhs) == time_internal::GetRepLo(rhs);
  1427. }
  1428. constexpr Duration operator-(Duration d) {
  1429. // This is a little interesting because of the special cases.
  1430. //
  1431. // If rep_lo_ is zero, we have it easy; it's safe to negate rep_hi_, we're
  1432. // dealing with an integral number of seconds, and the only special case is
  1433. // the maximum negative finite duration, which can't be negated.
  1434. //
  1435. // Infinities stay infinite, and just change direction.
  1436. //
  1437. // Finally we're in the case where rep_lo_ is non-zero, and we can borrow
  1438. // a second's worth of ticks and avoid overflow (as negating int64_t-min + 1
  1439. // is safe).
  1440. return time_internal::GetRepLo(d) == 0
  1441. ? time_internal::GetRepHi(d) ==
  1442. (std::numeric_limits<int64_t>::min)()
  1443. ? InfiniteDuration()
  1444. : time_internal::MakeDuration(-time_internal::GetRepHi(d))
  1445. : time_internal::IsInfiniteDuration(d)
  1446. ? time_internal::OppositeInfinity(d)
  1447. : time_internal::MakeDuration(
  1448. time_internal::NegateAndSubtractOne(
  1449. time_internal::GetRepHi(d)),
  1450. time_internal::kTicksPerSecond -
  1451. time_internal::GetRepLo(d));
  1452. }
  1453. constexpr Duration InfiniteDuration() {
  1454. return time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
  1455. ~0U);
  1456. }
  1457. constexpr Duration FromChrono(const std::chrono::nanoseconds& d) {
  1458. return time_internal::FromChrono(d);
  1459. }
  1460. constexpr Duration FromChrono(const std::chrono::microseconds& d) {
  1461. return time_internal::FromChrono(d);
  1462. }
  1463. constexpr Duration FromChrono(const std::chrono::milliseconds& d) {
  1464. return time_internal::FromChrono(d);
  1465. }
  1466. constexpr Duration FromChrono(const std::chrono::seconds& d) {
  1467. return time_internal::FromChrono(d);
  1468. }
  1469. constexpr Duration FromChrono(const std::chrono::minutes& d) {
  1470. return time_internal::FromChrono(d);
  1471. }
  1472. constexpr Duration FromChrono(const std::chrono::hours& d) {
  1473. return time_internal::FromChrono(d);
  1474. }
  1475. constexpr Time FromUnixNanos(int64_t ns) {
  1476. return time_internal::FromUnixDuration(Nanoseconds(ns));
  1477. }
  1478. constexpr Time FromUnixMicros(int64_t us) {
  1479. return time_internal::FromUnixDuration(Microseconds(us));
  1480. }
  1481. constexpr Time FromUnixMillis(int64_t ms) {
  1482. return time_internal::FromUnixDuration(Milliseconds(ms));
  1483. }
  1484. constexpr Time FromUnixSeconds(int64_t s) {
  1485. return time_internal::FromUnixDuration(Seconds(s));
  1486. }
  1487. constexpr Time FromTimeT(time_t t) {
  1488. return time_internal::FromUnixDuration(Seconds(t));
  1489. }
  1490. Y_ABSL_NAMESPACE_END
  1491. } // namespace y_absl
  1492. #endif // Y_ABSL_TIME_TIME_H_