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