Coverage Report

Created: 2023-06-07 07:13

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