Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-12-16 09:41:07

0001 // Copyright 2017 The Abseil Authors.
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //      https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 //
0015 // -----------------------------------------------------------------------------
0016 // File: time.h
0017 // -----------------------------------------------------------------------------
0018 //
0019 // This header file defines abstractions for computing with absolute points
0020 // in time, durations of time, and formatting and parsing time within a given
0021 // time zone. The following abstractions are defined:
0022 //
0023 //  * `absl::Time` defines an absolute, specific instance in time
0024 //  * `absl::Duration` defines a signed, fixed-length span of time
0025 //  * `absl::TimeZone` defines geopolitical time zone regions (as collected
0026 //     within the IANA Time Zone database (https://www.iana.org/time-zones)).
0027 //
0028 // Note: Absolute times are distinct from civil times, which refer to the
0029 // human-scale time commonly represented by `YYYY-MM-DD hh:mm:ss`. The mapping
0030 // between absolute and civil times can be specified by use of time zones
0031 // (`absl::TimeZone` within this API). That is:
0032 //
0033 //   Civil Time = F(Absolute Time, Time Zone)
0034 //   Absolute Time = G(Civil Time, Time Zone)
0035 //
0036 // See civil_time.h for abstractions related to constructing and manipulating
0037 // civil time.
0038 //
0039 // Example:
0040 //
0041 //   absl::TimeZone nyc;
0042 //   // LoadTimeZone() may fail so it's always better to check for success.
0043 //   if (!absl::LoadTimeZone("America/New_York", &nyc)) {
0044 //      // handle error case
0045 //   }
0046 //
0047 //   // My flight leaves NYC on Jan 2, 2017 at 03:04:05
0048 //   absl::CivilSecond cs(2017, 1, 2, 3, 4, 5);
0049 //   absl::Time takeoff = absl::FromCivil(cs, nyc);
0050 //
0051 //   absl::Duration flight_duration = absl::Hours(21) + absl::Minutes(35);
0052 //   absl::Time landing = takeoff + flight_duration;
0053 //
0054 //   absl::TimeZone syd;
0055 //   if (!absl::LoadTimeZone("Australia/Sydney", &syd)) {
0056 //      // handle error case
0057 //   }
0058 //   std::string s = absl::FormatTime(
0059 //       "My flight will land in Sydney on %Y-%m-%d at %H:%M:%S",
0060 //       landing, syd);
0061 
0062 #ifndef ABSL_TIME_TIME_H_
0063 #define ABSL_TIME_TIME_H_
0064 
0065 #if !defined(_MSC_VER)
0066 #include <sys/time.h>
0067 #else
0068 // We don't include `winsock2.h` because it drags in `windows.h` and friends,
0069 // and they define conflicting macros like OPAQUE, ERROR, and more. This has the
0070 // potential to break Abseil users.
0071 //
0072 // Instead we only forward declare `timeval` and require Windows users include
0073 // `winsock2.h` themselves. This is both inconsistent and troublesome, but so is
0074 // including 'windows.h' so we are picking the lesser of two evils here.
0075 struct timeval;
0076 #endif
0077 #include <chrono>  // NOLINT(build/c++11)
0078 
0079 #ifdef __cpp_impl_three_way_comparison
0080 #include <compare>
0081 #endif  // __cpp_impl_three_way_comparison
0082 
0083 #include <cmath>
0084 #include <cstdint>
0085 #include <ctime>
0086 #include <limits>
0087 #include <ostream>
0088 #include <ratio>  // NOLINT(build/c++11)
0089 #include <string>
0090 #include <type_traits>
0091 #include <utility>
0092 
0093 #include "absl/base/attributes.h"
0094 #include "absl/base/config.h"
0095 #include "absl/base/macros.h"
0096 #include "absl/strings/string_view.h"
0097 #include "absl/time/civil_time.h"
0098 #include "absl/time/internal/cctz/include/cctz/time_zone.h"
0099 
0100 namespace absl {
0101 ABSL_NAMESPACE_BEGIN
0102 
0103 class Duration;  // Defined below
0104 class Time;      // Defined below
0105 class TimeZone;  // Defined below
0106 
0107 namespace time_internal {
0108 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d);
0109 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t);
0110 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d);
0111 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d);
0112 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
0113                                                               uint32_t lo);
0114 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
0115                                                               int64_t lo);
0116 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n);
0117 constexpr int64_t kTicksPerNanosecond = 4;
0118 constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond;
0119 template <std::intmax_t N>
0120 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
0121                                                            std::ratio<1, N>);
0122 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
0123                                                            std::ratio<60>);
0124 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
0125                                                            std::ratio<3600>);
0126 template <typename T>
0127 using EnableIfIntegral = typename std::enable_if<
0128     std::is_integral<T>::value || std::is_enum<T>::value, int>::type;
0129 template <typename T>
0130 using EnableIfFloat =
0131     typename std::enable_if<std::is_floating_point<T>::value, int>::type;
0132 }  // namespace time_internal
0133 
0134 // Duration
0135 //
0136 // The `absl::Duration` class represents a signed, fixed-length amount of time.
0137 // A `Duration` is generated using a unit-specific factory function, or is
0138 // the result of subtracting one `absl::Time` from another. Durations behave
0139 // like unit-safe integers and they support all the natural integer-like
0140 // arithmetic operations. Arithmetic overflows and saturates at +/- infinity.
0141 // `Duration` should be passed by value rather than const reference.
0142 //
0143 // Factory functions `Nanoseconds()`, `Microseconds()`, `Milliseconds()`,
0144 // `Seconds()`, `Minutes()`, `Hours()` and `InfiniteDuration()` allow for
0145 // creation of constexpr `Duration` values
0146 //
0147 // Examples:
0148 //
0149 //   constexpr absl::Duration ten_ns = absl::Nanoseconds(10);
0150 //   constexpr absl::Duration min = absl::Minutes(1);
0151 //   constexpr absl::Duration hour = absl::Hours(1);
0152 //   absl::Duration dur = 60 * min;  // dur == hour
0153 //   absl::Duration half_sec = absl::Milliseconds(500);
0154 //   absl::Duration quarter_sec = 0.25 * absl::Seconds(1);
0155 //
0156 // `Duration` values can be easily converted to an integral number of units
0157 // using the division operator.
0158 //
0159 // Example:
0160 //
0161 //   constexpr absl::Duration dur = absl::Milliseconds(1500);
0162 //   int64_t ns = dur / absl::Nanoseconds(1);   // ns == 1500000000
0163 //   int64_t ms = dur / absl::Milliseconds(1);  // ms == 1500
0164 //   int64_t sec = dur / absl::Seconds(1);    // sec == 1 (subseconds truncated)
0165 //   int64_t min = dur / absl::Minutes(1);    // min == 0
0166 //
0167 // See the `IDivDuration()` and `FDivDuration()` functions below for details on
0168 // how to access the fractional parts of the quotient.
0169 //
0170 // Alternatively, conversions can be performed using helpers such as
0171 // `ToInt64Microseconds()` and `ToDoubleSeconds()`.
0172 class Duration {
0173  public:
0174   // Value semantics.
0175   constexpr Duration() : rep_hi_(0), rep_lo_(0) {}  // zero-length duration
0176 
0177   // Copyable.
0178 #if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1930
0179   // Explicitly defining the constexpr copy constructor avoids an MSVC bug.
0180   constexpr Duration(const Duration& d)
0181       : rep_hi_(d.rep_hi_), rep_lo_(d.rep_lo_) {}
0182 #else
0183   constexpr Duration(const Duration& d) = default;
0184 #endif
0185   Duration& operator=(const Duration& d) = default;
0186 
0187   // Compound assignment operators.
0188   Duration& operator+=(Duration d);
0189   Duration& operator-=(Duration d);
0190   Duration& operator*=(int64_t r);
0191   Duration& operator*=(double r);
0192   Duration& operator/=(int64_t r);
0193   Duration& operator/=(double r);
0194   Duration& operator%=(Duration rhs);
0195 
0196   // Overloads that forward to either the int64_t or double overloads above.
0197   // Integer operands must be representable as int64_t. Integer division is
0198   // truncating, so values less than the resolution will be returned as zero.
0199   // Floating-point multiplication and division is rounding (halfway cases
0200   // rounding away from zero), so values less than the resolution may be
0201   // returned as either the resolution or zero.  In particular, `d / 2.0`
0202   // can produce `d` when it is the resolution and "even".
0203   template <typename T, time_internal::EnableIfIntegral<T> = 0>
0204   Duration& operator*=(T r) {
0205     int64_t x = r;
0206     return *this *= x;
0207   }
0208 
0209   template <typename T, time_internal::EnableIfIntegral<T> = 0>
0210   Duration& operator/=(T r) {
0211     int64_t x = r;
0212     return *this /= x;
0213   }
0214 
0215   template <typename T, time_internal::EnableIfFloat<T> = 0>
0216   Duration& operator*=(T r) {
0217     double x = r;
0218     return *this *= x;
0219   }
0220 
0221   template <typename T, time_internal::EnableIfFloat<T> = 0>
0222   Duration& operator/=(T r) {
0223     double x = r;
0224     return *this /= x;
0225   }
0226 
0227   template <typename H>
0228   friend H AbslHashValue(H h, Duration d) {
0229     return H::combine(std::move(h), d.rep_hi_.Get(), d.rep_lo_);
0230   }
0231 
0232  private:
0233   friend constexpr int64_t time_internal::GetRepHi(Duration d);
0234   friend constexpr uint32_t time_internal::GetRepLo(Duration d);
0235   friend constexpr Duration time_internal::MakeDuration(int64_t hi,
0236                                                         uint32_t lo);
0237   constexpr Duration(int64_t hi, uint32_t lo) : rep_hi_(hi), rep_lo_(lo) {}
0238 
0239   // We store `rep_hi_` 4-byte rather than 8-byte aligned to avoid 4 bytes of
0240   // tail padding.
0241   class HiRep {
0242    public:
0243     // Default constructor default-initializes `hi_`, which has the same
0244     // semantics as default-initializing an `int64_t` (undetermined value).
0245     HiRep() = default;
0246 
0247     HiRep(const HiRep&) = default;
0248     HiRep& operator=(const HiRep&) = default;
0249 
0250     explicit constexpr HiRep(const int64_t value)
0251         :  // C++17 forbids default-initialization in constexpr contexts. We can
0252            // remove this in C++20.
0253 #if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
0254           hi_(0),
0255           lo_(0)
0256 #else
0257           lo_(0),
0258           hi_(0)
0259 #endif
0260     {
0261       *this = value;
0262     }
0263 
0264     constexpr int64_t Get() const {
0265       const uint64_t unsigned_value =
0266           (static_cast<uint64_t>(hi_) << 32) | static_cast<uint64_t>(lo_);
0267       // `static_cast<int64_t>(unsigned_value)` is implementation-defined
0268       // before c++20. On all supported platforms the behaviour is that mandated
0269       // by c++20, i.e. "If the destination type is signed, [...] the result is
0270       // the unique value of the destination type equal to the source value
0271       // modulo 2^n, where n is the number of bits used to represent the
0272       // destination type."
0273       static_assert(
0274           (static_cast<int64_t>((std::numeric_limits<uint64_t>::max)()) ==
0275            int64_t{-1}) &&
0276               (static_cast<int64_t>(static_cast<uint64_t>(
0277                                         (std::numeric_limits<int64_t>::max)()) +
0278                                     1) ==
0279                (std::numeric_limits<int64_t>::min)()),
0280           "static_cast<int64_t>(uint64_t) does not have c++20 semantics");
0281       return static_cast<int64_t>(unsigned_value);
0282     }
0283 
0284     constexpr HiRep& operator=(const int64_t value) {
0285       // "If the destination type is unsigned, the resulting value is the
0286       // smallest unsigned value equal to the source value modulo 2^n
0287       // where `n` is the number of bits used to represent the destination
0288       // type".
0289       const auto unsigned_value = static_cast<uint64_t>(value);
0290       hi_ = static_cast<uint32_t>(unsigned_value >> 32);
0291       lo_ = static_cast<uint32_t>(unsigned_value);
0292       return *this;
0293     }
0294 
0295    private:
0296     // Notes:
0297     //  - Ideally we would use a `char[]` and `std::bitcast`, but the latter
0298     //    does not exist (and is not constexpr in `absl`) before c++20.
0299     //  - Order is optimized depending on endianness so that the compiler can
0300     //    turn `Get()` (resp. `operator=()`) into a single 8-byte load (resp.
0301     //    store).
0302 #if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
0303     uint32_t hi_;
0304     uint32_t lo_;
0305 #else
0306     uint32_t lo_;
0307     uint32_t hi_;
0308 #endif
0309   };
0310   HiRep rep_hi_;
0311   uint32_t rep_lo_;
0312 };
0313 
0314 // Relational Operators
0315 
0316 #ifdef __cpp_impl_three_way_comparison
0317 
0318 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr std::strong_ordering operator<=>(
0319     Duration lhs, Duration rhs);
0320 
0321 #endif  // __cpp_impl_three_way_comparison
0322 
0323 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
0324                                                        Duration rhs);
0325 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Duration lhs,
0326                                                        Duration rhs) {
0327   return rhs < lhs;
0328 }
0329 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Duration lhs,
0330                                                         Duration rhs) {
0331   return !(lhs < rhs);
0332 }
0333 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Duration lhs,
0334                                                         Duration rhs) {
0335   return !(rhs < lhs);
0336 }
0337 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
0338                                                         Duration rhs);
0339 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Duration lhs,
0340                                                         Duration rhs) {
0341   return !(lhs == rhs);
0342 }
0343 
0344 // Additive Operators
0345 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d);
0346 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator+(Duration lhs,
0347                                                         Duration rhs) {
0348   return lhs += rhs;
0349 }
0350 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Duration lhs,
0351                                                         Duration rhs) {
0352   return lhs -= rhs;
0353 }
0354 
0355 // IDivDuration()
0356 //
0357 // Divides a numerator `Duration` by a denominator `Duration`, returning the
0358 // quotient and remainder. The remainder always has the same sign as the
0359 // numerator. The returned quotient and remainder respect the identity:
0360 //
0361 //   numerator = denominator * quotient + remainder
0362 //
0363 // Returned quotients are capped to the range of `int64_t`, with the difference
0364 // spilling into the remainder to uphold the above identity. This means that the
0365 // remainder returned could differ from the remainder returned by
0366 // `Duration::operator%` for huge quotients.
0367 //
0368 // See also the notes on `InfiniteDuration()` below regarding the behavior of
0369 // division involving zero and infinite durations.
0370 //
0371 // Example:
0372 //
0373 //   constexpr absl::Duration a =
0374 //       absl::Seconds(std::numeric_limits<int64_t>::max());  // big
0375 //   constexpr absl::Duration b = absl::Nanoseconds(1);       // small
0376 //
0377 //   absl::Duration rem = a % b;
0378 //   // rem == absl::ZeroDuration()
0379 //
0380 //   // Here, q would overflow int64_t, so rem accounts for the difference.
0381 //   int64_t q = absl::IDivDuration(a, b, &rem);
0382 //   // q == std::numeric_limits<int64_t>::max(), rem == a - b * q
0383 int64_t IDivDuration(Duration num, Duration den, Duration* rem);
0384 
0385 // FDivDuration()
0386 //
0387 // Divides a `Duration` numerator into a fractional number of units of a
0388 // `Duration` denominator.
0389 //
0390 // See also the notes on `InfiniteDuration()` below regarding the behavior of
0391 // division involving zero and infinite durations.
0392 //
0393 // Example:
0394 //
0395 //   double d = absl::FDivDuration(absl::Milliseconds(1500), absl::Seconds(1));
0396 //   // d == 1.5
0397 ABSL_ATTRIBUTE_CONST_FUNCTION double FDivDuration(Duration num, Duration den);
0398 
0399 // Multiplicative Operators
0400 // Integer operands must be representable as int64_t.
0401 template <typename T>
0402 ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(Duration lhs, T rhs) {
0403   return lhs *= rhs;
0404 }
0405 template <typename T>
0406 ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(T lhs, Duration rhs) {
0407   return rhs *= lhs;
0408 }
0409 template <typename T>
0410 ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator/(Duration lhs, T rhs) {
0411   return lhs /= rhs;
0412 }
0413 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t operator/(Duration lhs,
0414                                                        Duration rhs) {
0415   return IDivDuration(lhs, rhs,
0416                       &lhs);  // trunc towards zero
0417 }
0418 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator%(Duration lhs,
0419                                                         Duration rhs) {
0420   return lhs %= rhs;
0421 }
0422 
0423 // ZeroDuration()
0424 //
0425 // Returns a zero-length duration. This function behaves just like the default
0426 // constructor, but the name helps make the semantics clear at call sites.
0427 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ZeroDuration() {
0428   return Duration();
0429 }
0430 
0431 // AbsDuration()
0432 //
0433 // Returns the absolute value of a duration.
0434 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration AbsDuration(Duration d) {
0435   return (d < ZeroDuration()) ? -d : d;
0436 }
0437 
0438 // Trunc()
0439 //
0440 // Truncates a duration (toward zero) to a multiple of a non-zero unit.
0441 //
0442 // Example:
0443 //
0444 //   absl::Duration d = absl::Nanoseconds(123456789);
0445 //   absl::Duration a = absl::Trunc(d, absl::Microseconds(1));  // 123456us
0446 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Trunc(Duration d, Duration unit);
0447 
0448 // Floor()
0449 //
0450 // Floors a duration using the passed duration unit to its largest value not
0451 // greater than the duration.
0452 //
0453 // Example:
0454 //
0455 //   absl::Duration d = absl::Nanoseconds(123456789);
0456 //   absl::Duration b = absl::Floor(d, absl::Microseconds(1));  // 123456us
0457 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Floor(Duration d, Duration unit);
0458 
0459 // Ceil()
0460 //
0461 // Returns the ceiling of a duration using the passed duration unit to its
0462 // smallest value not less than the duration.
0463 //
0464 // Example:
0465 //
0466 //   absl::Duration d = absl::Nanoseconds(123456789);
0467 //   absl::Duration c = absl::Ceil(d, absl::Microseconds(1));   // 123457us
0468 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Ceil(Duration d, Duration unit);
0469 
0470 // InfiniteDuration()
0471 //
0472 // Returns an infinite `Duration`.  To get a `Duration` representing negative
0473 // infinity, use `-InfiniteDuration()`.
0474 //
0475 // Duration arithmetic overflows to +/- infinity and saturates. In general,
0476 // arithmetic with `Duration` infinities is similar to IEEE 754 infinities
0477 // except where IEEE 754 NaN would be involved, in which case +/-
0478 // `InfiniteDuration()` is used in place of a "nan" Duration.
0479 //
0480 // Examples:
0481 //
0482 //   constexpr absl::Duration inf = absl::InfiniteDuration();
0483 //   const absl::Duration d = ... any finite duration ...
0484 //
0485 //   inf == inf + inf
0486 //   inf == inf + d
0487 //   inf == inf - inf
0488 //   -inf == d - inf
0489 //
0490 //   inf == d * 1e100
0491 //   inf == inf / 2
0492 //   0 == d / inf
0493 //   INT64_MAX == inf / d
0494 //
0495 //   d < inf
0496 //   -inf < d
0497 //
0498 //   // Division by zero returns infinity, or INT64_MIN/MAX where appropriate.
0499 //   inf == d / 0
0500 //   INT64_MAX == d / absl::ZeroDuration()
0501 //
0502 // The examples involving the `/` operator above also apply to `IDivDuration()`
0503 // and `FDivDuration()`.
0504 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration();
0505 
0506 // Nanoseconds()
0507 // Microseconds()
0508 // Milliseconds()
0509 // Seconds()
0510 // Minutes()
0511 // Hours()
0512 //
0513 // Factory functions for constructing `Duration` values from an integral number
0514 // of the unit indicated by the factory function's name. The number must be
0515 // representable as int64_t.
0516 //
0517 // NOTE: no "Days()" factory function exists because "a day" is ambiguous.
0518 // Civil days are not always 24 hours long, and a 24-hour duration often does
0519 // not correspond with a civil day. If a 24-hour duration is needed, use
0520 // `absl::Hours(24)`. If you actually want a civil day, use absl::CivilDay
0521 // from civil_time.h.
0522 //
0523 // Example:
0524 //
0525 //   absl::Duration a = absl::Seconds(60);
0526 //   absl::Duration b = absl::Minutes(1);  // b == a
0527 template <typename T, time_internal::EnableIfIntegral<T> = 0>
0528 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Nanoseconds(T n) {
0529   return time_internal::FromInt64(n, std::nano{});
0530 }
0531 template <typename T, time_internal::EnableIfIntegral<T> = 0>
0532 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Microseconds(T n) {
0533   return time_internal::FromInt64(n, std::micro{});
0534 }
0535 template <typename T, time_internal::EnableIfIntegral<T> = 0>
0536 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Milliseconds(T n) {
0537   return time_internal::FromInt64(n, std::milli{});
0538 }
0539 template <typename T, time_internal::EnableIfIntegral<T> = 0>
0540 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Seconds(T n) {
0541   return time_internal::FromInt64(n, std::ratio<1>{});
0542 }
0543 template <typename T, time_internal::EnableIfIntegral<T> = 0>
0544 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Minutes(T n) {
0545   return time_internal::FromInt64(n, std::ratio<60>{});
0546 }
0547 template <typename T, time_internal::EnableIfIntegral<T> = 0>
0548 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Hours(T n) {
0549   return time_internal::FromInt64(n, std::ratio<3600>{});
0550 }
0551 
0552 // Factory overloads for constructing `Duration` values from a floating-point
0553 // number of the unit indicated by the factory function's name. These functions
0554 // exist for convenience, but they are not as efficient as the integral
0555 // factories, which should be preferred.
0556 //
0557 // Example:
0558 //
0559 //   auto a = absl::Seconds(1.5);        // OK
0560 //   auto b = absl::Milliseconds(1500);  // BETTER
0561 template <typename T, time_internal::EnableIfFloat<T> = 0>
0562 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Nanoseconds(T n) {
0563   return n * Nanoseconds(1);
0564 }
0565 template <typename T, time_internal::EnableIfFloat<T> = 0>
0566 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Microseconds(T n) {
0567   return n * Microseconds(1);
0568 }
0569 template <typename T, time_internal::EnableIfFloat<T> = 0>
0570 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Milliseconds(T n) {
0571   return n * Milliseconds(1);
0572 }
0573 template <typename T, time_internal::EnableIfFloat<T> = 0>
0574 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Seconds(T n) {
0575   if (n >= 0) {  // Note: `NaN >= 0` is false.
0576     if (n >= static_cast<T>((std::numeric_limits<int64_t>::max)())) {
0577       return InfiniteDuration();
0578     }
0579     return time_internal::MakePosDoubleDuration(n);
0580   } else {
0581     if (std::isnan(n))
0582       return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration();
0583     if (n <= (std::numeric_limits<int64_t>::min)()) return -InfiniteDuration();
0584     return -time_internal::MakePosDoubleDuration(-n);
0585   }
0586 }
0587 template <typename T, time_internal::EnableIfFloat<T> = 0>
0588 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Minutes(T n) {
0589   return n * Minutes(1);
0590 }
0591 template <typename T, time_internal::EnableIfFloat<T> = 0>
0592 ABSL_ATTRIBUTE_CONST_FUNCTION Duration Hours(T n) {
0593   return n * Hours(1);
0594 }
0595 
0596 // ToInt64Nanoseconds()
0597 // ToInt64Microseconds()
0598 // ToInt64Milliseconds()
0599 // ToInt64Seconds()
0600 // ToInt64Minutes()
0601 // ToInt64Hours()
0602 //
0603 // Helper functions that convert a Duration to an integral count of the
0604 // indicated unit. These return the same results as the `IDivDuration()`
0605 // function, though they usually do so more efficiently; see the
0606 // documentation of `IDivDuration()` for details about overflow, etc.
0607 //
0608 // Example:
0609 //
0610 //   absl::Duration d = absl::Milliseconds(1500);
0611 //   int64_t isec = absl::ToInt64Seconds(d);  // isec == 1
0612 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Nanoseconds(Duration d);
0613 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Microseconds(Duration d);
0614 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Milliseconds(Duration d);
0615 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Seconds(Duration d);
0616 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Minutes(Duration d);
0617 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Hours(Duration d);
0618 
0619 // ToDoubleNanoseconds()
0620 // ToDoubleMicroseconds()
0621 // ToDoubleMilliseconds()
0622 // ToDoubleSeconds()
0623 // ToDoubleMinutes()
0624 // ToDoubleHours()
0625 //
0626 // Helper functions that convert a Duration to a floating point count of the
0627 // indicated unit. These functions are shorthand for the `FDivDuration()`
0628 // function above; see its documentation for details about overflow, etc.
0629 //
0630 // Example:
0631 //
0632 //   absl::Duration d = absl::Milliseconds(1500);
0633 //   double dsec = absl::ToDoubleSeconds(d);  // dsec == 1.5
0634 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleNanoseconds(Duration d);
0635 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMicroseconds(Duration d);
0636 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMilliseconds(Duration d);
0637 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleSeconds(Duration d);
0638 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMinutes(Duration d);
0639 ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleHours(Duration d);
0640 
0641 // FromChrono()
0642 //
0643 // Converts any of the pre-defined std::chrono durations to an absl::Duration.
0644 //
0645 // Example:
0646 //
0647 //   std::chrono::milliseconds ms(123);
0648 //   absl::Duration d = absl::FromChrono(ms);
0649 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
0650     const std::chrono::nanoseconds& d);
0651 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
0652     const std::chrono::microseconds& d);
0653 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
0654     const std::chrono::milliseconds& d);
0655 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
0656     const std::chrono::seconds& d);
0657 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
0658     const std::chrono::minutes& d);
0659 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
0660     const std::chrono::hours& d);
0661 
0662 // ToChronoNanoseconds()
0663 // ToChronoMicroseconds()
0664 // ToChronoMilliseconds()
0665 // ToChronoSeconds()
0666 // ToChronoMinutes()
0667 // ToChronoHours()
0668 //
0669 // Converts an absl::Duration to any of the pre-defined std::chrono durations.
0670 // If overflow would occur, the returned value will saturate at the min/max
0671 // chrono duration value instead.
0672 //
0673 // Example:
0674 //
0675 //   absl::Duration d = absl::Microseconds(123);
0676 //   auto x = absl::ToChronoMicroseconds(d);
0677 //   auto y = absl::ToChronoNanoseconds(d);  // x == y
0678 //   auto z = absl::ToChronoSeconds(absl::InfiniteDuration());
0679 //   // z == std::chrono::seconds::max()
0680 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::nanoseconds ToChronoNanoseconds(
0681     Duration d);
0682 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::microseconds ToChronoMicroseconds(
0683     Duration d);
0684 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::milliseconds ToChronoMilliseconds(
0685     Duration d);
0686 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::seconds ToChronoSeconds(Duration d);
0687 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::minutes ToChronoMinutes(Duration d);
0688 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::hours ToChronoHours(Duration d);
0689 
0690 // FormatDuration()
0691 //
0692 // Returns a string representing the duration in the form "72h3m0.5s".
0693 // Returns "inf" or "-inf" for +/- `InfiniteDuration()`.
0694 ABSL_ATTRIBUTE_CONST_FUNCTION std::string FormatDuration(Duration d);
0695 
0696 // Output stream operator.
0697 inline std::ostream& operator<<(std::ostream& os, Duration d) {
0698   return os << FormatDuration(d);
0699 }
0700 
0701 // Support for StrFormat(), StrCat() etc.
0702 template <typename Sink>
0703 void AbslStringify(Sink& sink, Duration d) {
0704   sink.Append(FormatDuration(d));
0705 }
0706 
0707 // ParseDuration()
0708 //
0709 // Parses a duration string consisting of a possibly signed sequence of
0710 // decimal numbers, each with an optional fractional part and a unit
0711 // suffix.  The valid suffixes are "ns", "us" "ms", "s", "m", and "h".
0712 // Simple examples include "300ms", "-1.5h", and "2h45m".  Parses "0" as
0713 // `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`.
0714 bool ParseDuration(absl::string_view dur_string, Duration* d);
0715 
0716 // AbslParseFlag()
0717 //
0718 // Parses a command-line flag string representation `text` into a Duration
0719 // value. Duration flags must be specified in a format that is valid input for
0720 // `absl::ParseDuration()`.
0721 bool AbslParseFlag(absl::string_view text, Duration* dst, std::string* error);
0722 
0723 
0724 // AbslUnparseFlag()
0725 //
0726 // Unparses a Duration value into a command-line string representation using
0727 // the format specified by `absl::ParseDuration()`.
0728 std::string AbslUnparseFlag(Duration d);
0729 
0730 ABSL_DEPRECATED("Use AbslParseFlag() instead.")
0731 bool ParseFlag(const std::string& text, Duration* dst, std::string* error);
0732 ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
0733 std::string UnparseFlag(Duration d);
0734 
0735 // Time
0736 //
0737 // An `absl::Time` represents a specific instant in time. Arithmetic operators
0738 // are provided for naturally expressing time calculations. Instances are
0739 // created using `absl::Now()` and the `absl::From*()` factory functions that
0740 // accept the gamut of other time representations. Formatting and parsing
0741 // functions are provided for conversion to and from strings.  `absl::Time`
0742 // should be passed by value rather than const reference.
0743 //
0744 // `absl::Time` assumes there are 60 seconds in a minute, which means the
0745 // underlying time scales must be "smeared" to eliminate leap seconds.
0746 // See https://developers.google.com/time/smear.
0747 //
0748 // Even though `absl::Time` supports a wide range of timestamps, exercise
0749 // caution when using values in the distant past. `absl::Time` uses the
0750 // Proleptic Gregorian calendar, which extends the Gregorian calendar backward
0751 // to dates before its introduction in 1582.
0752 // See https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar
0753 // for more information. Use the ICU calendar classes to convert a date in
0754 // some other calendar (http://userguide.icu-project.org/datetime/calendar).
0755 //
0756 // Similarly, standardized time zones are a reasonably recent innovation, with
0757 // the Greenwich prime meridian being established in 1884. The TZ database
0758 // itself does not profess accurate offsets for timestamps prior to 1970. The
0759 // breakdown of future timestamps is subject to the whim of regional
0760 // governments.
0761 //
0762 // The `absl::Time` class represents an instant in time as a count of clock
0763 // ticks of some granularity (resolution) from some starting point (epoch).
0764 //
0765 // `absl::Time` uses a resolution that is high enough to avoid loss in
0766 // precision, and a range that is wide enough to avoid overflow, when
0767 // converting between tick counts in most Google time scales (i.e., resolution
0768 // of at least one nanosecond, and range +/-100 billion years).  Conversions
0769 // between the time scales are performed by truncating (towards negative
0770 // infinity) to the nearest representable point.
0771 //
0772 // Examples:
0773 //
0774 //   absl::Time t1 = ...;
0775 //   absl::Time t2 = t1 + absl::Minutes(2);
0776 //   absl::Duration d = t2 - t1;  // == absl::Minutes(2)
0777 //
0778 class Time {
0779  public:
0780   // Value semantics.
0781 
0782   // Returns the Unix epoch.  However, those reading your code may not know
0783   // or expect the Unix epoch as the default value, so make your code more
0784   // readable by explicitly initializing all instances before use.
0785   //
0786   // Example:
0787   //   absl::Time t = absl::UnixEpoch();
0788   //   absl::Time t = absl::Now();
0789   //   absl::Time t = absl::TimeFromTimeval(tv);
0790   //   absl::Time t = absl::InfinitePast();
0791   constexpr Time() = default;
0792 
0793   // Copyable.
0794   constexpr Time(const Time& t) = default;
0795   Time& operator=(const Time& t) = default;
0796 
0797   // Assignment operators.
0798   Time& operator+=(Duration d) {
0799     rep_ += d;
0800     return *this;
0801   }
0802   Time& operator-=(Duration d) {
0803     rep_ -= d;
0804     return *this;
0805   }
0806 
0807   // Time::Breakdown
0808   //
0809   // The calendar and wall-clock (aka "civil time") components of an
0810   // `absl::Time` in a certain `absl::TimeZone`. This struct is not
0811   // intended to represent an instant in time. So, rather than passing
0812   // a `Time::Breakdown` to a function, pass an `absl::Time` and an
0813   // `absl::TimeZone`.
0814   //
0815   // Deprecated. Use `absl::TimeZone::CivilInfo`.
0816   struct ABSL_DEPRECATED("Use `absl::TimeZone::CivilInfo`.") Breakdown {
0817     int64_t year;        // year (e.g., 2013)
0818     int month;           // month of year [1:12]
0819     int day;             // day of month [1:31]
0820     int hour;            // hour of day [0:23]
0821     int minute;          // minute of hour [0:59]
0822     int second;          // second of minute [0:59]
0823     Duration subsecond;  // [Seconds(0):Seconds(1)) if finite
0824     int weekday;         // 1==Mon, ..., 7=Sun
0825     int yearday;         // day of year [1:366]
0826 
0827     // Note: The following fields exist for backward compatibility
0828     // with older APIs.  Accessing these fields directly is a sign of
0829     // imprudent logic in the calling code.  Modern time-related code
0830     // should only access this data indirectly by way of FormatTime().
0831     // These fields are undefined for InfiniteFuture() and InfinitePast().
0832     int offset;             // seconds east of UTC
0833     bool is_dst;            // is offset non-standard?
0834     const char* zone_abbr;  // time-zone abbreviation (e.g., "PST")
0835   };
0836 
0837   // Time::In()
0838   //
0839   // Returns the breakdown of this instant in the given TimeZone.
0840   //
0841   // Deprecated. Use `absl::TimeZone::At(Time)`.
0842   ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
0843   ABSL_DEPRECATED("Use `absl::TimeZone::At(Time)`.")
0844   Breakdown In(TimeZone tz) const;
0845   ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
0846 
0847   template <typename H>
0848   friend H AbslHashValue(H h, Time t) {
0849     return H::combine(std::move(h), t.rep_);
0850   }
0851 
0852  private:
0853   friend constexpr Time time_internal::FromUnixDuration(Duration d);
0854   friend constexpr Duration time_internal::ToUnixDuration(Time t);
0855 
0856 #ifdef __cpp_impl_three_way_comparison
0857   friend constexpr std::strong_ordering operator<=>(Time lhs, Time rhs);
0858 #endif  // __cpp_impl_three_way_comparison
0859 
0860   friend constexpr bool operator<(Time lhs, Time rhs);
0861   friend constexpr bool operator==(Time lhs, Time rhs);
0862   friend Duration operator-(Time lhs, Time rhs);
0863   friend constexpr Time UniversalEpoch();
0864   friend constexpr Time InfiniteFuture();
0865   friend constexpr Time InfinitePast();
0866   constexpr explicit Time(Duration rep) : rep_(rep) {}
0867   Duration rep_;
0868 };
0869 
0870 // Relational Operators
0871 #ifdef __cpp_impl_three_way_comparison
0872 
0873 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr std::strong_ordering operator<=>(
0874     Time lhs, Time rhs) {
0875   return lhs.rep_ <=> rhs.rep_;
0876 }
0877 
0878 #endif  // __cpp_impl_three_way_comparison
0879 
0880 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Time lhs, Time rhs) {
0881   return lhs.rep_ < rhs.rep_;
0882 }
0883 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Time lhs, Time rhs) {
0884   return rhs < lhs;
0885 }
0886 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Time lhs, Time rhs) {
0887   return !(lhs < rhs);
0888 }
0889 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Time lhs, Time rhs) {
0890   return !(rhs < lhs);
0891 }
0892 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Time lhs, Time rhs) {
0893   return lhs.rep_ == rhs.rep_;
0894 }
0895 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Time lhs, Time rhs) {
0896   return !(lhs == rhs);
0897 }
0898 
0899 // Additive Operators
0900 ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Time lhs, Duration rhs) {
0901   return lhs += rhs;
0902 }
0903 ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Duration lhs, Time rhs) {
0904   return rhs += lhs;
0905 }
0906 ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator-(Time lhs, Duration rhs) {
0907   return lhs -= rhs;
0908 }
0909 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Time lhs, Time rhs) {
0910   return lhs.rep_ - rhs.rep_;
0911 }
0912 
0913 // UnixEpoch()
0914 //
0915 // Returns the `absl::Time` representing "1970-01-01 00:00:00.0 +0000".
0916 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UnixEpoch() { return Time(); }
0917 
0918 // UniversalEpoch()
0919 //
0920 // Returns the `absl::Time` representing "0001-01-01 00:00:00.0 +0000", the
0921 // epoch of the ICU Universal Time Scale.
0922 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UniversalEpoch() {
0923   // 719162 is the number of days from 0001-01-01 to 1970-01-01,
0924   // assuming the Gregorian calendar.
0925   return Time(
0926       time_internal::MakeDuration(-24 * 719162 * int64_t{3600}, uint32_t{0}));
0927 }
0928 
0929 // InfiniteFuture()
0930 //
0931 // Returns an `absl::Time` that is infinitely far in the future.
0932 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfiniteFuture() {
0933   return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
0934                                           ~uint32_t{0}));
0935 }
0936 
0937 // InfinitePast()
0938 //
0939 // Returns an `absl::Time` that is infinitely far in the past.
0940 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfinitePast() {
0941   return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::min)(),
0942                                           ~uint32_t{0}));
0943 }
0944 
0945 // FromUnixNanos()
0946 // FromUnixMicros()
0947 // FromUnixMillis()
0948 // FromUnixSeconds()
0949 // FromTimeT()
0950 // FromUDate()
0951 // FromUniversal()
0952 //
0953 // Creates an `absl::Time` from a variety of other representations.  See
0954 // https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
0955 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns);
0956 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us);
0957 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms);
0958 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s);
0959 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t);
0960 ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUDate(double udate);
0961 ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUniversal(int64_t universal);
0962 
0963 // ToUnixNanos()
0964 // ToUnixMicros()
0965 // ToUnixMillis()
0966 // ToUnixSeconds()
0967 // ToTimeT()
0968 // ToUDate()
0969 // ToUniversal()
0970 //
0971 // Converts an `absl::Time` to a variety of other representations.  See
0972 // https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
0973 //
0974 // Note that these operations round down toward negative infinity where
0975 // necessary to adjust to the resolution of the result type.  Beware of
0976 // possible time_t over/underflow in ToTime{T,val,spec}() on 32-bit platforms.
0977 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixNanos(Time t);
0978 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMicros(Time t);
0979 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMillis(Time t);
0980 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixSeconds(Time t);
0981 ABSL_ATTRIBUTE_CONST_FUNCTION time_t ToTimeT(Time t);
0982 ABSL_ATTRIBUTE_CONST_FUNCTION double ToUDate(Time t);
0983 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUniversal(Time t);
0984 
0985 // DurationFromTimespec()
0986 // DurationFromTimeval()
0987 // ToTimespec()
0988 // ToTimeval()
0989 // TimeFromTimespec()
0990 // TimeFromTimeval()
0991 // ToTimespec()
0992 // ToTimeval()
0993 //
0994 // Some APIs use a timespec or a timeval as a Duration (e.g., nanosleep(2)
0995 // and select(2)), while others use them as a Time (e.g. clock_gettime(2)
0996 // and gettimeofday(2)), so conversion functions are provided for both cases.
0997 // The "to timespec/val" direction is easily handled via overloading, but
0998 // for "from timespec/val" the desired type is part of the function name.
0999 ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimespec(timespec ts);
1000 ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimeval(timeval tv);
1001 ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Duration d);
1002 ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Duration d);
1003 ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimespec(timespec ts);
1004 ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimeval(timeval tv);
1005 ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Time t);
1006 ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Time t);
1007 
1008 // FromChrono()
1009 //
1010 // Converts a std::chrono::system_clock::time_point to an absl::Time.
1011 //
1012 // Example:
1013 //
1014 //   auto tp = std::chrono::system_clock::from_time_t(123);
1015 //   absl::Time t = absl::FromChrono(tp);
1016 //   // t == absl::FromTimeT(123)
1017 ABSL_ATTRIBUTE_PURE_FUNCTION Time
1018 FromChrono(const std::chrono::system_clock::time_point& tp);
1019 
1020 // ToChronoTime()
1021 //
1022 // Converts an absl::Time to a std::chrono::system_clock::time_point. If
1023 // overflow would occur, the returned value will saturate at the min/max time
1024 // point value instead.
1025 //
1026 // Example:
1027 //
1028 //   absl::Time t = absl::FromTimeT(123);
1029 //   auto tp = absl::ToChronoTime(t);
1030 //   // tp == std::chrono::system_clock::from_time_t(123);
1031 ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::system_clock::time_point
1032     ToChronoTime(Time);
1033 
1034 // AbslParseFlag()
1035 //
1036 // Parses the command-line flag string representation `text` into a Time value.
1037 // Time flags must be specified in a format that matches absl::RFC3339_full.
1038 //
1039 // For example:
1040 //
1041 //   --start_time=2016-01-02T03:04:05.678+08:00
1042 //
1043 // Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required.
1044 //
1045 // Additionally, if you'd like to specify a time as a count of
1046 // seconds/milliseconds/etc from the Unix epoch, use an absl::Duration flag
1047 // and add that duration to absl::UnixEpoch() to get an absl::Time.
1048 bool AbslParseFlag(absl::string_view text, Time* t, std::string* error);
1049 
1050 // AbslUnparseFlag()
1051 //
1052 // Unparses a Time value into a command-line string representation using
1053 // the format specified by `absl::ParseTime()`.
1054 std::string AbslUnparseFlag(Time t);
1055 
1056 ABSL_DEPRECATED("Use AbslParseFlag() instead.")
1057 bool ParseFlag(const std::string& text, Time* t, std::string* error);
1058 ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
1059 std::string UnparseFlag(Time t);
1060 
1061 // TimeZone
1062 //
1063 // The `absl::TimeZone` is an opaque, small, value-type class representing a
1064 // geo-political region within which particular rules are used for converting
1065 // between absolute and civil times (see https://git.io/v59Ly). `absl::TimeZone`
1066 // values are named using the TZ identifiers from the IANA Time Zone Database,
1067 // such as "America/Los_Angeles" or "Australia/Sydney". `absl::TimeZone` values
1068 // are created from factory functions such as `absl::LoadTimeZone()`. Note:
1069 // strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by
1070 // value rather than const reference.
1071 //
1072 // For more on the fundamental concepts of time zones, absolute times, and civil
1073 // times, see https://github.com/google/cctz#fundamental-concepts
1074 //
1075 // Examples:
1076 //
1077 //   absl::TimeZone utc = absl::UTCTimeZone();
1078 //   absl::TimeZone pst = absl::FixedTimeZone(-8 * 60 * 60);
1079 //   absl::TimeZone loc = absl::LocalTimeZone();
1080 //   absl::TimeZone lax;
1081 //   if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) {
1082 //     // handle error case
1083 //   }
1084 //
1085 // See also:
1086 // - https://github.com/google/cctz
1087 // - https://www.iana.org/time-zones
1088 // - https://en.wikipedia.org/wiki/Zoneinfo
1089 class TimeZone {
1090  public:
1091   explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {}
1092   TimeZone() = default;  // UTC, but prefer UTCTimeZone() to be explicit.
1093 
1094   // Copyable.
1095   TimeZone(const TimeZone&) = default;
1096   TimeZone& operator=(const TimeZone&) = default;
1097 
1098   explicit operator time_internal::cctz::time_zone() const { return cz_; }
1099 
1100   std::string name() const { return cz_.name(); }
1101 
1102   // TimeZone::CivilInfo
1103   //
1104   // Information about the civil time corresponding to an absolute time.
1105   // This struct is not intended to represent an instant in time. So, rather
1106   // than passing a `TimeZone::CivilInfo` to a function, pass an `absl::Time`
1107   // and an `absl::TimeZone`.
1108   struct CivilInfo {
1109     CivilSecond cs;
1110     Duration subsecond;
1111 
1112     // Note: The following fields exist for backward compatibility
1113     // with older APIs.  Accessing these fields directly is a sign of
1114     // imprudent logic in the calling code.  Modern time-related code
1115     // should only access this data indirectly by way of FormatTime().
1116     // These fields are undefined for InfiniteFuture() and InfinitePast().
1117     int offset;             // seconds east of UTC
1118     bool is_dst;            // is offset non-standard?
1119     const char* zone_abbr;  // time-zone abbreviation (e.g., "PST")
1120   };
1121 
1122   // TimeZone::At(Time)
1123   //
1124   // Returns the civil time for this TimeZone at a certain `absl::Time`.
1125   // If the input time is infinite, the output civil second will be set to
1126   // CivilSecond::max() or min(), and the subsecond will be infinite.
1127   //
1128   // Example:
1129   //
1130   //   const auto epoch = lax.At(absl::UnixEpoch());
1131   //   // epoch.cs == 1969-12-31 16:00:00
1132   //   // epoch.subsecond == absl::ZeroDuration()
1133   //   // epoch.offset == -28800
1134   //   // epoch.is_dst == false
1135   //   // epoch.abbr == "PST"
1136   CivilInfo At(Time t) const;
1137 
1138   // TimeZone::TimeInfo
1139   //
1140   // Information about the absolute times corresponding to a civil time.
1141   // (Subseconds must be handled separately.)
1142   //
1143   // It is possible for a caller to pass a civil-time value that does
1144   // not represent an actual or unique instant in time (due to a shift
1145   // in UTC offset in the TimeZone, which results in a discontinuity in
1146   // the civil-time components). For example, a daylight-saving-time
1147   // transition skips or repeats civil times---in the United States,
1148   // March 13, 2011 02:15 never occurred, while November 6, 2011 01:15
1149   // occurred twice---so requests for such times are not well-defined.
1150   // To account for these possibilities, `absl::TimeZone::TimeInfo` is
1151   // richer than just a single `absl::Time`.
1152   struct TimeInfo {
1153     enum CivilKind {
1154       UNIQUE,    // the civil time was singular (pre == trans == post)
1155       SKIPPED,   // the civil time did not exist (pre >= trans > post)
1156       REPEATED,  // the civil time was ambiguous (pre < trans <= post)
1157     } kind;
1158     Time pre;    // time calculated using the pre-transition offset
1159     Time trans;  // when the civil-time discontinuity occurred
1160     Time post;   // time calculated using the post-transition offset
1161   };
1162 
1163   // TimeZone::At(CivilSecond)
1164   //
1165   // Returns an `absl::TimeInfo` containing the absolute time(s) for this
1166   // TimeZone at an `absl::CivilSecond`. When the civil time is skipped or
1167   // repeated, returns times calculated using the pre-transition and post-
1168   // transition UTC offsets, plus the transition time itself.
1169   //
1170   // Examples:
1171   //
1172   //   // A unique civil time
1173   //   const auto jan01 = lax.At(absl::CivilSecond(2011, 1, 1, 0, 0, 0));
1174   //   // jan01.kind == TimeZone::TimeInfo::UNIQUE
1175   //   // jan01.pre    is 2011-01-01 00:00:00 -0800
1176   //   // jan01.trans  is 2011-01-01 00:00:00 -0800
1177   //   // jan01.post   is 2011-01-01 00:00:00 -0800
1178   //
1179   //   // A Spring DST transition, when there is a gap in civil time
1180   //   const auto mar13 = lax.At(absl::CivilSecond(2011, 3, 13, 2, 15, 0));
1181   //   // mar13.kind == TimeZone::TimeInfo::SKIPPED
1182   //   // mar13.pre   is 2011-03-13 03:15:00 -0700
1183   //   // mar13.trans is 2011-03-13 03:00:00 -0700
1184   //   // mar13.post  is 2011-03-13 01:15:00 -0800
1185   //
1186   //   // A Fall DST transition, when civil times are repeated
1187   //   const auto nov06 = lax.At(absl::CivilSecond(2011, 11, 6, 1, 15, 0));
1188   //   // nov06.kind == TimeZone::TimeInfo::REPEATED
1189   //   // nov06.pre   is 2011-11-06 01:15:00 -0700
1190   //   // nov06.trans is 2011-11-06 01:00:00 -0800
1191   //   // nov06.post  is 2011-11-06 01:15:00 -0800
1192   TimeInfo At(CivilSecond ct) const;
1193 
1194   // TimeZone::NextTransition()
1195   // TimeZone::PrevTransition()
1196   //
1197   // Finds the time of the next/previous offset change in this time zone.
1198   //
1199   // By definition, `NextTransition(t, &trans)` returns false when `t` is
1200   // `InfiniteFuture()`, and `PrevTransition(t, &trans)` returns false
1201   // when `t` is `InfinitePast()`. If the zone has no transitions, the
1202   // result will also be false no matter what the argument.
1203   //
1204   // Otherwise, when `t` is `InfinitePast()`, `NextTransition(t, &trans)`
1205   // returns true and sets `trans` to the first recorded transition. Chains
1206   // of calls to `NextTransition()/PrevTransition()` will eventually return
1207   // false, but it is unspecified exactly when `NextTransition(t, &trans)`
1208   // jumps to false, or what time is set by `PrevTransition(t, &trans)` for
1209   // a very distant `t`.
1210   //
1211   // Note: Enumeration of time-zone transitions is for informational purposes
1212   // only. Modern time-related code should not care about when offset changes
1213   // occur.
1214   //
1215   // Example:
1216   //   absl::TimeZone nyc;
1217   //   if (!absl::LoadTimeZone("America/New_York", &nyc)) { ... }
1218   //   const auto now = absl::Now();
1219   //   auto t = absl::InfinitePast();
1220   //   absl::TimeZone::CivilTransition trans;
1221   //   while (t <= now && nyc.NextTransition(t, &trans)) {
1222   //     // transition: trans.from -> trans.to
1223   //     t = nyc.At(trans.to).trans;
1224   //   }
1225   struct CivilTransition {
1226     CivilSecond from;  // the civil time we jump from
1227     CivilSecond to;    // the civil time we jump to
1228   };
1229   bool NextTransition(Time t, CivilTransition* trans) const;
1230   bool PrevTransition(Time t, CivilTransition* trans) const;
1231 
1232   template <typename H>
1233   friend H AbslHashValue(H h, TimeZone tz) {
1234     return H::combine(std::move(h), tz.cz_);
1235   }
1236 
1237  private:
1238   friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; }
1239   friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; }
1240   friend std::ostream& operator<<(std::ostream& os, TimeZone tz) {
1241     return os << tz.name();
1242   }
1243 
1244   time_internal::cctz::time_zone cz_;
1245 };
1246 
1247 // LoadTimeZone()
1248 //
1249 // Loads the named zone. May perform I/O on the initial load of the named
1250 // zone. If the name is invalid, or some other kind of error occurs, returns
1251 // `false` and `*tz` is set to the UTC time zone.
1252 inline bool LoadTimeZone(absl::string_view name, TimeZone* tz) {
1253   if (name == "localtime") {
1254     *tz = TimeZone(time_internal::cctz::local_time_zone());
1255     return true;
1256   }
1257   time_internal::cctz::time_zone cz;
1258   const bool b = time_internal::cctz::load_time_zone(std::string(name), &cz);
1259   *tz = TimeZone(cz);
1260   return b;
1261 }
1262 
1263 // FixedTimeZone()
1264 //
1265 // Returns a TimeZone that is a fixed offset (seconds east) from UTC.
1266 // Note: If the absolute value of the offset is greater than 24 hours
1267 // you'll get UTC (i.e., no offset) instead.
1268 inline TimeZone FixedTimeZone(int seconds) {
1269   return TimeZone(
1270       time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds)));
1271 }
1272 
1273 // UTCTimeZone()
1274 //
1275 // Convenience method returning the UTC time zone.
1276 inline TimeZone UTCTimeZone() {
1277   return TimeZone(time_internal::cctz::utc_time_zone());
1278 }
1279 
1280 // LocalTimeZone()
1281 //
1282 // Convenience method returning the local time zone, or UTC if there is
1283 // no configured local zone.  Warning: Be wary of using LocalTimeZone(),
1284 // and particularly so in a server process, as the zone configured for the
1285 // local machine should be irrelevant.  Prefer an explicit zone name.
1286 inline TimeZone LocalTimeZone() {
1287   return TimeZone(time_internal::cctz::local_time_zone());
1288 }
1289 
1290 // ToCivilSecond()
1291 // ToCivilMinute()
1292 // ToCivilHour()
1293 // ToCivilDay()
1294 // ToCivilMonth()
1295 // ToCivilYear()
1296 //
1297 // Helpers for TimeZone::At(Time) to return particularly aligned civil times.
1298 //
1299 // Example:
1300 //
1301 //   absl::Time t = ...;
1302 //   absl::TimeZone tz = ...;
1303 //   const auto cd = absl::ToCivilDay(t, tz);
1304 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilSecond ToCivilSecond(Time t,
1305                                                               TimeZone tz) {
1306   return tz.At(t).cs;  // already a CivilSecond
1307 }
1308 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilMinute ToCivilMinute(Time t,
1309                                                               TimeZone tz) {
1310   return CivilMinute(tz.At(t).cs);
1311 }
1312 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilHour ToCivilHour(Time t, TimeZone tz) {
1313   return CivilHour(tz.At(t).cs);
1314 }
1315 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilDay ToCivilDay(Time t, TimeZone tz) {
1316   return CivilDay(tz.At(t).cs);
1317 }
1318 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilMonth ToCivilMonth(Time t,
1319                                                             TimeZone tz) {
1320   return CivilMonth(tz.At(t).cs);
1321 }
1322 ABSL_ATTRIBUTE_PURE_FUNCTION inline CivilYear ToCivilYear(Time t, TimeZone tz) {
1323   return CivilYear(tz.At(t).cs);
1324 }
1325 
1326 // FromCivil()
1327 //
1328 // Helper for TimeZone::At(CivilSecond) that provides "order-preserving
1329 // semantics." If the civil time maps to a unique time, that time is
1330 // returned. If the civil time is repeated in the given time zone, the
1331 // time using the pre-transition offset is returned. Otherwise, the
1332 // civil time is skipped in the given time zone, and the transition time
1333 // is returned. This means that for any two civil times, ct1 and ct2,
1334 // (ct1 < ct2) => (FromCivil(ct1) <= FromCivil(ct2)), the equal case
1335 // being when two non-existent civil times map to the same transition time.
1336 //
1337 // Note: Accepts civil times of any alignment.
1338 ABSL_ATTRIBUTE_PURE_FUNCTION inline Time FromCivil(CivilSecond ct,
1339                                                    TimeZone tz) {
1340   const auto ti = tz.At(ct);
1341   if (ti.kind == TimeZone::TimeInfo::SKIPPED) return ti.trans;
1342   return ti.pre;
1343 }
1344 
1345 // TimeConversion
1346 //
1347 // An `absl::TimeConversion` represents the conversion of year, month, day,
1348 // hour, minute, and second values (i.e., a civil time), in a particular
1349 // `absl::TimeZone`, to a time instant (an absolute time), as returned by
1350 // `absl::ConvertDateTime()`. Legacy version of `absl::TimeZone::TimeInfo`.
1351 //
1352 // Deprecated. Use `absl::TimeZone::TimeInfo`.
1353 struct ABSL_DEPRECATED("Use `absl::TimeZone::TimeInfo`.") TimeConversion {
1354   Time pre;    // time calculated using the pre-transition offset
1355   Time trans;  // when the civil-time discontinuity occurred
1356   Time post;   // time calculated using the post-transition offset
1357 
1358   enum Kind {
1359     UNIQUE,    // the civil time was singular (pre == trans == post)
1360     SKIPPED,   // the civil time did not exist
1361     REPEATED,  // the civil time was ambiguous
1362   };
1363   Kind kind;
1364 
1365   bool normalized;  // input values were outside their valid ranges
1366 };
1367 
1368 // ConvertDateTime()
1369 //
1370 // Legacy version of `absl::TimeZone::At(absl::CivilSecond)` that takes
1371 // the civil time as six, separate values (YMDHMS).
1372 //
1373 // The input month, day, hour, minute, and second values can be outside
1374 // of their valid ranges, in which case they will be "normalized" during
1375 // the conversion.
1376 //
1377 // Example:
1378 //
1379 //   // "October 32" normalizes to "November 1".
1380 //   absl::TimeConversion tc =
1381 //       absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, lax);
1382 //   // tc.kind == TimeConversion::UNIQUE && tc.normalized == true
1383 //   // absl::ToCivilDay(tc.pre, tz).month() == 11
1384 //   // absl::ToCivilDay(tc.pre, tz).day() == 1
1385 //
1386 // Deprecated. Use `absl::TimeZone::At(CivilSecond)`.
1387 ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
1388 ABSL_DEPRECATED("Use `absl::TimeZone::At(CivilSecond)`.")
1389 TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour,
1390                                int min, int sec, TimeZone tz);
1391 ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
1392 
1393 // FromDateTime()
1394 //
1395 // A convenience wrapper for `absl::ConvertDateTime()` that simply returns
1396 // the "pre" `absl::Time`.  That is, the unique result, or the instant that
1397 // is correct using the pre-transition offset (as if the transition never
1398 // happened).
1399 //
1400 // Example:
1401 //
1402 //   absl::Time t = absl::FromDateTime(2017, 9, 26, 9, 30, 0, lax);
1403 //   // t = 2017-09-26 09:30:00 -0700
1404 //
1405 // Deprecated. Use `absl::FromCivil(CivilSecond, TimeZone)`. Note that the
1406 // behavior of `FromCivil()` differs from `FromDateTime()` for skipped civil
1407 // times. If you care about that see `absl::TimeZone::At(absl::CivilSecond)`.
1408 ABSL_DEPRECATED("Use `absl::FromCivil(CivilSecond, TimeZone)`.")
1409 inline Time FromDateTime(int64_t year, int mon, int day, int hour, int min,
1410                          int sec, TimeZone tz) {
1411   ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
1412   return ConvertDateTime(year, mon, day, hour, min, sec, tz).pre;
1413   ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
1414 }
1415 
1416 // FromTM()
1417 //
1418 // Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and
1419 // `tm_sec` fields to an `absl::Time` using the given time zone. See ctime(3)
1420 // for a description of the expected values of the tm fields. If the civil time
1421 // is unique (see `absl::TimeZone::At(absl::CivilSecond)` above), the matching
1422 // time instant is returned.  Otherwise, the `tm_isdst` field is consulted to
1423 // choose between the possible results.  For a repeated civil time, `tm_isdst !=
1424 // 0` returns the matching DST instant, while `tm_isdst == 0` returns the
1425 // matching non-DST instant.  For a skipped civil time there is no matching
1426 // instant, so `tm_isdst != 0` returns the DST instant, and `tm_isdst == 0`
1427 // returns the non-DST instant, that would have matched if the transition never
1428 // happened.
1429 ABSL_ATTRIBUTE_PURE_FUNCTION Time FromTM(const struct tm& tm, TimeZone tz);
1430 
1431 // ToTM()
1432 //
1433 // Converts the given `absl::Time` to a struct tm using the given time zone.
1434 // See ctime(3) for a description of the values of the tm fields.
1435 ABSL_ATTRIBUTE_PURE_FUNCTION struct tm ToTM(Time t, TimeZone tz);
1436 
1437 // RFC3339_full
1438 // RFC3339_sec
1439 //
1440 // FormatTime()/ParseTime() format specifiers for RFC3339 date/time strings,
1441 // with trailing zeros trimmed or with fractional seconds omitted altogether.
1442 //
1443 // Note that RFC3339_sec[] matches an ISO 8601 extended format for date and
1444 // time with UTC offset.  Also note the use of "%Y": RFC3339 mandates that
1445 // years have exactly four digits, but we allow them to take their natural
1446 // width.
1447 ABSL_DLL extern const char RFC3339_full[];  // %Y-%m-%d%ET%H:%M:%E*S%Ez
1448 ABSL_DLL extern const char RFC3339_sec[];   // %Y-%m-%d%ET%H:%M:%S%Ez
1449 
1450 // RFC1123_full
1451 // RFC1123_no_wday
1452 //
1453 // FormatTime()/ParseTime() format specifiers for RFC1123 date/time strings.
1454 ABSL_DLL extern const char RFC1123_full[];     // %a, %d %b %E4Y %H:%M:%S %z
1455 ABSL_DLL extern const char RFC1123_no_wday[];  // %d %b %E4Y %H:%M:%S %z
1456 
1457 // FormatTime()
1458 //
1459 // Formats the given `absl::Time` in the `absl::TimeZone` according to the
1460 // provided format string. Uses strftime()-like formatting options, with
1461 // the following extensions:
1462 //
1463 //   - %Ez  - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm)
1464 //   - %E*z - Full-resolution numeric UTC offset (+hh:mm:ss or -hh:mm:ss)
1465 //   - %E#S - Seconds with # digits of fractional precision
1466 //   - %E*S - Seconds with full fractional precision (a literal '*')
1467 //   - %E#f - Fractional seconds with # digits of precision
1468 //   - %E*f - Fractional seconds with full precision (a literal '*')
1469 //   - %E4Y - Four-character years (-999 ... -001, 0000, 0001 ... 9999)
1470 //   - %ET  - The RFC3339 "date-time" separator "T"
1471 //
1472 // Note that %E0S behaves like %S, and %E0f produces no characters.  In
1473 // contrast %E*f always produces at least one digit, which may be '0'.
1474 //
1475 // Note that %Y produces as many characters as it takes to fully render the
1476 // year.  A year outside of [-999:9999] when formatted with %E4Y will produce
1477 // more than four characters, just like %Y.
1478 //
1479 // We recommend that format strings include the UTC offset (%z, %Ez, or %E*z)
1480 // so that the result uniquely identifies a time instant.
1481 //
1482 // Example:
1483 //
1484 //   absl::CivilSecond cs(2013, 1, 2, 3, 4, 5);
1485 //   absl::Time t = absl::FromCivil(cs, lax);
1486 //   std::string f = absl::FormatTime("%H:%M:%S", t, lax);  // "03:04:05"
1487 //   f = absl::FormatTime("%H:%M:%E3S", t, lax);  // "03:04:05.000"
1488 //
1489 // Note: If the given `absl::Time` is `absl::InfiniteFuture()`, the returned
1490 // string will be exactly "infinite-future". If the given `absl::Time` is
1491 // `absl::InfinitePast()`, the returned string will be exactly "infinite-past".
1492 // In both cases the given format string and `absl::TimeZone` are ignored.
1493 //
1494 ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(absl::string_view format,
1495                                                     Time t, TimeZone tz);
1496 
1497 // Convenience functions that format the given time using the RFC3339_full
1498 // format.  The first overload uses the provided TimeZone, while the second
1499 // uses LocalTimeZone().
1500 ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(Time t, TimeZone tz);
1501 ABSL_ATTRIBUTE_PURE_FUNCTION std::string FormatTime(Time t);
1502 
1503 // Output stream operator.
1504 inline std::ostream& operator<<(std::ostream& os, Time t) {
1505   return os << FormatTime(t);
1506 }
1507 
1508 // Support for StrFormat(), StrCat() etc.
1509 template <typename Sink>
1510 void AbslStringify(Sink& sink, Time t) {
1511   sink.Append(FormatTime(t));
1512 }
1513 
1514 // ParseTime()
1515 //
1516 // Parses an input string according to the provided format string and
1517 // returns the corresponding `absl::Time`. Uses strftime()-like formatting
1518 // options, with the same extensions as FormatTime(), but with the
1519 // exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f.  %Ez
1520 // and %E*z also accept the same inputs, which (along with %z) includes
1521 // 'z' and 'Z' as synonyms for +00:00.  %ET accepts either 'T' or 't'.
1522 //
1523 // %Y consumes as many numeric characters as it can, so the matching data
1524 // should always be terminated with a non-numeric.  %E4Y always consumes
1525 // exactly four characters, including any sign.
1526 //
1527 // Unspecified fields are taken from the default date and time of ...
1528 //
1529 //   "1970-01-01 00:00:00.0 +0000"
1530 //
1531 // For example, parsing a string of "15:45" (%H:%M) will return an absl::Time
1532 // that represents "1970-01-01 15:45:00.0 +0000".
1533 //
1534 // Note that since ParseTime() returns time instants, it makes the most sense
1535 // to parse fully-specified date/time strings that include a UTC offset (%z,
1536 // %Ez, or %E*z).
1537 //
1538 // Note also that `absl::ParseTime()` only heeds the fields year, month, day,
1539 // hour, minute, (fractional) second, and UTC offset.  Other fields, like
1540 // weekday (%a or %A), while parsed for syntactic validity, are ignored
1541 // in the conversion.
1542 //
1543 // Date and time fields that are out-of-range will be treated as errors
1544 // rather than normalizing them like `absl::CivilSecond` does.  For example,
1545 // it is an error to parse the date "Oct 32, 2013" because 32 is out of range.
1546 //
1547 // A leap second of ":60" is normalized to ":00" of the following minute
1548 // with fractional seconds discarded.  The following table shows how the
1549 // given seconds and subseconds will be parsed:
1550 //
1551 //   "59.x" -> 59.x  // exact
1552 //   "60.x" -> 00.0  // normalized
1553 //   "00.x" -> 00.x  // exact
1554 //
1555 // Errors are indicated by returning false and assigning an error message
1556 // to the "err" out param if it is non-null.
1557 //
1558 // Note: If the input string is exactly "infinite-future", the returned
1559 // `absl::Time` will be `absl::InfiniteFuture()` and `true` will be returned.
1560 // If the input string is "infinite-past", the returned `absl::Time` will be
1561 // `absl::InfinitePast()` and `true` will be returned.
1562 //
1563 bool ParseTime(absl::string_view format, absl::string_view input, Time* time,
1564                std::string* err);
1565 
1566 // Like ParseTime() above, but if the format string does not contain a UTC
1567 // offset specification (%z/%Ez/%E*z) then the input is interpreted in the
1568 // given TimeZone.  This means that the input, by itself, does not identify a
1569 // unique instant.  Being time-zone dependent, it also admits the possibility
1570 // of ambiguity or non-existence, in which case the "pre" time (as defined
1571 // by TimeZone::TimeInfo) is returned.  For these reasons we recommend that
1572 // all date/time strings include a UTC offset so they're context independent.
1573 bool ParseTime(absl::string_view format, absl::string_view input, TimeZone tz,
1574                Time* time, std::string* err);
1575 
1576 // ============================================================================
1577 // Implementation Details Follow
1578 // ============================================================================
1579 
1580 namespace time_internal {
1581 
1582 // Creates a Duration with a given representation.
1583 // REQUIRES: hi,lo is a valid representation of a Duration as specified
1584 // in time/duration.cc.
1585 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
1586                                                               uint32_t lo = 0) {
1587   return Duration(hi, lo);
1588 }
1589 
1590 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
1591                                                               int64_t lo) {
1592   return MakeDuration(hi, static_cast<uint32_t>(lo));
1593 }
1594 
1595 // Make a Duration value from a floating-point number, as long as that number
1596 // is in the range [ 0 .. numeric_limits<int64_t>::max ), that is, as long as
1597 // it's positive and can be converted to int64_t without risk of UB.
1598 ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n) {
1599   const int64_t int_secs = static_cast<int64_t>(n);
1600   const uint32_t ticks = static_cast<uint32_t>(
1601       std::round((n - static_cast<double>(int_secs)) * kTicksPerSecond));
1602   return ticks < kTicksPerSecond
1603              ? MakeDuration(int_secs, ticks)
1604              : MakeDuration(int_secs + 1, ticks - kTicksPerSecond);
1605 }
1606 
1607 // Creates a normalized Duration from an almost-normalized (sec,ticks)
1608 // pair. sec may be positive or negative.  ticks must be in the range
1609 // -kTicksPerSecond < *ticks < kTicksPerSecond.  If ticks is negative it
1610 // will be normalized to a positive value in the resulting Duration.
1611 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeNormalizedDuration(
1612     int64_t sec, int64_t ticks) {
1613   return (ticks < 0) ? MakeDuration(sec - 1, ticks + kTicksPerSecond)
1614                      : MakeDuration(sec, ticks);
1615 }
1616 
1617 // Provide access to the Duration representation.
1618 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d) {
1619   return d.rep_hi_.Get();
1620 }
1621 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d) {
1622   return d.rep_lo_;
1623 }
1624 
1625 // Returns true iff d is positive or negative infinity.
1626 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool IsInfiniteDuration(Duration d) {
1627   return GetRepLo(d) == ~uint32_t{0};
1628 }
1629 
1630 // Returns an infinite Duration with the opposite sign.
1631 // REQUIRES: IsInfiniteDuration(d)
1632 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration OppositeInfinity(Duration d) {
1633   return GetRepHi(d) < 0
1634              ? MakeDuration((std::numeric_limits<int64_t>::max)(), ~uint32_t{0})
1635              : MakeDuration((std::numeric_limits<int64_t>::min)(),
1636                             ~uint32_t{0});
1637 }
1638 
1639 // Returns (-n)-1 (equivalently -(n+1)) without avoidable overflow.
1640 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t NegateAndSubtractOne(
1641     int64_t n) {
1642   // Note: Good compilers will optimize this expression to ~n when using
1643   // a two's-complement representation (which is required for int64_t).
1644   return (n < 0) ? -(n + 1) : (-n) - 1;
1645 }
1646 
1647 // Map between a Time and a Duration since the Unix epoch.  Note that these
1648 // functions depend on the above mentioned choice of the Unix epoch for the
1649 // Time representation (and both need to be Time friends).  Without this
1650 // knowledge, we would need to add-in/subtract-out UnixEpoch() respectively.
1651 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d) {
1652   return Time(d);
1653 }
1654 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t) {
1655   return t.rep_;
1656 }
1657 
1658 template <std::intmax_t N>
1659 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1660                                                            std::ratio<1, N>) {
1661   static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
1662   // Subsecond ratios cannot overflow.
1663   return MakeNormalizedDuration(
1664       v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
1665 }
1666 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1667                                                            std::ratio<60>) {
1668   return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
1669           v >= (std::numeric_limits<int64_t>::min)() / 60)
1670              ? MakeDuration(v * 60)
1671              : v > 0 ? InfiniteDuration() : -InfiniteDuration();
1672 }
1673 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
1674                                                            std::ratio<3600>) {
1675   return (v <= (std::numeric_limits<int64_t>::max)() / 3600 &&
1676           v >= (std::numeric_limits<int64_t>::min)() / 3600)
1677              ? MakeDuration(v * 3600)
1678              : v > 0 ? InfiniteDuration() : -InfiniteDuration();
1679 }
1680 
1681 // IsValidRep64<T>(0) is true if the expression `int64_t{std::declval<T>()}` is
1682 // valid. That is, if a T can be assigned to an int64_t without narrowing.
1683 template <typename T>
1684 constexpr auto IsValidRep64(int) -> decltype(int64_t{std::declval<T>()} == 0) {
1685   return true;
1686 }
1687 template <typename T>
1688 constexpr auto IsValidRep64(char) -> bool {
1689   return false;
1690 }
1691 
1692 // Converts a std::chrono::duration to an absl::Duration.
1693 template <typename Rep, typename Period>
1694 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1695     const std::chrono::duration<Rep, Period>& d) {
1696   static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
1697   return FromInt64(int64_t{d.count()}, Period{});
1698 }
1699 
1700 template <typename Ratio>
1701 ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64(Duration d, Ratio) {
1702   // Note: This may be used on MSVC, which may have a system_clock period of
1703   // std::ratio<1, 10 * 1000 * 1000>
1704   return ToInt64Seconds(d * Ratio::den / Ratio::num);
1705 }
1706 // Fastpath implementations for the 6 common duration units.
1707 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::nano) {
1708   return ToInt64Nanoseconds(d);
1709 }
1710 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::micro) {
1711   return ToInt64Microseconds(d);
1712 }
1713 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d, std::milli) {
1714   return ToInt64Milliseconds(d);
1715 }
1716 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1717                                                      std::ratio<1>) {
1718   return ToInt64Seconds(d);
1719 }
1720 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1721                                                      std::ratio<60>) {
1722   return ToInt64Minutes(d);
1723 }
1724 ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t ToInt64(Duration d,
1725                                                      std::ratio<3600>) {
1726   return ToInt64Hours(d);
1727 }
1728 
1729 // Converts an absl::Duration to a chrono duration of type T.
1730 template <typename T>
1731 ABSL_ATTRIBUTE_CONST_FUNCTION T ToChronoDuration(Duration d) {
1732   using Rep = typename T::rep;
1733   using Period = typename T::period;
1734   static_assert(IsValidRep64<Rep>(0), "duration::rep is invalid");
1735   if (time_internal::IsInfiniteDuration(d))
1736     return d < ZeroDuration() ? (T::min)() : (T::max)();
1737   const auto v = ToInt64(d, Period{});
1738   if (v > (std::numeric_limits<Rep>::max)()) return (T::max)();
1739   if (v < (std::numeric_limits<Rep>::min)()) return (T::min)();
1740   return T{v};
1741 }
1742 
1743 }  // namespace time_internal
1744 
1745 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
1746                                                        Duration rhs) {
1747   return time_internal::GetRepHi(lhs) != time_internal::GetRepHi(rhs)
1748              ? time_internal::GetRepHi(lhs) < time_internal::GetRepHi(rhs)
1749          : time_internal::GetRepHi(lhs) == (std::numeric_limits<int64_t>::min)()
1750              ? time_internal::GetRepLo(lhs) + 1 <
1751                    time_internal::GetRepLo(rhs) + 1
1752              : time_internal::GetRepLo(lhs) < time_internal::GetRepLo(rhs);
1753 }
1754 
1755 
1756 #ifdef __cpp_impl_three_way_comparison
1757 
1758 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr std::strong_ordering operator<=>(
1759     Duration lhs, Duration rhs) {
1760   const int64_t lhs_hi = time_internal::GetRepHi(lhs);
1761   const int64_t rhs_hi = time_internal::GetRepHi(rhs);
1762   if (auto c = lhs_hi <=> rhs_hi; c != std::strong_ordering::equal) {
1763     return c;
1764   }
1765   const uint32_t lhs_lo = time_internal::GetRepLo(lhs);
1766   const uint32_t rhs_lo = time_internal::GetRepLo(rhs);
1767   return (lhs_hi == (std::numeric_limits<int64_t>::min)())
1768              ? (lhs_lo + 1) <=> (rhs_lo + 1)
1769              : lhs_lo <=> rhs_lo;
1770 }
1771 
1772 #endif  // __cpp_impl_three_way_comparison
1773 
1774 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
1775                                                         Duration rhs) {
1776   return time_internal::GetRepHi(lhs) == time_internal::GetRepHi(rhs) &&
1777          time_internal::GetRepLo(lhs) == time_internal::GetRepLo(rhs);
1778 }
1779 
1780 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d) {
1781   // This is a little interesting because of the special cases.
1782   //
1783   // If rep_lo_ is zero, we have it easy; it's safe to negate rep_hi_, we're
1784   // dealing with an integral number of seconds, and the only special case is
1785   // the maximum negative finite duration, which can't be negated.
1786   //
1787   // Infinities stay infinite, and just change direction.
1788   //
1789   // Finally we're in the case where rep_lo_ is non-zero, and we can borrow
1790   // a second's worth of ticks and avoid overflow (as negating int64_t-min + 1
1791   // is safe).
1792   return time_internal::GetRepLo(d) == 0
1793              ? time_internal::GetRepHi(d) ==
1794                        (std::numeric_limits<int64_t>::min)()
1795                    ? InfiniteDuration()
1796                    : time_internal::MakeDuration(-time_internal::GetRepHi(d))
1797              : time_internal::IsInfiniteDuration(d)
1798                    ? time_internal::OppositeInfinity(d)
1799                    : time_internal::MakeDuration(
1800                          time_internal::NegateAndSubtractOne(
1801                              time_internal::GetRepHi(d)),
1802                          time_internal::kTicksPerSecond -
1803                              time_internal::GetRepLo(d));
1804 }
1805 
1806 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration() {
1807   return time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
1808                                      ~uint32_t{0});
1809 }
1810 
1811 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1812     const std::chrono::nanoseconds& d) {
1813   return time_internal::FromChrono(d);
1814 }
1815 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1816     const std::chrono::microseconds& d) {
1817   return time_internal::FromChrono(d);
1818 }
1819 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1820     const std::chrono::milliseconds& d) {
1821   return time_internal::FromChrono(d);
1822 }
1823 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1824     const std::chrono::seconds& d) {
1825   return time_internal::FromChrono(d);
1826 }
1827 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1828     const std::chrono::minutes& d) {
1829   return time_internal::FromChrono(d);
1830 }
1831 ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
1832     const std::chrono::hours& d) {
1833   return time_internal::FromChrono(d);
1834 }
1835 
1836 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns) {
1837   return time_internal::FromUnixDuration(Nanoseconds(ns));
1838 }
1839 
1840 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us) {
1841   return time_internal::FromUnixDuration(Microseconds(us));
1842 }
1843 
1844 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms) {
1845   return time_internal::FromUnixDuration(Milliseconds(ms));
1846 }
1847 
1848 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s) {
1849   return time_internal::FromUnixDuration(Seconds(s));
1850 }
1851 
1852 ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t) {
1853   return time_internal::FromUnixDuration(Seconds(t));
1854 }
1855 
1856 ABSL_NAMESPACE_END
1857 }  // namespace absl
1858 
1859 #endif  // ABSL_TIME_TIME_H_