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