tor-browser

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

time.h (57049B)


      1 // Copyright 2012 The Chromium Authors
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 // `Time` represents an absolute point in coordinated universal time (UTC),
      6 // internally represented as microseconds (s/1,000,000) since the Windows epoch
      7 // (1601-01-01 00:00:00 UTC). System-dependent clock interface routines are
      8 // defined in time_PLATFORM.cc. Note that values for `Time` may skew and jump
      9 // around as the operating system makes adjustments to synchronize (e.g., with
     10 // NTP servers). Thus, client code that uses the `Time` class must account for
     11 // this.
     12 //
     13 // `TimeDelta` represents a duration of time, internally represented in
     14 // microseconds.
     15 //
     16 // `TimeTicks` and `ThreadTicks` represent an abstract time that is most of the
     17 // time incrementing, for use in measuring time durations. Internally, they are
     18 // represented in microseconds. They cannot be converted to a human-readable
     19 // time, but are guaranteed not to decrease (unlike the `Time` class). Note
     20 // that `TimeTicks` may "stand still" (e.g., if the computer is suspended), and
     21 // `ThreadTicks` will "stand still" whenever the thread has been de-scheduled
     22 // by the operating system.
     23 //
     24 // All time classes are copyable, assignable, and occupy 64 bits per instance.
     25 // Prefer to pass them by value, e.g.:
     26 //
     27 //   void MyFunction(TimeDelta arg);
     28 //
     29 // All time classes support `operator<<` with logging streams, e.g. `LOG(INFO)`.
     30 // For human-readable formatting, use //base/i18n/time_formatting.h.
     31 //
     32 // Example use cases for different time classes:
     33 //
     34 //   Time:        Interpreting the wall-clock time provided by a remote system.
     35 //                Detecting whether cached resources have expired. Providing the
     36 //                user with a display of the current date and time. Determining
     37 //                the amount of time between events across re-boots of the
     38 //                machine.
     39 //
     40 //   TimeTicks:   Tracking the amount of time a task runs. Executing delayed
     41 //                tasks at the right time. Computing presentation timestamps.
     42 //                Synchronizing audio and video using TimeTicks as a common
     43 //                reference clock (lip-sync). Measuring network round-trip
     44 //                latency.
     45 //
     46 //   ThreadTicks: Benchmarking how long the current thread has been doing actual
     47 //                work.
     48 //
     49 // Serialization:
     50 //
     51 // Use the helpers in //base/json/values_util.h when serializing `Time`
     52 // or `TimeDelta` to/from `base::Value`.
     53 //
     54 // Otherwise:
     55 //
     56 // - Time: use `FromDeltaSinceWindowsEpoch()`/`ToDeltaSinceWindowsEpoch()`.
     57 // - TimeDelta: use `base::Microseconds()`/`InMicroseconds()`.
     58 //
     59 // `TimeTicks` and `ThreadTicks` do not have a stable origin; serialization for
     60 // the purpose of persistence is not supported.
     61 
     62 #ifndef BASE_TIME_TIME_H_
     63 #define BASE_TIME_TIME_H_
     64 
     65 #include <stdint.h>
     66 #include <time.h>
     67 
     68 #include <iosfwd>
     69 #include <limits>
     70 #include <ostream>
     71 #include <type_traits>
     72 
     73 #include "base/base_export.h"
     74 #include "base/check.h"
     75 #include "base/check_op.h"
     76 #include "base/compiler_specific.h"
     77 #include "base/numerics/clamped_math.h"
     78 #include "build/build_config.h"
     79 #include "build/chromeos_buildflags.h"
     80 
     81 #if BUILDFLAG(IS_FUCHSIA)
     82 #include <zircon/types.h>
     83 #endif
     84 
     85 #if BUILDFLAG(IS_APPLE)
     86 #include <CoreFoundation/CoreFoundation.h>
     87 #include <mach/mach_time.h>
     88 // Avoid Mac system header macro leak.
     89 #undef TYPE_BOOL
     90 #endif
     91 
     92 #if BUILDFLAG(IS_ANDROID)
     93 #include <jni.h>
     94 #endif
     95 
     96 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
     97 #include <unistd.h>
     98 #include <sys/time.h>
     99 #endif
    100 
    101 #if BUILDFLAG(IS_WIN)
    102 #include "base/gtest_prod_util.h"
    103 #include "base/win/windows_types.h"
    104 
    105 namespace ABI {
    106 namespace Windows {
    107 namespace Foundation {
    108 struct DateTime;
    109 struct TimeSpan;
    110 }  // namespace Foundation
    111 }  // namespace Windows
    112 }  // namespace ABI
    113 #endif
    114 
    115 namespace base {
    116 
    117 class PlatformThreadHandle;
    118 class TimeDelta;
    119 
    120 template <typename T>
    121 constexpr TimeDelta Microseconds(T n);
    122 
    123 namespace {
    124 
    125 // TODO: Replace usage of this with std::isnan() once Chromium uses C++23,
    126 // where that is constexpr.
    127 constexpr bool isnan(double d) {
    128  return d != d;
    129 }
    130 
    131 }
    132 
    133 // TimeDelta ------------------------------------------------------------------
    134 
    135 class BASE_EXPORT TimeDelta {
    136 public:
    137  constexpr TimeDelta() = default;
    138 
    139 #if BUILDFLAG(IS_WIN)
    140  static TimeDelta FromQPCValue(LONGLONG qpc_value);
    141  // TODO(crbug.com/989694): Avoid base::TimeDelta factory functions
    142  // based on absolute time
    143  static TimeDelta FromFileTime(FILETIME ft);
    144  static TimeDelta FromWinrtDateTime(ABI::Windows::Foundation::DateTime dt);
    145  static TimeDelta FromWinrtTimeSpan(ABI::Windows::Foundation::TimeSpan ts);
    146 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
    147  static TimeDelta FromTimeSpec(const timespec& ts);
    148 #endif
    149 #if BUILDFLAG(IS_FUCHSIA)
    150  static TimeDelta FromZxDuration(zx_duration_t nanos);
    151 #endif
    152 #if BUILDFLAG(IS_APPLE)
    153  static TimeDelta FromMachTime(uint64_t mach_time);
    154 #endif  // BUILDFLAG(IS_APPLE)
    155 
    156  // Converts an integer value representing TimeDelta to a class. This is used
    157  // when deserializing a |TimeDelta| structure, using a value known to be
    158  // compatible. It is not provided as a constructor because the integer type
    159  // may be unclear from the perspective of a caller.
    160  //
    161  // DEPRECATED - Do not use in new code. http://crbug.com/634507
    162  static constexpr TimeDelta FromInternalValue(int64_t delta) {
    163    return TimeDelta(delta);
    164  }
    165 
    166  // Returns the maximum time delta, which should be greater than any reasonable
    167  // time delta we might compare it to. If converted to double with ToDouble()
    168  // it becomes an IEEE double infinity. Use FiniteMax() if you want a very
    169  // large number that doesn't do this. TimeDelta math saturates at the end
    170  // points so adding to TimeDelta::Max() leaves the value unchanged.
    171  // Subtracting should leave the value unchanged but currently changes it
    172  // TODO(https://crbug.com/869387).
    173  static constexpr TimeDelta Max();
    174 
    175  // Returns the minimum time delta, which should be less than than any
    176  // reasonable time delta we might compare it to. For more details see the
    177  // comments for Max().
    178  static constexpr TimeDelta Min();
    179 
    180  // Returns the maximum time delta which is not equivalent to infinity. Only
    181  // subtracting a finite time delta from this time delta has a defined result.
    182  static constexpr TimeDelta FiniteMax();
    183 
    184  // Returns the minimum time delta which is not equivalent to -infinity. Only
    185  // adding a finite time delta to this time delta has a defined result.
    186  static constexpr TimeDelta FiniteMin();
    187 
    188  // Returns the internal numeric value of the TimeDelta object. Please don't
    189  // use this and do arithmetic on it, as it is more error prone than using the
    190  // provided operators.
    191  // For serializing, use FromInternalValue to reconstitute.
    192  //
    193  // DEPRECATED - Do not use in new code. http://crbug.com/634507
    194  constexpr int64_t ToInternalValue() const { return delta_; }
    195 
    196  // Returns the magnitude (absolute value) of this TimeDelta.
    197  constexpr TimeDelta magnitude() const { return TimeDelta(delta_.Abs()); }
    198 
    199  // Returns true if the time delta is a zero, positive or negative time delta.
    200  constexpr bool is_zero() const { return delta_ == 0; }
    201  constexpr bool is_positive() const { return delta_ > 0; }
    202  constexpr bool is_negative() const { return delta_ < 0; }
    203 
    204  // Returns true if the time delta is the maximum/minimum time delta.
    205  constexpr bool is_max() const { return *this == Max(); }
    206  constexpr bool is_min() const { return *this == Min(); }
    207  constexpr bool is_inf() const { return is_min() || is_max(); }
    208 
    209 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
    210  struct timespec ToTimeSpec() const;
    211 #endif
    212 #if BUILDFLAG(IS_FUCHSIA)
    213  zx_duration_t ToZxDuration() const;
    214 #endif
    215 #if BUILDFLAG(IS_WIN)
    216  ABI::Windows::Foundation::DateTime ToWinrtDateTime() const;
    217  ABI::Windows::Foundation::TimeSpan ToWinrtTimeSpan() const;
    218 #endif
    219 
    220  // Returns the frequency in Hertz (cycles per second) that has a period of
    221  // *this.
    222  constexpr double ToHz() const;
    223 
    224  // Returns the time delta in some unit. Minimum argument values return as
    225  // -inf for doubles and min type values otherwise. Maximum ones are treated as
    226  // +inf for doubles and max type values otherwise. Their results will produce
    227  // an is_min() or is_max() TimeDelta. The InXYZF versions return a floating
    228  // point value. The InXYZ versions return a truncated value (aka rounded
    229  // towards zero, std::trunc() behavior). The InXYZFloored() versions round to
    230  // lesser integers (std::floor() behavior). The XYZRoundedUp() versions round
    231  // up to greater integers (std::ceil() behavior). WARNING: Floating point
    232  // arithmetic is such that XXX(t.InXXXF()) may not precisely equal |t|.
    233  // Hence, floating point values should not be used for storage.
    234  constexpr int InDays() const;
    235  constexpr int InDaysFloored() const;
    236  constexpr int InHours() const;
    237  constexpr int InMinutes() const;
    238  constexpr double InSecondsF() const;
    239  constexpr int64_t InSeconds() const;
    240  constexpr int64_t InSecondsFloored() const;
    241  constexpr double InMillisecondsF() const;
    242  constexpr int64_t InMilliseconds() const;
    243  constexpr int64_t InMillisecondsRoundedUp() const;
    244  constexpr int64_t InMicroseconds() const { return delta_; }
    245  constexpr double InMicrosecondsF() const;
    246  constexpr int64_t InNanoseconds() const;
    247 
    248  // Computations with other deltas.
    249  constexpr TimeDelta operator+(TimeDelta other) const;
    250  constexpr TimeDelta operator-(TimeDelta other) const;
    251 
    252  constexpr TimeDelta& operator+=(TimeDelta other) {
    253    return *this = (*this + other);
    254  }
    255  constexpr TimeDelta& operator-=(TimeDelta other) {
    256    return *this = (*this - other);
    257  }
    258  constexpr TimeDelta operator-() const {
    259    if (!is_inf())
    260      return TimeDelta(-delta_);
    261    return (delta_ < 0) ? Max() : Min();
    262  }
    263 
    264  // Computations with numeric types.
    265  template <typename T>
    266  constexpr TimeDelta operator*(T a) const {
    267    return TimeDelta(int64_t{delta_ * a});
    268  }
    269  template <typename T>
    270  constexpr TimeDelta operator/(T a) const {
    271    return TimeDelta(int64_t{delta_ / a});
    272  }
    273  template <typename T>
    274  constexpr TimeDelta& operator*=(T a) {
    275    return *this = (*this * a);
    276  }
    277  template <typename T>
    278  constexpr TimeDelta& operator/=(T a) {
    279    return *this = (*this / a);
    280  }
    281 
    282  // This does floating-point division. For an integer result, either call
    283  // IntDiv(), or (possibly clearer) use this operator with
    284  // base::Clamp{Ceil,Floor,Round}() or base::saturated_cast() (for truncation).
    285  // Note that converting to double here drops precision to 53 bits.
    286  constexpr double operator/(TimeDelta a) const {
    287    // 0/0 and inf/inf (any combination of positive and negative) are invalid
    288    // (they are almost certainly not intentional, and result in NaN, which
    289    // turns into 0 if clamped to an integer; this makes introducing subtle bugs
    290    // too easy).
    291    CHECK(!is_zero() || !a.is_zero());
    292    CHECK(!is_inf() || !a.is_inf());
    293 
    294    return ToDouble() / a.ToDouble();
    295  }
    296  constexpr int64_t IntDiv(TimeDelta a) const {
    297    if (!is_inf() && !a.is_zero())
    298      return int64_t{delta_ / a.delta_};
    299 
    300    // For consistency, use the same edge case CHECKs and behavior as the code
    301    // above.
    302    CHECK(!is_zero() || !a.is_zero());
    303    CHECK(!is_inf() || !a.is_inf());
    304    return ((delta_ < 0) == (a.delta_ < 0))
    305               ? std::numeric_limits<int64_t>::max()
    306               : std::numeric_limits<int64_t>::min();
    307  }
    308 
    309  constexpr TimeDelta operator%(TimeDelta a) const {
    310    return TimeDelta(
    311        (is_inf() || a.is_zero() || a.is_inf()) ? delta_ : (delta_ % a.delta_));
    312  }
    313  constexpr TimeDelta& operator%=(TimeDelta other) {
    314    return *this = (*this % other);
    315  }
    316 
    317  // Comparison operators.
    318  constexpr bool operator==(TimeDelta other) const {
    319    return delta_ == other.delta_;
    320  }
    321  constexpr bool operator!=(TimeDelta other) const {
    322    return delta_ != other.delta_;
    323  }
    324  constexpr bool operator<(TimeDelta other) const {
    325    return delta_ < other.delta_;
    326  }
    327  constexpr bool operator<=(TimeDelta other) const {
    328    return delta_ <= other.delta_;
    329  }
    330  constexpr bool operator>(TimeDelta other) const {
    331    return delta_ > other.delta_;
    332  }
    333  constexpr bool operator>=(TimeDelta other) const {
    334    return delta_ >= other.delta_;
    335  }
    336 
    337  // Returns this delta, ceiled/floored/rounded-away-from-zero to the nearest
    338  // multiple of |interval|.
    339  TimeDelta CeilToMultiple(TimeDelta interval) const;
    340  TimeDelta FloorToMultiple(TimeDelta interval) const;
    341  TimeDelta RoundToMultiple(TimeDelta interval) const;
    342 
    343 private:
    344  // Constructs a delta given the duration in microseconds. This is private
    345  // to avoid confusion by callers with an integer constructor. Use
    346  // base::Seconds, base::Milliseconds, etc. instead.
    347  constexpr explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
    348  constexpr explicit TimeDelta(ClampedNumeric<int64_t> delta_us)
    349      : delta_(delta_us) {}
    350 
    351  // Returns a double representation of this TimeDelta's tick count.  In
    352  // particular, Max()/Min() are converted to +/-infinity.
    353  constexpr double ToDouble() const {
    354    if (!is_inf())
    355      return static_cast<double>(delta_);
    356    return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
    357                        : std::numeric_limits<double>::infinity();
    358  }
    359 
    360  // Delta in microseconds.
    361  ClampedNumeric<int64_t> delta_ = 0;
    362 };
    363 
    364 constexpr TimeDelta TimeDelta::operator+(TimeDelta other) const {
    365  if (!other.is_inf())
    366    return TimeDelta(delta_ + other.delta_);
    367 
    368  // Additions involving two infinities are only valid if signs match.
    369  CHECK(!is_inf() || (delta_ == other.delta_));
    370  return other;
    371 }
    372 
    373 constexpr TimeDelta TimeDelta::operator-(TimeDelta other) const {
    374  if (!other.is_inf())
    375    return TimeDelta(delta_ - other.delta_);
    376 
    377  // Subtractions involving two infinities are only valid if signs differ.
    378  CHECK_NE(int64_t{delta_}, int64_t{other.delta_});
    379  return (other.delta_ < 0) ? Max() : Min();
    380 }
    381 
    382 template <typename T>
    383 constexpr TimeDelta operator*(T a, TimeDelta td) {
    384  return td * a;
    385 }
    386 
    387 // For logging use only.
    388 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
    389 
    390 // TimeBase--------------------------------------------------------------------
    391 
    392 // Do not reference the time_internal::TimeBase template class directly.  Please
    393 // use one of the time subclasses instead, and only reference the public
    394 // TimeBase members via those classes.
    395 namespace time_internal {
    396 
    397 // Provides value storage and comparison/math operations common to all time
    398 // classes. Each subclass provides for strong type-checking to ensure
    399 // semantically meaningful comparison/math of time values from the same clock
    400 // source or timeline.
    401 template<class TimeClass>
    402 class TimeBase {
    403 public:
    404  static constexpr int64_t kHoursPerDay = 24;
    405  static constexpr int64_t kSecondsPerMinute = 60;
    406  static constexpr int64_t kMinutesPerHour = 60;
    407  static constexpr int64_t kSecondsPerHour =
    408      kSecondsPerMinute * kMinutesPerHour;
    409  static constexpr int64_t kMillisecondsPerSecond = 1000;
    410  static constexpr int64_t kMillisecondsPerDay =
    411      kMillisecondsPerSecond * kSecondsPerHour * kHoursPerDay;
    412  static constexpr int64_t kMicrosecondsPerMillisecond = 1000;
    413  static constexpr int64_t kMicrosecondsPerSecond =
    414      kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
    415  static constexpr int64_t kMicrosecondsPerMinute =
    416      kMicrosecondsPerSecond * kSecondsPerMinute;
    417  static constexpr int64_t kMicrosecondsPerHour =
    418      kMicrosecondsPerMinute * kMinutesPerHour;
    419  static constexpr int64_t kMicrosecondsPerDay =
    420      kMicrosecondsPerHour * kHoursPerDay;
    421  static constexpr int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
    422  static constexpr int64_t kNanosecondsPerMicrosecond = 1000;
    423  static constexpr int64_t kNanosecondsPerSecond =
    424      kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
    425 
    426  // TODO(https://crbug.com/1392437): Remove concept of "null" from base::Time.
    427  //
    428  // Warning: Be careful when writing code that performs math on time values,
    429  // since it's possible to produce a valid "zero" result that should not be
    430  // interpreted as a "null" value. If you find yourself using this method or
    431  // the zero-arg default constructor, please consider using an optional to
    432  // express the null state.
    433  //
    434  // Returns true if this object has not been initialized (probably).
    435  constexpr bool is_null() const { return us_ == 0; }
    436 
    437  // Returns true if this object represents the maximum/minimum time.
    438  constexpr bool is_max() const { return *this == Max(); }
    439  constexpr bool is_min() const { return *this == Min(); }
    440  constexpr bool is_inf() const { return is_min() || is_max(); }
    441 
    442  // Returns the maximum/minimum times, which should be greater/less than than
    443  // any reasonable time with which we might compare it.
    444  static constexpr TimeClass Max() {
    445    return TimeClass(std::numeric_limits<int64_t>::max());
    446  }
    447 
    448  static constexpr TimeClass Min() {
    449    return TimeClass(std::numeric_limits<int64_t>::min());
    450  }
    451 
    452  // For legacy serialization only. When serializing to `base::Value`, prefer
    453  // the helpers from //base/json/values_util.h instead. Otherwise, use
    454  // `Time::ToDeltaSinceWindowsEpoch()` for `Time` and
    455  // `TimeDelta::InMicroseconds()` for `TimeDelta`. See http://crbug.com/634507.
    456  constexpr int64_t ToInternalValue() const { return us_; }
    457 
    458  // The amount of time since the origin (or "zero") point. This is a syntactic
    459  // convenience to aid in code readability, mainly for debugging/testing use
    460  // cases.
    461  //
    462  // Warning: While the Time subclass has a fixed origin point, the origin for
    463  // the other subclasses can vary each time the application is restarted.
    464  constexpr TimeDelta since_origin() const;
    465 
    466  // Compute the difference between two times.
    467 #if !defined(__aarch64__) && BUILDFLAG(IS_ANDROID)
    468  NOINLINE  // https://crbug.com/1369775
    469 #endif
    470  constexpr TimeDelta operator-(const TimeBase<TimeClass>& other) const;
    471 
    472  // Return a new time modified by some delta.
    473  constexpr TimeClass operator+(TimeDelta delta) const;
    474  constexpr TimeClass operator-(TimeDelta delta) const;
    475 
    476  // Modify by some time delta.
    477  constexpr TimeClass& operator+=(TimeDelta delta) {
    478    return static_cast<TimeClass&>(*this = (*this + delta));
    479  }
    480  constexpr TimeClass& operator-=(TimeDelta delta) {
    481    return static_cast<TimeClass&>(*this = (*this - delta));
    482  }
    483 
    484  // Comparison operators
    485  constexpr bool operator==(const TimeBase<TimeClass>& other) const {
    486    return us_ == other.us_;
    487  }
    488  constexpr bool operator!=(const TimeBase<TimeClass>& other) const {
    489    return us_ != other.us_;
    490  }
    491  constexpr bool operator<(const TimeBase<TimeClass>& other) const {
    492    return us_ < other.us_;
    493  }
    494  constexpr bool operator<=(const TimeBase<TimeClass>& other) const {
    495    return us_ <= other.us_;
    496  }
    497  constexpr bool operator>(const TimeBase<TimeClass>& other) const {
    498    return us_ > other.us_;
    499  }
    500  constexpr bool operator>=(const TimeBase<TimeClass>& other) const {
    501    return us_ >= other.us_;
    502  }
    503 
    504 protected:
    505  constexpr explicit TimeBase(int64_t us) : us_(us) {}
    506 
    507  // Time value in a microsecond timebase.
    508  ClampedNumeric<int64_t> us_;
    509 };
    510 
    511 #if BUILDFLAG(IS_WIN)
    512 #if defined(ARCH_CPU_ARM64)
    513 // TSCTicksPerSecond is not supported on Windows on Arm systems because the
    514 // cycle-counting methods use the actual CPU cycle count, and not a consistent
    515 // incrementing counter.
    516 #else
    517 // Returns true if the CPU support constant rate TSC.
    518 [[nodiscard]] BASE_EXPORT bool HasConstantRateTSC();
    519 
    520 // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
    521 // been measured yet. Needs to be guarded with a call to HasConstantRateTSC().
    522 [[nodiscard]] BASE_EXPORT double TSCTicksPerSecond();
    523 #endif
    524 #endif  // BUILDFLAG(IS_WIN)
    525 
    526 }  // namespace time_internal
    527 
    528 template <class TimeClass>
    529 inline constexpr TimeClass operator+(TimeDelta delta, TimeClass t) {
    530  return t + delta;
    531 }
    532 
    533 // Time -----------------------------------------------------------------------
    534 
    535 // Represents a wall clock time in UTC. Values are not guaranteed to be
    536 // monotonically non-decreasing and are subject to large amounts of skew.
    537 // Time is stored internally as microseconds since the Windows epoch (1601).
    538 class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
    539 public:
    540  // Offset of UNIX epoch (1970-01-01 00:00:00 UTC) from Windows FILETIME epoch
    541  // (1601-01-01 00:00:00 UTC), in microseconds. This value is derived from the
    542  // following: ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the number
    543  // of leap year days between 1601 and 1970: (1970-1601)/4 excluding 1700,
    544  // 1800, and 1900.
    545  static constexpr int64_t kTimeTToMicrosecondsOffset =
    546      INT64_C(11644473600000000);
    547 
    548 #if BUILDFLAG(IS_WIN)
    549  // To avoid overflow in QPC to Microseconds calculations, since we multiply
    550  // by kMicrosecondsPerSecond, then the QPC value should not exceed
    551  // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
    552  static constexpr int64_t kQPCOverflowThreshold = INT64_C(0x8637BD05AF7);
    553 #endif
    554 
    555 // kExplodedMinYear and kExplodedMaxYear define the platform-specific limits
    556 // for values passed to FromUTCExploded() and FromLocalExploded(). Those
    557 // functions will return false if passed values outside these limits. The limits
    558 // are inclusive, meaning that the API should support all dates within a given
    559 // limit year.
    560 //
    561 // WARNING: These are not the same limits for the inverse functionality,
    562 // UTCExplode() and LocalExplode(). See method comments for further details.
    563 #if BUILDFLAG(IS_WIN)
    564  static constexpr int kExplodedMinYear = 1601;
    565  static constexpr int kExplodedMaxYear = 30827;
    566 #elif BUILDFLAG(IS_IOS) && !__LP64__
    567  static constexpr int kExplodedMinYear = std::numeric_limits<int>::min();
    568  static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
    569 #elif BUILDFLAG(IS_APPLE)
    570  static constexpr int kExplodedMinYear = 1902;
    571  static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
    572 #elif BUILDFLAG(IS_ANDROID)
    573  // Though we use 64-bit time APIs on both 32 and 64 bit Android, some OS
    574  // versions like KitKat (ARM but not x86 emulator) can't handle some early
    575  // dates (e.g. before 1170). So we set min conservatively here.
    576  static constexpr int kExplodedMinYear = 1902;
    577  static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
    578 #else
    579  static constexpr int kExplodedMinYear =
    580      (sizeof(time_t) == 4 ? 1902 : std::numeric_limits<int>::min());
    581  static constexpr int kExplodedMaxYear =
    582      (sizeof(time_t) == 4 ? 2037 : std::numeric_limits<int>::max());
    583 #endif
    584 
    585  // Represents an exploded time. This is kind of like the Win32 SYSTEMTIME
    586  // structure or the Unix "struct tm" with a few additions and changes to
    587  // prevent errors.
    588  //
    589  // This structure always represents dates in the Gregorian calendar and always
    590  // encodes day_of_week as Sunday==0, Monday==1, .., Saturday==6. This means
    591  // that base::Time::LocalExplode and base::Time::FromLocalExploded only
    592  // respect the current local time zone in the conversion and do *not* use a
    593  // calendar or day-of-week encoding from the current locale.
    594  //
    595  // NOTE: Generally, you should prefer the functions in
    596  // base/i18n/time_formatting.h (in particular,
    597  // `UnlocalizedTimeFormatWithPattern()`) over trying to create a formatted
    598  // time string from this object.
    599  struct BASE_EXPORT Exploded {
    600    int year;          // Four digit year "2007"
    601    int month;         // 1-based month (values 1 = January, etc.)
    602    int day_of_week;   // 0-based day of week (0 = Sunday, etc.)
    603    int day_of_month;  // 1-based day of month (1-31)
    604    int hour;          // Hour within the current day (0-23)
    605    int minute;        // Minute within the current hour (0-59)
    606    int second;        // Second within the current minute (0-59 plus leap
    607                       //   seconds which may take it up to 60).
    608    int millisecond;   // Milliseconds within the current second (0-999)
    609 
    610    // A cursory test for whether the data members are within their
    611    // respective ranges. A 'true' return value does not guarantee the
    612    // Exploded value can be successfully converted to a Time value.
    613    bool HasValidValues() const;
    614  };
    615 
    616  // TODO(https://crbug.com/1392437): Remove concept of "null" from base::Time.
    617  //
    618  // Warning: Be careful when writing code that performs math on time values,
    619  // since it's possible to produce a valid "zero" result that should not be
    620  // interpreted as a "null" value. If you find yourself using this constructor
    621  // or the is_null() method, please consider using an optional to express the
    622  // null state.
    623  //
    624  // Contains the NULL time. Use Time::Now() to get the current time.
    625  constexpr Time() : TimeBase(0) {}
    626 
    627  // Returns the time for epoch in Unix-like system (Jan 1, 1970).
    628  static constexpr Time UnixEpoch() { return Time(kTimeTToMicrosecondsOffset); }
    629 
    630  // Returns the current time. Watch out, the system might adjust its clock
    631  // in which case time will actually go backwards. We don't guarantee that
    632  // times are increasing, or that two calls to Now() won't be the same.
    633  static Time Now();
    634 
    635  // Returns the current time. Same as Now() except that this function always
    636  // uses system time so that there are no discrepancies between the returned
    637  // time and system time even on virtual environments including our test bot.
    638  // For timing sensitive unittests, this function should be used.
    639  static Time NowFromSystemTime();
    640 
    641  // Converts to/from TimeDeltas relative to the Windows epoch (1601-01-01
    642  // 00:00:00 UTC).
    643  //
    644  // For serialization, when handling `base::Value`, prefer the helpers in
    645  // //base/json/values_util.h instead. Otherwise, use these methods for
    646  // opaque serialization and deserialization, e.g.
    647  //
    648  //   // Serialization:
    649  //   base::Time last_updated = ...;
    650  //   SaveToDatabase(last_updated.ToDeltaSinceWindowsEpoch().InMicroseconds());
    651  //
    652  //   // Deserialization:
    653  //   base::Time last_updated = base::Time::FromDeltaSinceWindowsEpoch(
    654  //       base::Microseconds(LoadFromDatabase()));
    655  //
    656  // Do not use `FromInternalValue()` or `ToInternalValue()` for this purpose.
    657  static constexpr Time FromDeltaSinceWindowsEpoch(TimeDelta delta) {
    658    return Time(delta.InMicroseconds());
    659  }
    660 
    661  constexpr TimeDelta ToDeltaSinceWindowsEpoch() const {
    662    return Microseconds(us_);
    663  }
    664 
    665  // Converts to/from time_t in UTC and a Time class.
    666  static constexpr Time FromTimeT(time_t tt);
    667  constexpr time_t ToTimeT() const;
    668 
    669  // Converts time to/from a number of seconds since the Unix epoch (Jan 1,
    670  // 1970).
    671  //
    672  // TODO(crbug.com/1495550): Add integral versions and use them.
    673  // TODO(crbug.com/1495554): Add ...PreservingNull() versions; see comments in
    674  // the implementation of FromSecondsSinceUnixEpoch().
    675  static constexpr Time FromSecondsSinceUnixEpoch(double dt);
    676  constexpr double InSecondsFSinceUnixEpoch() const;
    677 
    678 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
    679  // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
    680  // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
    681  // having a 1 second resolution, which agrees with
    682  // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
    683  static constexpr Time FromTimeSpec(const timespec& ts);
    684 #endif
    685 
    686  // Converts to/from a number of milliseconds since the Unix epoch.
    687  // TODO(crbug.com/1495554): Add ...PreservingNull() versions; see comments in
    688  // the implementation of FromMillisecondsSinceUnixEpoch().
    689  static constexpr Time FromMillisecondsSinceUnixEpoch(int64_t dt);
    690  static constexpr Time FromMillisecondsSinceUnixEpoch(double dt);
    691  // Explicitly forward calls with smaller integral types to the int64_t
    692  // version; otherwise such calls would need to manually cast their args to
    693  // int64_t, since the compiler isn't sure whether to promote to int64_t or
    694  // double.
    695  template <typename T,
    696            typename = std::enable_if_t<
    697                std::is_integral_v<T> && !std::is_same_v<T, int64_t> &&
    698                (sizeof(T) < sizeof(int64_t) ||
    699                 (sizeof(T) == sizeof(int64_t) && std::is_signed_v<T>))>>
    700  static constexpr Time FromMillisecondsSinceUnixEpoch(T ms_since_epoch) {
    701    return FromMillisecondsSinceUnixEpoch(int64_t{ms_since_epoch});
    702  }
    703  constexpr int64_t InMillisecondsSinceUnixEpoch() const;
    704  // Don't use InMillisecondsFSinceUnixEpoch() in new code, since it contains a
    705  // subtle hack (only exactly 1601-01-01 00:00 UTC is represented as 1970-01-01
    706  // 00:00 UTC), and that is not appropriate for general use. Try to use
    707  // InMillisecondsFSinceUnixEpochIgnoringNull() unless you have a very good
    708  // reason to use InMillisecondsFSinceUnixEpoch().
    709  //
    710  // TODO(crbug.com/1495554): Rename the no-suffix version to
    711  // "...PreservingNull()" and remove the suffix from the other version, to
    712  // guide people to the preferable API.
    713  constexpr double InMillisecondsFSinceUnixEpoch() const;
    714  constexpr double InMillisecondsFSinceUnixEpochIgnoringNull() const;
    715 
    716 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
    717  static Time FromTimeVal(struct timeval t);
    718  struct timeval ToTimeVal() const;
    719 #endif
    720 
    721 #if BUILDFLAG(IS_FUCHSIA)
    722  static Time FromZxTime(zx_time_t time);
    723  zx_time_t ToZxTime() const;
    724 #endif
    725 
    726 #if BUILDFLAG(IS_APPLE)
    727  static Time FromCFAbsoluteTime(CFAbsoluteTime t);
    728  CFAbsoluteTime ToCFAbsoluteTime() const;
    729 #if defined(__OBJC__)
    730  static Time FromNSDate(NSDate* date);
    731  NSDate* ToNSDate() const;
    732 #endif
    733 #endif
    734 
    735 #if BUILDFLAG(IS_WIN)
    736  static Time FromFileTime(FILETIME ft);
    737  FILETIME ToFileTime() const;
    738 
    739  // The minimum time of a low resolution timer.  This is basically a windows
    740  // constant of ~15.6ms.  While it does vary on some older OS versions, we'll
    741  // treat it as static across all windows versions.
    742  static const int kMinLowResolutionThresholdMs = 16;
    743 
    744  // Enable or disable Windows high resolution timer.
    745  static void EnableHighResolutionTimer(bool enable);
    746 
    747  // Activates or deactivates the high resolution timer based on the |activate|
    748  // flag.  If the HighResolutionTimer is not Enabled (see
    749  // EnableHighResolutionTimer), this function will return false.  Otherwise
    750  // returns true.  Each successful activate call must be paired with a
    751  // subsequent deactivate call.
    752  // All callers to activate the high resolution timer must eventually call
    753  // this function to deactivate the high resolution timer.
    754  static bool ActivateHighResolutionTimer(bool activate);
    755 
    756  // Returns true if the high resolution timer is both enabled and activated.
    757  // This is provided for testing only, and is not tracked in a thread-safe
    758  // way.
    759  static bool IsHighResolutionTimerInUse();
    760 
    761  // The following two functions are used to report the fraction of elapsed time
    762  // that the high resolution timer is activated.
    763  // ResetHighResolutionTimerUsage() resets the cumulative usage and starts the
    764  // measurement interval and GetHighResolutionTimerUsage() returns the
    765  // percentage of time since the reset that the high resolution timer was
    766  // activated.
    767  // ResetHighResolutionTimerUsage() must be called at least once before calling
    768  // GetHighResolutionTimerUsage(); otherwise the usage result would be
    769  // undefined.
    770  static void ResetHighResolutionTimerUsage();
    771  static double GetHighResolutionTimerUsage();
    772 #endif  // BUILDFLAG(IS_WIN)
    773 
    774  // Converts an exploded structure representing either the local time or UTC
    775  // into a Time class. Returns false on a failure when, for example, a day of
    776  // month is set to 31 on a 28-30 day month. Returns Time(0) on overflow.
    777  // FromLocalExploded respects the current time zone but does not attempt to
    778  // use the calendar or day-of-week encoding from the current locale - see the
    779  // comments on Exploded for more information.
    780  [[nodiscard]] static bool FromUTCExploded(const Exploded& exploded,
    781                                            Time* time) {
    782    return FromExploded(false, exploded, time);
    783  }
    784  [[nodiscard]] static bool FromLocalExploded(const Exploded& exploded,
    785                                              Time* time) {
    786    return FromExploded(true, exploded, time);
    787  }
    788 
    789  // Converts a string representation of time to a Time object.
    790  // An example of a time string which is converted is as below:-
    791  // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
    792  // in the input string, FromString assumes local time and FromUTCString
    793  // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
    794  // specified in RFC822) is treated as if the timezone is not specified.
    795  //
    796  // WARNING: the underlying converter is very permissive. For example: it is
    797  // not checked whether a given day of the week matches the date; Feb 29
    798  // silently becomes Mar 1 in non-leap years; under certain conditions, whole
    799  // English sentences may be parsed successfully and yield unexpected results.
    800  //
    801  // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
    802  // a new time converter class.
    803  [[nodiscard]] static bool FromString(const char* time_string,
    804                                       Time* parsed_time) {
    805    return FromStringInternal(time_string, true, parsed_time);
    806  }
    807  [[nodiscard]] static bool FromUTCString(const char* time_string,
    808                                          Time* parsed_time) {
    809    return FromStringInternal(time_string, false, parsed_time);
    810  }
    811 
    812 #if !defined(MOZ_SANDBOX)
    813  // Fills the given |exploded| structure with either the local time or UTC from
    814  // this Time instance. If the conversion cannot be made, the output will be
    815  // assigned invalid values. Use Exploded::HasValidValues() to confirm a
    816  // successful conversion.
    817  //
    818  // Y10K compliance: This method will successfully convert all Times that
    819  // represent dates on/after the start of the year 1601 and on/before the start
    820  // of the year 30828. Some platforms might convert over a wider input range.
    821  // LocalExplode respects the current time zone but does not attempt to use the
    822  // calendar or day-of-week encoding from the current locale - see the comments
    823  // on Exploded for more information.
    824  void UTCExplode(Exploded* exploded) const { Explode(false, exploded); }
    825  void LocalExplode(Exploded* exploded) const { Explode(true, exploded); }
    826 
    827  // The following two functions round down the time to the nearest day in
    828  // either UTC or local time. It will represent midnight on that day.
    829  Time UTCMidnight() const { return Midnight(false); }
    830  Time LocalMidnight() const { return Midnight(true); }
    831 #endif
    832 
    833  // For legacy deserialization only. Converts an integer value representing
    834  // Time to a class. This may be used when deserializing a |Time| structure,
    835  // using a value known to be compatible. It is not provided as a constructor
    836  // because the integer type may be unclear from the perspective of a caller.
    837  //
    838  // DEPRECATED - Do not use in new code. When deserializing from `base::Value`,
    839  // prefer the helpers from //base/json/values_util.h instead.
    840  // Otherwise, use `Time::FromDeltaSinceWindowsEpoch()` for `Time` and
    841  // `Microseconds()` for `TimeDelta`. http://crbug.com/634507
    842  static constexpr Time FromInternalValue(int64_t us) { return Time(us); }
    843 
    844 private:
    845  friend class time_internal::TimeBase<Time>;
    846 
    847  constexpr explicit Time(int64_t microseconds_since_win_epoch)
    848      : TimeBase(microseconds_since_win_epoch) {}
    849 
    850  // Explodes the given time to either local time |is_local = true| or UTC
    851  // |is_local = false|.
    852  void Explode(bool is_local, Exploded* exploded) const;
    853 
    854  // Unexplodes a given time assuming the source is either local time
    855  // |is_local = true| or UTC |is_local = false|. Function returns false on
    856  // failure and sets |time| to Time(0). Otherwise returns true and sets |time|
    857  // to non-exploded time.
    858  [[nodiscard]] static bool FromExploded(bool is_local,
    859                                         const Exploded& exploded,
    860                                         Time* time);
    861 
    862  // Some platforms use the ICU library to provide To/FromExploded, when their
    863  // native library implementations are insufficient in some way.
    864  static void ExplodeUsingIcu(int64_t millis_since_unix_epoch,
    865                              bool is_local,
    866                              Exploded* exploded);
    867  [[nodiscard]] static bool FromExplodedUsingIcu(
    868      bool is_local,
    869      const Exploded& exploded,
    870      int64_t* millis_since_unix_epoch);
    871 
    872  // Rounds down the time to the nearest day in either local time
    873  // |is_local = true| or UTC |is_local = false|.
    874  Time Midnight(bool is_local) const;
    875 
    876  // Converts a string representation of time to a Time object.
    877  // An example of a time string which is converted is as below:-
    878  // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
    879  // in the input string, local time |is_local = true| or
    880  // UTC |is_local = false| is assumed. A timezone that cannot be parsed
    881  // (e.g. "UTC" which is not specified in RFC822) is treated as if the
    882  // timezone is not specified.
    883  [[nodiscard]] static bool FromStringInternal(const char* time_string,
    884                                               bool is_local,
    885                                               Time* parsed_time);
    886 
    887  // Comparison does not consider |day_of_week| when doing the operation.
    888  [[nodiscard]] static bool ExplodedMostlyEquals(const Exploded& lhs,
    889                                                 const Exploded& rhs);
    890 
    891  // Converts the provided time in milliseconds since the Unix epoch (1970) to a
    892  // Time object, avoiding overflows.
    893  [[nodiscard]] static bool FromMillisecondsSinceUnixEpoch(
    894      int64_t unix_milliseconds,
    895      Time* time);
    896 
    897  // Returns the milliseconds since the Unix epoch (1970), rounding the
    898  // microseconds towards -infinity.
    899  int64_t ToRoundedDownMillisecondsSinceUnixEpoch() const;
    900 };
    901 
    902 // Factory methods that return a TimeDelta of the given unit.
    903 // WARNING: Floating point arithmetic is such that XXX(t.InXXXF()) may not
    904 // precisely equal |t|. Hence, floating point values should not be used for
    905 // storage.
    906 
    907 template <typename T>
    908 constexpr TimeDelta Days(T n) {
    909  return TimeDelta::FromInternalValue(MakeClampedNum(n) *
    910                                      Time::kMicrosecondsPerDay);
    911 }
    912 template <typename T>
    913 constexpr TimeDelta Hours(T n) {
    914  return TimeDelta::FromInternalValue(MakeClampedNum(n) *
    915                                      Time::kMicrosecondsPerHour);
    916 }
    917 template <typename T>
    918 constexpr TimeDelta Minutes(T n) {
    919  return TimeDelta::FromInternalValue(MakeClampedNum(n) *
    920                                      Time::kMicrosecondsPerMinute);
    921 }
    922 template <typename T>
    923 constexpr TimeDelta Seconds(T n) {
    924  return TimeDelta::FromInternalValue(MakeClampedNum(n) *
    925                                      Time::kMicrosecondsPerSecond);
    926 }
    927 template <typename T>
    928 constexpr TimeDelta Milliseconds(T n) {
    929  return TimeDelta::FromInternalValue(MakeClampedNum(n) *
    930                                      Time::kMicrosecondsPerMillisecond);
    931 }
    932 template <typename T>
    933 constexpr TimeDelta Microseconds(T n) {
    934  return TimeDelta::FromInternalValue(MakeClampedNum(n));
    935 }
    936 template <typename T>
    937 constexpr TimeDelta Nanoseconds(T n) {
    938  return TimeDelta::FromInternalValue(MakeClampedNum(n) /
    939                                      Time::kNanosecondsPerMicrosecond);
    940 }
    941 template <typename T>
    942 constexpr TimeDelta Hertz(T n) {
    943  return n ? TimeDelta::FromInternalValue(Time::kMicrosecondsPerSecond /
    944                                          MakeClampedNum(n))
    945           : TimeDelta::Max();
    946 }
    947 
    948 // TimeDelta functions that must appear below the declarations of Time/TimeDelta
    949 
    950 constexpr double TimeDelta::ToHz() const {
    951  return Seconds(1) / *this;
    952 }
    953 
    954 constexpr int TimeDelta::InDays() const {
    955  if (!is_inf()) {
    956    return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
    957  }
    958  return (delta_ < 0) ? std::numeric_limits<int>::min()
    959                      : std::numeric_limits<int>::max();
    960 }
    961 
    962 constexpr int TimeDelta::InDaysFloored() const {
    963  if (!is_inf()) {
    964    const int result = delta_ / Time::kMicrosecondsPerDay;
    965    // Convert |result| from truncating to flooring.
    966    return (result * Time::kMicrosecondsPerDay > delta_) ? (result - 1)
    967                                                         : result;
    968  }
    969  return (delta_ < 0) ? std::numeric_limits<int>::min()
    970                      : std::numeric_limits<int>::max();
    971 }
    972 
    973 constexpr int TimeDelta::InHours() const {
    974  // saturated_cast<> is necessary since very large (but still less than
    975  // min/max) deltas would result in overflow.
    976  return saturated_cast<int>(delta_ / Time::kMicrosecondsPerHour);
    977 }
    978 
    979 constexpr int TimeDelta::InMinutes() const {
    980  // saturated_cast<> is necessary since very large (but still less than
    981  // min/max) deltas would result in overflow.
    982  return saturated_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
    983 }
    984 
    985 constexpr double TimeDelta::InSecondsF() const {
    986  if (!is_inf())
    987    return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
    988  return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
    989                      : std::numeric_limits<double>::infinity();
    990 }
    991 
    992 constexpr int64_t TimeDelta::InSeconds() const {
    993  return is_inf() ? delta_ : (delta_ / Time::kMicrosecondsPerSecond);
    994 }
    995 
    996 constexpr int64_t TimeDelta::InSecondsFloored() const {
    997  if (!is_inf()) {
    998    const int64_t result = delta_ / Time::kMicrosecondsPerSecond;
    999    // Convert |result| from truncating to flooring.
   1000    return (result * Time::kMicrosecondsPerSecond > delta_) ? (result - 1)
   1001                                                            : result;
   1002  }
   1003  return delta_;
   1004 }
   1005 
   1006 constexpr double TimeDelta::InMillisecondsF() const {
   1007  if (!is_inf()) {
   1008    return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
   1009  }
   1010  return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
   1011                      : std::numeric_limits<double>::infinity();
   1012 }
   1013 
   1014 constexpr int64_t TimeDelta::InMilliseconds() const {
   1015  if (!is_inf()) {
   1016    return delta_ / Time::kMicrosecondsPerMillisecond;
   1017  }
   1018  return (delta_ < 0) ? std::numeric_limits<int64_t>::min()
   1019                      : std::numeric_limits<int64_t>::max();
   1020 }
   1021 
   1022 constexpr int64_t TimeDelta::InMillisecondsRoundedUp() const {
   1023  if (!is_inf()) {
   1024    const int64_t result = delta_ / Time::kMicrosecondsPerMillisecond;
   1025    // Convert |result| from truncating to ceiling.
   1026    return (delta_ > result * Time::kMicrosecondsPerMillisecond) ? (result + 1)
   1027                                                                 : result;
   1028  }
   1029  return delta_;
   1030 }
   1031 
   1032 constexpr double TimeDelta::InMicrosecondsF() const {
   1033  if (!is_inf()) {
   1034    return static_cast<double>(delta_);
   1035  }
   1036  return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
   1037                      : std::numeric_limits<double>::infinity();
   1038 }
   1039 
   1040 constexpr int64_t TimeDelta::InNanoseconds() const {
   1041  return base::ClampMul(delta_, Time::kNanosecondsPerMicrosecond);
   1042 }
   1043 
   1044 // static
   1045 constexpr TimeDelta TimeDelta::Max() {
   1046  return TimeDelta(std::numeric_limits<int64_t>::max());
   1047 }
   1048 
   1049 // static
   1050 constexpr TimeDelta TimeDelta::Min() {
   1051  return TimeDelta(std::numeric_limits<int64_t>::min());
   1052 }
   1053 
   1054 // static
   1055 constexpr TimeDelta TimeDelta::FiniteMax() {
   1056  return TimeDelta(std::numeric_limits<int64_t>::max() - 1);
   1057 }
   1058 
   1059 // static
   1060 constexpr TimeDelta TimeDelta::FiniteMin() {
   1061  return TimeDelta(std::numeric_limits<int64_t>::min() + 1);
   1062 }
   1063 
   1064 // TimeBase functions that must appear below the declarations of Time/TimeDelta
   1065 namespace time_internal {
   1066 
   1067 template <class TimeClass>
   1068 constexpr TimeDelta TimeBase<TimeClass>::since_origin() const {
   1069  return Microseconds(us_);
   1070 }
   1071 
   1072 template <class TimeClass>
   1073 constexpr TimeDelta TimeBase<TimeClass>::operator-(
   1074    const TimeBase<TimeClass>& other) const {
   1075  return Microseconds(us_ - other.us_);
   1076 }
   1077 
   1078 template <class TimeClass>
   1079 constexpr TimeClass TimeBase<TimeClass>::operator+(TimeDelta delta) const {
   1080  return TimeClass((Microseconds(us_) + delta).InMicroseconds());
   1081 }
   1082 
   1083 template <class TimeClass>
   1084 constexpr TimeClass TimeBase<TimeClass>::operator-(TimeDelta delta) const {
   1085  return TimeClass((Microseconds(us_) - delta).InMicroseconds());
   1086 }
   1087 
   1088 }  // namespace time_internal
   1089 
   1090 // Time functions that must appear below the declarations of Time/TimeDelta
   1091 
   1092 // static
   1093 constexpr Time Time::FromTimeT(time_t tt) {
   1094  if (tt == 0)
   1095    return Time();  // Preserve 0 so we can tell it doesn't exist.
   1096  return (tt == std::numeric_limits<time_t>::max())
   1097             ? Max()
   1098             : (UnixEpoch() + Seconds(tt));
   1099 }
   1100 
   1101 constexpr time_t Time::ToTimeT() const {
   1102  if (is_null()) {
   1103    return 0;  // Preserve 0 so we can tell it doesn't exist.
   1104  }
   1105  if (!is_inf()) {
   1106    return saturated_cast<time_t>((*this - UnixEpoch()).InSecondsFloored());
   1107  }
   1108  return (us_ < 0) ? std::numeric_limits<time_t>::min()
   1109                   : std::numeric_limits<time_t>::max();
   1110 }
   1111 
   1112 // static
   1113 constexpr Time Time::FromSecondsSinceUnixEpoch(double dt) {
   1114  // Preserve 0.
   1115  //
   1116  // TODO(crbug.com/1495554): This is an unfortunate artifact of WebKit using 0
   1117  // to mean "no time". Add a "...PreservingNull()" version that does this,
   1118  // convert the minimum necessary set of callers to use it, and remove the zero
   1119  // check here.
   1120  return (dt == 0 || isnan(dt)) ? Time() : (UnixEpoch() + Seconds(dt));
   1121 }
   1122 
   1123 constexpr double Time::InSecondsFSinceUnixEpoch() const {
   1124  // Preserve 0.
   1125  if (is_null()) {
   1126    return 0;
   1127  }
   1128  if (!is_inf()) {
   1129    return (*this - UnixEpoch()).InSecondsF();
   1130  }
   1131  return (us_ < 0) ? -std::numeric_limits<double>::infinity()
   1132                   : std::numeric_limits<double>::infinity();
   1133 }
   1134 
   1135 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
   1136 // static
   1137 constexpr Time Time::FromTimeSpec(const timespec& ts) {
   1138  return FromSecondsSinceUnixEpoch(ts.tv_sec + static_cast<double>(ts.tv_nsec) /
   1139                                                   kNanosecondsPerSecond);
   1140 }
   1141 #endif
   1142 
   1143 // static
   1144 constexpr Time Time::FromMillisecondsSinceUnixEpoch(int64_t dt) {
   1145  // TODO(crbug.com/1495554): The lack of zero-preservation here doesn't match
   1146  // InMillisecondsSinceUnixEpoch(), which is dangerous since it means
   1147  // round-trips are not necessarily idempotent. Add "...PreservingNull()"
   1148  // versions that explicitly check for zeros, convert the minimum necessary set
   1149  // of callers to use them, and remove the null-check in
   1150  // InMillisecondsSinceUnixEpoch().
   1151  return UnixEpoch() + Milliseconds(dt);
   1152 }
   1153 
   1154 // static
   1155 constexpr Time Time::FromMillisecondsSinceUnixEpoch(double dt) {
   1156  return isnan(dt) ? Time() : (UnixEpoch() + Milliseconds(dt));
   1157 }
   1158 
   1159 constexpr int64_t Time::InMillisecondsSinceUnixEpoch() const {
   1160  // Preserve 0.
   1161  if (is_null()) {
   1162    return 0;
   1163  }
   1164  if (!is_inf()) {
   1165    return (*this - UnixEpoch()).InMilliseconds();
   1166  }
   1167  return (us_ < 0) ? std::numeric_limits<int64_t>::min()
   1168                   : std::numeric_limits<int64_t>::max();
   1169 }
   1170 
   1171 constexpr double Time::InMillisecondsFSinceUnixEpoch() const {
   1172  // Preserve 0.
   1173  return is_null() ? 0 : InMillisecondsFSinceUnixEpochIgnoringNull();
   1174 }
   1175 
   1176 constexpr double Time::InMillisecondsFSinceUnixEpochIgnoringNull() const {
   1177  // Preserve max and min without offset to prevent over/underflow.
   1178  if (!is_inf()) {
   1179    return (*this - UnixEpoch()).InMillisecondsF();
   1180  }
   1181  return (us_ < 0) ? -std::numeric_limits<double>::infinity()
   1182                   : std::numeric_limits<double>::infinity();
   1183 }
   1184 
   1185 // For logging use only.
   1186 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
   1187 
   1188 // TimeTicks ------------------------------------------------------------------
   1189 
   1190 // Represents monotonically non-decreasing clock time.
   1191 class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
   1192 public:
   1193  // The underlying clock used to generate new TimeTicks.
   1194  enum class Clock {
   1195    FUCHSIA_ZX_CLOCK_MONOTONIC,
   1196    LINUX_CLOCK_MONOTONIC,
   1197    IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME,
   1198    MAC_MACH_ABSOLUTE_TIME,
   1199    WIN_QPC,
   1200    WIN_ROLLOVER_PROTECTED_TIME_GET_TIME
   1201  };
   1202 
   1203  constexpr TimeTicks() : TimeBase(0) {}
   1204 
   1205  // Platform-dependent tick count representing "right now." When
   1206  // IsHighResolution() returns false, the resolution of the clock could be
   1207  // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
   1208  // microsecond.
   1209  static TimeTicks Now();
   1210 
   1211  // Returns true if the high resolution clock is working on this system and
   1212  // Now() will return high resolution values. Note that, on systems where the
   1213  // high resolution clock works but is deemed inefficient, the low resolution
   1214  // clock will be used instead.
   1215  [[nodiscard]] static bool IsHighResolution();
   1216 
   1217  // Returns true if TimeTicks is consistent across processes, meaning that
   1218  // timestamps taken on different processes can be safely compared with one
   1219  // another. (Note that, even on platforms where this returns true, time values
   1220  // from different threads that are within one tick of each other must be
   1221  // considered to have an ambiguous ordering.)
   1222  [[nodiscard]] static bool IsConsistentAcrossProcesses();
   1223 
   1224 #if BUILDFLAG(IS_FUCHSIA)
   1225  // Converts between TimeTicks and an ZX_CLOCK_MONOTONIC zx_time_t value.
   1226  static TimeTicks FromZxTime(zx_time_t nanos_since_boot);
   1227  zx_time_t ToZxTime() const;
   1228 #endif
   1229 
   1230 #if BUILDFLAG(IS_WIN)
   1231  // Translates an absolute QPC timestamp into a TimeTicks value. The returned
   1232  // value has the same origin as Now(). Do NOT attempt to use this if
   1233  // IsHighResolution() returns false.
   1234  static TimeTicks FromQPCValue(LONGLONG qpc_value);
   1235 #endif
   1236 
   1237 #if BUILDFLAG(IS_APPLE)
   1238  static TimeTicks FromMachAbsoluteTime(uint64_t mach_absolute_time);
   1239 
   1240  // Sets the current Mach timebase to `timebase`. Returns the old timebase.
   1241  static mach_timebase_info_data_t SetMachTimebaseInfoForTesting(
   1242      mach_timebase_info_data_t timebase);
   1243 
   1244 #endif  // BUILDFLAG(IS_APPLE)
   1245 
   1246 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH)
   1247  // Converts to TimeTicks the value obtained from SystemClock.uptimeMillis().
   1248  // Note: this conversion may be non-monotonic in relation to previously
   1249  // obtained TimeTicks::Now() values because of the truncation (to
   1250  // milliseconds) performed by uptimeMillis().
   1251  static TimeTicks FromUptimeMillis(int64_t uptime_millis_value);
   1252 
   1253 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH)
   1254 
   1255 #if BUILDFLAG(IS_ANDROID)
   1256  // Converts to TimeTicks the value obtained from System.nanoTime(). This
   1257  // conversion will be monotonic in relation to previously obtained
   1258  // TimeTicks::Now() values as the clocks are based on the same posix monotonic
   1259  // clock, with nanoTime() potentially providing higher resolution.
   1260  static TimeTicks FromJavaNanoTime(int64_t nano_time_value);
   1261 
   1262  // Truncates the TimeTicks value to the precision of SystemClock#uptimeMillis.
   1263  // Note that the clocks already share the same monotonic clock source.
   1264  jlong ToUptimeMillis() const;
   1265 
   1266  // Returns the TimeTicks value as microseconds in the timebase of
   1267  // SystemClock#uptimeMillis.
   1268  // Note that the clocks already share the same monotonic clock source.
   1269  //
   1270  // System.nanoTime() may be used to get sub-millisecond precision in Java code
   1271  // and may be compared against this value as the two share the same clock
   1272  // source (though be sure to convert nanos to micros).
   1273  jlong ToUptimeMicros() const;
   1274 
   1275 #endif  // BUILDFLAG(IS_ANDROID)
   1276 
   1277  // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
   1278  // Time and TimeTicks respond differently to user-set time and NTP
   1279  // adjustments, this number is only an estimate. Nevertheless, this can be
   1280  // useful when you need to relate the value of TimeTicks to a real time and
   1281  // date. Note: Upon first invocation, this function takes a snapshot of the
   1282  // realtime clock to establish a reference point.  This function will return
   1283  // the same value for the duration of the application, but will be different
   1284  // in future application runs.
   1285  static TimeTicks UnixEpoch();
   1286 
   1287  static void SetSharedUnixEpoch(TimeTicks);
   1288 
   1289  // Returns |this| snapped to the next tick, given a |tick_phase| and
   1290  // repeating |tick_interval| in both directions. |this| may be before,
   1291  // after, or equal to the |tick_phase|.
   1292  TimeTicks SnappedToNextTick(TimeTicks tick_phase,
   1293                              TimeDelta tick_interval) const;
   1294 
   1295  // Returns an enum indicating the underlying clock being used to generate
   1296  // TimeTicks timestamps. This function should only be used for debugging and
   1297  // logging purposes.
   1298  static Clock GetClock();
   1299 
   1300  // Converts an integer value representing TimeTicks to a class. This may be
   1301  // used when deserializing a |TimeTicks| structure, using a value known to be
   1302  // compatible. It is not provided as a constructor because the integer type
   1303  // may be unclear from the perspective of a caller.
   1304  //
   1305  // DEPRECATED - Do not use in new code. For deserializing TimeTicks values,
   1306  // prefer TimeTicks + TimeDelta(); however, be aware that the origin is not
   1307  // fixed and may vary. Serializing for persistence is strongly discouraged.
   1308  // http://crbug.com/634507
   1309  static constexpr TimeTicks FromInternalValue(int64_t us) {
   1310    return TimeTicks(us);
   1311  }
   1312 
   1313 protected:
   1314 #if BUILDFLAG(IS_WIN)
   1315  typedef DWORD (*TickFunctionType)(void);
   1316  static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
   1317 #endif
   1318 
   1319 private:
   1320  friend class time_internal::TimeBase<TimeTicks>;
   1321 
   1322  // Please use Now() to create a new object. This is for internal use
   1323  // and testing.
   1324  constexpr explicit TimeTicks(int64_t us) : TimeBase(us) {}
   1325 };
   1326 
   1327 // For logging use only.
   1328 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
   1329 
   1330 // LiveTicks ------------------------------------------------------------------
   1331 
   1332 // Behaves similarly to `TimeTicks` (a monotonically non-decreasing clock time)
   1333 // with the main difference being that `LiveTicks` is guaranteed not to advance
   1334 // while the system is suspended.
   1335 class BASE_EXPORT LiveTicks : public time_internal::TimeBase<LiveTicks> {
   1336 public:
   1337  constexpr LiveTicks() : TimeBase(0) {}
   1338  static LiveTicks Now();
   1339 
   1340 private:
   1341  friend class time_internal::TimeBase<LiveTicks>;
   1342 
   1343  // Please use Now() to create a new object. This is for internal use
   1344  // and testing.
   1345  constexpr explicit LiveTicks(int64_t us) : TimeBase(us) {}
   1346 };
   1347 
   1348 // ThreadTicks ----------------------------------------------------------------
   1349 
   1350 // Represents a clock, specific to a particular thread, than runs only while the
   1351 // thread is running.
   1352 class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
   1353 public:
   1354  constexpr ThreadTicks() : TimeBase(0) {}
   1355 
   1356  // Returns true if ThreadTicks::Now() is supported on this system.
   1357  [[nodiscard]] static bool IsSupported() {
   1358 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
   1359    BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_FUCHSIA)
   1360    return true;
   1361 #elif BUILDFLAG(IS_WIN)
   1362    return IsSupportedWin();
   1363 #else
   1364    return false;
   1365 #endif
   1366  }
   1367 
   1368  // Waits until the initialization is completed. Needs to be guarded with a
   1369  // call to IsSupported().
   1370  static void WaitUntilInitialized() {
   1371 #if BUILDFLAG(IS_WIN)
   1372    WaitUntilInitializedWin();
   1373 #endif
   1374  }
   1375 
   1376  // Returns thread-specific CPU-time on systems that support this feature.
   1377  // Needs to be guarded with a call to IsSupported(). Use this timer
   1378  // to (approximately) measure how much time the calling thread spent doing
   1379  // actual work vs. being de-scheduled. May return bogus results if the thread
   1380  // migrates to another CPU between two calls. Returns an empty ThreadTicks
   1381  // object until the initialization is completed. If a clock reading is
   1382  // absolutely needed, call WaitUntilInitialized() before this method.
   1383  static ThreadTicks Now();
   1384 
   1385 #if BUILDFLAG(IS_WIN)
   1386  // Similar to Now() above except this returns thread-specific CPU time for an
   1387  // arbitrary thread. All comments for Now() method above apply apply to this
   1388  // method as well.
   1389  static ThreadTicks GetForThread(const PlatformThreadHandle& thread_handle);
   1390 #endif
   1391 
   1392  // Converts an integer value representing ThreadTicks to a class. This may be
   1393  // used when deserializing a |ThreadTicks| structure, using a value known to
   1394  // be compatible. It is not provided as a constructor because the integer type
   1395  // may be unclear from the perspective of a caller.
   1396  //
   1397  // DEPRECATED - Do not use in new code. For deserializing ThreadTicks values,
   1398  // prefer ThreadTicks + TimeDelta(); however, be aware that the origin is not
   1399  // fixed and may vary. Serializing for persistence is strongly
   1400  // discouraged. http://crbug.com/634507
   1401  static constexpr ThreadTicks FromInternalValue(int64_t us) {
   1402    return ThreadTicks(us);
   1403  }
   1404 
   1405 private:
   1406  friend class time_internal::TimeBase<ThreadTicks>;
   1407 
   1408  // Please use Now() or GetForThread() to create a new object. This is for
   1409  // internal use and testing.
   1410  constexpr explicit ThreadTicks(int64_t us) : TimeBase(us) {}
   1411 
   1412 #if BUILDFLAG(IS_WIN)
   1413  [[nodiscard]] static bool IsSupportedWin();
   1414  static void WaitUntilInitializedWin();
   1415 #endif
   1416 };
   1417 
   1418 // For logging use only.
   1419 BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
   1420 
   1421 }  // namespace base
   1422 
   1423 #endif  // BASE_TIME_TIME_H_