tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

time.h (75888B)


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