forked from abseil/abseil-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.h
1815 lines (1683 loc) · 70.7 KB
/
time.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// -----------------------------------------------------------------------------
// File: time.h
// -----------------------------------------------------------------------------
//
// This header file defines abstractions for computing with absolute points
// in time, durations of time, and formatting and parsing time within a given
// time zone. The following abstractions are defined:
//
// * `absl::Time` defines an absolute, specific instance in time
// * `absl::Duration` defines a signed, fixed-length span of time
// * `absl::TimeZone` defines geopolitical time zone regions (as collected
// within the IANA Time Zone database (https://www.iana.org/time-zones)).
//
// Note: Absolute times are distinct from civil times, which refer to the
// human-scale time commonly represented by `YYYY-MM-DD hh:mm:ss`. The mapping
// between absolute and civil times can be specified by use of time zones
// (`absl::TimeZone` within this API). That is:
//
// Civil Time = F(Absolute Time, Time Zone)
// Absolute Time = G(Civil Time, Time Zone)
//
// See civil_time.h for abstractions related to constructing and manipulating
// civil time.
//
// Example:
//
// absl::TimeZone nyc;
// // LoadTimeZone() may fail so it's always better to check for success.
// if (!absl::LoadTimeZone("America/New_York", &nyc)) {
// // handle error case
// }
//
// // My flight leaves NYC on Jan 2, 2017 at 03:04:05
// absl::CivilSecond cs(2017, 1, 2, 3, 4, 5);
// absl::Time takeoff = absl::FromCivil(cs, nyc);
//
// absl::Duration flight_duration = absl::Hours(21) + absl::Minutes(35);
// absl::Time landing = takeoff + flight_duration;
//
// absl::TimeZone syd;
// if (!absl::LoadTimeZone("Australia/Sydney", &syd)) {
// // handle error case
// }
// std::string s = absl::FormatTime(
// "My flight will land in Sydney on %Y-%m-%d at %H:%M:%S",
// landing, syd);
#ifndef ABSL_TIME_TIME_H_
#define ABSL_TIME_TIME_H_
#if !defined(_MSC_VER)
#include <sys/time.h>
#else
// We don't include `winsock2.h` because it drags in `windows.h` and friends,
// and they define conflicting macros like OPAQUE, ERROR, and more. This has the
// potential to break Abseil users.
//
// Instead we only forward declare `timeval` and require Windows users include
// `winsock2.h` themselves. This is both inconsistent and troublesome, but so is
// including 'windows.h' so we are picking the lesser of two evils here.
struct timeval;
#endif
#include <chrono> // NOLINT(build/c++11)
#include <cmath>
#include <cstdint>
#include <ctime>
#include <limits>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "absl/time/civil_time.h"
#include "absl/time/internal/cctz/include/cctz/time_zone.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Duration; // Defined below
class Time; // Defined below
class TimeZone; // Defined below
namespace time_internal {
int64_t IDivDuration(bool satq, Duration num, Duration den, Duration* rem);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
uint32_t lo);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
int64_t lo);
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n);
constexpr int64_t kTicksPerNanosecond = 4;
constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond;
template <std::intmax_t N>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
std::ratio<1, N>);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
std::ratio<60>);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
std::ratio<3600>);
template <typename T>
using EnableIfIntegral = typename std::enable_if<
std::is_integral<T>::value || std::is_enum<T>::value, int>::type;
template <typename T>
using EnableIfFloat =
typename std::enable_if<std::is_floating_point<T>::value, int>::type;
} // namespace time_internal
// Duration
//
// The `absl::Duration` class represents a signed, fixed-length amount of time.
// A `Duration` is generated using a unit-specific factory function, or is
// the result of subtracting one `absl::Time` from another. Durations behave
// like unit-safe integers and they support all the natural integer-like
// arithmetic operations. Arithmetic overflows and saturates at +/- infinity.
// `Duration` should be passed by value rather than const reference.
//
// Factory functions `Nanoseconds()`, `Microseconds()`, `Milliseconds()`,
// `Seconds()`, `Minutes()`, `Hours()` and `InfiniteDuration()` allow for
// creation of constexpr `Duration` values
//
// Examples:
//
// constexpr absl::Duration ten_ns = absl::Nanoseconds(10);
// constexpr absl::Duration min = absl::Minutes(1);
// constexpr absl::Duration hour = absl::Hours(1);
// absl::Duration dur = 60 * min; // dur == hour
// absl::Duration half_sec = absl::Milliseconds(500);
// absl::Duration quarter_sec = 0.25 * absl::Seconds(1);
//
// `Duration` values can be easily converted to an integral number of units
// using the division operator.
//
// Example:
//
// constexpr absl::Duration dur = absl::Milliseconds(1500);
// int64_t ns = dur / absl::Nanoseconds(1); // ns == 1500000000
// int64_t ms = dur / absl::Milliseconds(1); // ms == 1500
// int64_t sec = dur / absl::Seconds(1); // sec == 1 (subseconds truncated)
// int64_t min = dur / absl::Minutes(1); // min == 0
//
// See the `IDivDuration()` and `FDivDuration()` functions below for details on
// how to access the fractional parts of the quotient.
//
// Alternatively, conversions can be performed using helpers such as
// `ToInt64Microseconds()` and `ToDoubleSeconds()`.
class Duration {
public:
// Value semantics.
constexpr Duration() : rep_hi_(0), rep_lo_(0) {} // zero-length duration
// Copyable.
#if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1930
// Explicitly defining the constexpr copy constructor avoids an MSVC bug.
constexpr Duration(const Duration& d)
: rep_hi_(d.rep_hi_), rep_lo_(d.rep_lo_) {}
#else
constexpr Duration(const Duration& d) = default;
#endif
Duration& operator=(const Duration& d) = default;
// Compound assignment operators.
Duration& operator+=(Duration d);
Duration& operator-=(Duration d);
Duration& operator*=(int64_t r);
Duration& operator*=(double r);
Duration& operator/=(int64_t r);
Duration& operator/=(double r);
Duration& operator%=(Duration rhs);
// Overloads that forward to either the int64_t or double overloads above.
// Integer operands must be representable as int64_t. Integer division is
// truncating, so values less than the resolution will be returned as zero.
// Floating-point multiplication and division is rounding (halfway cases
// rounding away from zero), so values less than the resolution may be
// returned as either the resolution or zero. In particular, `d / 2.0`
// can produce `d` when it is the resolution and "even".
template <typename T, time_internal::EnableIfIntegral<T> = 0>
Duration& operator*=(T r) {
int64_t x = r;
return *this *= x;
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
Duration& operator/=(T r) {
int64_t x = r;
return *this /= x;
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
Duration& operator*=(T r) {
double x = r;
return *this *= x;
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
Duration& operator/=(T r) {
double x = r;
return *this /= x;
}
template <typename H>
friend H AbslHashValue(H h, Duration d) {
return H::combine(std::move(h), d.rep_hi_.Get(), d.rep_lo_);
}
private:
friend constexpr int64_t time_internal::GetRepHi(Duration d);
friend constexpr uint32_t time_internal::GetRepLo(Duration d);
friend constexpr Duration time_internal::MakeDuration(int64_t hi,
uint32_t lo);
constexpr Duration(int64_t hi, uint32_t lo) : rep_hi_(hi), rep_lo_(lo) {}
// We store `rep_hi_` 4-byte rather than 8-byte aligned to avoid 4 bytes of
// tail padding.
class HiRep {
public:
// Default constructor default-initializes `hi_`, which has the same
// semantics as default-initializing an `int64_t` (undetermined value).
HiRep() = default;
HiRep(const HiRep&) = default;
HiRep& operator=(const HiRep&) = default;
explicit constexpr HiRep(const int64_t value)
: // C++17 forbids default-initialization in constexpr contexts. We can
// remove this in C++20.
#if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
hi_(0),
lo_(0)
#else
lo_(0),
hi_(0)
#endif
{
*this = value;
}
constexpr int64_t Get() const {
const uint64_t unsigned_value =
(static_cast<uint64_t>(hi_) << 32) | static_cast<uint64_t>(lo_);
// `static_cast<int64_t>(unsigned_value)` is implementation-defined
// before c++20. On all supported platforms the behaviour is that mandated
// by c++20, i.e. "If the destination type is signed, [...] the result is
// the unique value of the destination type equal to the source value
// modulo 2^n, where n is the number of bits used to represent the
// destination type."
static_assert(
(static_cast<int64_t>((std::numeric_limits<uint64_t>::max)()) ==
int64_t{-1}) &&
(static_cast<int64_t>(static_cast<uint64_t>(
(std::numeric_limits<int64_t>::max)()) +
1) ==
(std::numeric_limits<int64_t>::min)()),
"static_cast<int64_t>(uint64_t) does not have c++20 semantics");
return static_cast<int64_t>(unsigned_value);
}
constexpr HiRep& operator=(const int64_t value) {
// "If the destination type is unsigned, the resulting value is the
// smallest unsigned value equal to the source value modulo 2^n
// where `n` is the number of bits used to represent the destination
// type".
const auto unsigned_value = static_cast<uint64_t>(value);
hi_ = static_cast<uint32_t>(unsigned_value >> 32);
lo_ = static_cast<uint32_t>(unsigned_value);
return *this;
}
private:
// Notes:
// - Ideally we would use a `char[]` and `std::bitcast`, but the latter
// does not exist (and is not constexpr in `absl`) before c++20.
// - Order is optimized depending on endianness so that the compiler can
// turn `Get()` (resp. `operator=()`) into a single 8-byte load (resp.
// store).
#if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
uint32_t hi_;
uint32_t lo_;
#else
uint32_t lo_;
uint32_t hi_;
#endif
};
HiRep rep_hi_;
uint32_t rep_lo_;
};
// Relational Operators
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
Duration rhs);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Duration lhs,
Duration rhs) {
return rhs < lhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Duration lhs,
Duration rhs) {
return !(lhs < rhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Duration lhs,
Duration rhs) {
return !(rhs < lhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
Duration rhs);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Duration lhs,
Duration rhs) {
return !(lhs == rhs);
}
// Additive Operators
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator+(Duration lhs,
Duration rhs) {
return lhs += rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Duration lhs,
Duration rhs) {
return lhs -= rhs;
}
// Multiplicative Operators
// Integer operands must be representable as int64_t.
template <typename T>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(Duration lhs, T rhs) {
return lhs *= rhs;
}
template <typename T>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(T lhs, Duration rhs) {
return rhs *= lhs;
}
template <typename T>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator/(Duration lhs, T rhs) {
return lhs /= rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t operator/(Duration lhs,
Duration rhs) {
return time_internal::IDivDuration(true, lhs, rhs,
&lhs); // trunc towards zero
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator%(Duration lhs,
Duration rhs) {
return lhs %= rhs;
}
// IDivDuration()
//
// Divides a numerator `Duration` by a denominator `Duration`, returning the
// quotient and remainder. The remainder always has the same sign as the
// numerator. The returned quotient and remainder respect the identity:
//
// numerator = denominator * quotient + remainder
//
// Returned quotients are capped to the range of `int64_t`, with the difference
// spilling into the remainder to uphold the above identity. This means that the
// remainder returned could differ from the remainder returned by
// `Duration::operator%` for huge quotients.
//
// See also the notes on `InfiniteDuration()` below regarding the behavior of
// division involving zero and infinite durations.
//
// Example:
//
// constexpr absl::Duration a =
// absl::Seconds(std::numeric_limits<int64_t>::max()); // big
// constexpr absl::Duration b = absl::Nanoseconds(1); // small
//
// absl::Duration rem = a % b;
// // rem == absl::ZeroDuration()
//
// // Here, q would overflow int64_t, so rem accounts for the difference.
// int64_t q = absl::IDivDuration(a, b, &rem);
// // q == std::numeric_limits<int64_t>::max(), rem == a - b * q
inline int64_t IDivDuration(Duration num, Duration den, Duration* rem) {
return time_internal::IDivDuration(true, num, den,
rem); // trunc towards zero
}
// FDivDuration()
//
// Divides a `Duration` numerator into a fractional number of units of a
// `Duration` denominator.
//
// See also the notes on `InfiniteDuration()` below regarding the behavior of
// division involving zero and infinite durations.
//
// Example:
//
// double d = absl::FDivDuration(absl::Milliseconds(1500), absl::Seconds(1));
// // d == 1.5
ABSL_ATTRIBUTE_CONST_FUNCTION double FDivDuration(Duration num, Duration den);
// ZeroDuration()
//
// Returns a zero-length duration. This function behaves just like the default
// constructor, but the name helps make the semantics clear at call sites.
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ZeroDuration() {
return Duration();
}
// AbsDuration()
//
// Returns the absolute value of a duration.
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration AbsDuration(Duration d) {
return (d < ZeroDuration()) ? -d : d;
}
// Trunc()
//
// Truncates a duration (toward zero) to a multiple of a non-zero unit.
//
// Example:
//
// absl::Duration d = absl::Nanoseconds(123456789);
// absl::Duration a = absl::Trunc(d, absl::Microseconds(1)); // 123456us
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Trunc(Duration d, Duration unit);
// Floor()
//
// Floors a duration using the passed duration unit to its largest value not
// greater than the duration.
//
// Example:
//
// absl::Duration d = absl::Nanoseconds(123456789);
// absl::Duration b = absl::Floor(d, absl::Microseconds(1)); // 123456us
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Floor(Duration d, Duration unit);
// Ceil()
//
// Returns the ceiling of a duration using the passed duration unit to its
// smallest value not less than the duration.
//
// Example:
//
// absl::Duration d = absl::Nanoseconds(123456789);
// absl::Duration c = absl::Ceil(d, absl::Microseconds(1)); // 123457us
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Ceil(Duration d, Duration unit);
// InfiniteDuration()
//
// Returns an infinite `Duration`. To get a `Duration` representing negative
// infinity, use `-InfiniteDuration()`.
//
// Duration arithmetic overflows to +/- infinity and saturates. In general,
// arithmetic with `Duration` infinities is similar to IEEE 754 infinities
// except where IEEE 754 NaN would be involved, in which case +/-
// `InfiniteDuration()` is used in place of a "nan" Duration.
//
// Examples:
//
// constexpr absl::Duration inf = absl::InfiniteDuration();
// const absl::Duration d = ... any finite duration ...
//
// inf == inf + inf
// inf == inf + d
// inf == inf - inf
// -inf == d - inf
//
// inf == d * 1e100
// inf == inf / 2
// 0 == d / inf
// INT64_MAX == inf / d
//
// d < inf
// -inf < d
//
// // Division by zero returns infinity, or INT64_MIN/MAX where appropriate.
// inf == d / 0
// INT64_MAX == d / absl::ZeroDuration()
//
// The examples involving the `/` operator above also apply to `IDivDuration()`
// and `FDivDuration()`.
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration();
// Nanoseconds()
// Microseconds()
// Milliseconds()
// Seconds()
// Minutes()
// Hours()
//
// Factory functions for constructing `Duration` values from an integral number
// of the unit indicated by the factory function's name. The number must be
// representable as int64_t.
//
// NOTE: no "Days()" factory function exists because "a day" is ambiguous.
// Civil days are not always 24 hours long, and a 24-hour duration often does
// not correspond with a civil day. If a 24-hour duration is needed, use
// `absl::Hours(24)`. If you actually want a civil day, use absl::CivilDay
// from civil_time.h.
//
// Example:
//
// absl::Duration a = absl::Seconds(60);
// absl::Duration b = absl::Minutes(1); // b == a
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Nanoseconds(T n) {
return time_internal::FromInt64(n, std::nano{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Microseconds(T n) {
return time_internal::FromInt64(n, std::micro{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Milliseconds(T n) {
return time_internal::FromInt64(n, std::milli{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Seconds(T n) {
return time_internal::FromInt64(n, std::ratio<1>{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Minutes(T n) {
return time_internal::FromInt64(n, std::ratio<60>{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Hours(T n) {
return time_internal::FromInt64(n, std::ratio<3600>{});
}
// Factory overloads for constructing `Duration` values from a floating-point
// number of the unit indicated by the factory function's name. These functions
// exist for convenience, but they are not as efficient as the integral
// factories, which should be preferred.
//
// Example:
//
// auto a = absl::Seconds(1.5); // OK
// auto b = absl::Milliseconds(1500); // BETTER
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Nanoseconds(T n) {
return n * Nanoseconds(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Microseconds(T n) {
return n * Microseconds(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Milliseconds(T n) {
return n * Milliseconds(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Seconds(T n) {
if (n >= 0) { // Note: `NaN >= 0` is false.
if (n >= static_cast<T>((std::numeric_limits<int64_t>::max)())) {
return InfiniteDuration();
}
return time_internal::MakePosDoubleDuration(n);
} else {
if (std::isnan(n))
return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration();
if (n <= (std::numeric_limits<int64_t>::min)()) return -InfiniteDuration();
return -time_internal::MakePosDoubleDuration(-n);
}
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Minutes(T n) {
return n * Minutes(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Hours(T n) {
return n * Hours(1);
}
// ToInt64Nanoseconds()
// ToInt64Microseconds()
// ToInt64Milliseconds()
// ToInt64Seconds()
// ToInt64Minutes()
// ToInt64Hours()
//
// Helper functions that convert a Duration to an integral count of the
// indicated unit. These return the same results as the `IDivDuration()`
// function, though they usually do so more efficiently; see the
// documentation of `IDivDuration()` for details about overflow, etc.
//
// Example:
//
// absl::Duration d = absl::Milliseconds(1500);
// int64_t isec = absl::ToInt64Seconds(d); // isec == 1
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Nanoseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Microseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Milliseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Seconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Minutes(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Hours(Duration d);
// ToDoubleNanoseconds()
// ToDoubleMicroseconds()
// ToDoubleMilliseconds()
// ToDoubleSeconds()
// ToDoubleMinutes()
// ToDoubleHours()
//
// Helper functions that convert a Duration to a floating point count of the
// indicated unit. These functions are shorthand for the `FDivDuration()`
// function above; see its documentation for details about overflow, etc.
//
// Example:
//
// absl::Duration d = absl::Milliseconds(1500);
// double dsec = absl::ToDoubleSeconds(d); // dsec == 1.5
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleNanoseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMicroseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMilliseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleSeconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMinutes(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleHours(Duration d);
// FromChrono()
//
// Converts any of the pre-defined std::chrono durations to an absl::Duration.
//
// Example:
//
// std::chrono::milliseconds ms(123);
// absl::Duration d = absl::FromChrono(ms);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::nanoseconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::microseconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::milliseconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::seconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::minutes& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::hours& d);
// ToChronoNanoseconds()
// ToChronoMicroseconds()
// ToChronoMilliseconds()
// ToChronoSeconds()
// ToChronoMinutes()
// ToChronoHours()
//
// Converts an absl::Duration to any of the pre-defined std::chrono durations.
// If overflow would occur, the returned value will saturate at the min/max
// chrono duration value instead.
//
// Example:
//
// absl::Duration d = absl::Microseconds(123);
// auto x = absl::ToChronoMicroseconds(d);
// auto y = absl::ToChronoNanoseconds(d); // x == y
// auto z = absl::ToChronoSeconds(absl::InfiniteDuration());
// // z == std::chrono::seconds::max()
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::nanoseconds ToChronoNanoseconds(
Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::microseconds ToChronoMicroseconds(
Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::milliseconds ToChronoMilliseconds(
Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::seconds ToChronoSeconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::minutes ToChronoMinutes(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::hours ToChronoHours(Duration d);
// FormatDuration()
//
// Returns a string representing the duration in the form "72h3m0.5s".
// Returns "inf" or "-inf" for +/- `InfiniteDuration()`.
ABSL_ATTRIBUTE_CONST_FUNCTION std::string FormatDuration(Duration d);
// Output stream operator.
inline std::ostream& operator<<(std::ostream& os, Duration d) {
return os << FormatDuration(d);
}
// Support for StrFormat(), StrCat() etc.
template <typename Sink>
void AbslStringify(Sink& sink, Duration d) {
sink.Append(FormatDuration(d));
}
// ParseDuration()
//
// Parses a duration string consisting of a possibly signed sequence of
// decimal numbers, each with an optional fractional part and a unit
// suffix. The valid suffixes are "ns", "us" "ms", "s", "m", and "h".
// Simple examples include "300ms", "-1.5h", and "2h45m". Parses "0" as
// `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`.
bool ParseDuration(absl::string_view dur_string, Duration* d);
// AbslParseFlag()
//
// Parses a command-line flag string representation `text` into a Duration
// value. Duration flags must be specified in a format that is valid input for
// `absl::ParseDuration()`.
bool AbslParseFlag(absl::string_view text, Duration* dst, std::string* error);
// AbslUnparseFlag()
//
// Unparses a Duration value into a command-line string representation using
// the format specified by `absl::ParseDuration()`.
std::string AbslUnparseFlag(Duration d);
ABSL_DEPRECATED("Use AbslParseFlag() instead.")
bool ParseFlag(const std::string& text, Duration* dst, std::string* error);
ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
std::string UnparseFlag(Duration d);
// Time
//
// An `absl::Time` represents a specific instant in time. Arithmetic operators
// are provided for naturally expressing time calculations. Instances are
// created using `absl::Now()` and the `absl::From*()` factory functions that
// accept the gamut of other time representations. Formatting and parsing
// functions are provided for conversion to and from strings. `absl::Time`
// should be passed by value rather than const reference.
//
// `absl::Time` assumes there are 60 seconds in a minute, which means the
// underlying time scales must be "smeared" to eliminate leap seconds.
// See https://developers.google.com/time/smear.
//
// Even though `absl::Time` supports a wide range of timestamps, exercise
// caution when using values in the distant past. `absl::Time` uses the
// Proleptic Gregorian calendar, which extends the Gregorian calendar backward
// to dates before its introduction in 1582.
// See https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar
// for more information. Use the ICU calendar classes to convert a date in
// some other calendar (http://userguide.icu-project.org/datetime/calendar).
//
// Similarly, standardized time zones are a reasonably recent innovation, with
// the Greenwich prime meridian being established in 1884. The TZ database
// itself does not profess accurate offsets for timestamps prior to 1970. The
// breakdown of future timestamps is subject to the whim of regional
// governments.
//
// The `absl::Time` class represents an instant in time as a count of clock
// ticks of some granularity (resolution) from some starting point (epoch).
//
// `absl::Time` uses a resolution that is high enough to avoid loss in
// precision, and a range that is wide enough to avoid overflow, when
// converting between tick counts in most Google time scales (i.e., resolution
// of at least one nanosecond, and range +/-100 billion years). Conversions
// between the time scales are performed by truncating (towards negative
// infinity) to the nearest representable point.
//
// Examples:
//
// absl::Time t1 = ...;
// absl::Time t2 = t1 + absl::Minutes(2);
// absl::Duration d = t2 - t1; // == absl::Minutes(2)
//
class Time {
public:
// Value semantics.
// Returns the Unix epoch. However, those reading your code may not know
// or expect the Unix epoch as the default value, so make your code more
// readable by explicitly initializing all instances before use.
//
// Example:
// absl::Time t = absl::UnixEpoch();
// absl::Time t = absl::Now();
// absl::Time t = absl::TimeFromTimeval(tv);
// absl::Time t = absl::InfinitePast();
constexpr Time() = default;
// Copyable.
constexpr Time(const Time& t) = default;
Time& operator=(const Time& t) = default;
// Assignment operators.
Time& operator+=(Duration d) {
rep_ += d;
return *this;
}
Time& operator-=(Duration d) {
rep_ -= d;
return *this;
}
// Time::Breakdown
//
// The calendar and wall-clock (aka "civil time") components of an
// `absl::Time` in a certain `absl::TimeZone`. This struct is not
// intended to represent an instant in time. So, rather than passing
// a `Time::Breakdown` to a function, pass an `absl::Time` and an
// `absl::TimeZone`.
//
// Deprecated. Use `absl::TimeZone::CivilInfo`.
struct ABSL_DEPRECATED("Use `absl::TimeZone::CivilInfo`.") Breakdown {
int64_t year; // year (e.g., 2013)
int month; // month of year [1:12]
int day; // day of month [1:31]
int hour; // hour of day [0:23]
int minute; // minute of hour [0:59]
int second; // second of minute [0:59]
Duration subsecond; // [Seconds(0):Seconds(1)) if finite
int weekday; // 1==Mon, ..., 7=Sun
int yearday; // day of year [1:366]
// Note: The following fields exist for backward compatibility
// with older APIs. Accessing these fields directly is a sign of
// imprudent logic in the calling code. Modern time-related code
// should only access this data indirectly by way of FormatTime().
// These fields are undefined for InfiniteFuture() and InfinitePast().
int offset; // seconds east of UTC
bool is_dst; // is offset non-standard?
const char* zone_abbr; // time-zone abbreviation (e.g., "PST")
};
// Time::In()
//
// Returns the breakdown of this instant in the given TimeZone.
//
// Deprecated. Use `absl::TimeZone::At(Time)`.
ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
ABSL_DEPRECATED("Use `absl::TimeZone::At(Time)`.")
Breakdown In(TimeZone tz) const;
ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
template <typename H>
friend H AbslHashValue(H h, Time t) {
return H::combine(std::move(h), t.rep_);
}
private:
friend constexpr Time time_internal::FromUnixDuration(Duration d);
friend constexpr Duration time_internal::ToUnixDuration(Time t);
friend constexpr bool operator<(Time lhs, Time rhs);
friend constexpr bool operator==(Time lhs, Time rhs);
friend Duration operator-(Time lhs, Time rhs);
friend constexpr Time UniversalEpoch();
friend constexpr Time InfiniteFuture();
friend constexpr Time InfinitePast();
constexpr explicit Time(Duration rep) : rep_(rep) {}
Duration rep_;
};
// Relational Operators
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Time lhs, Time rhs) {
return lhs.rep_ < rhs.rep_;
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Time lhs, Time rhs) {
return rhs < lhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Time lhs, Time rhs) {
return !(lhs < rhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Time lhs, Time rhs) {
return !(rhs < lhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Time lhs, Time rhs) {
return lhs.rep_ == rhs.rep_;
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Time lhs, Time rhs) {
return !(lhs == rhs);
}
// Additive Operators
ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Time lhs, Duration rhs) {
return lhs += rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator+(Duration lhs, Time rhs) {
return rhs += lhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Time operator-(Time lhs, Duration rhs) {
return lhs -= rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Time lhs, Time rhs) {
return lhs.rep_ - rhs.rep_;
}
// UnixEpoch()
//
// Returns the `absl::Time` representing "1970-01-01 00:00:00.0 +0000".
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UnixEpoch() { return Time(); }
// UniversalEpoch()
//
// Returns the `absl::Time` representing "0001-01-01 00:00:00.0 +0000", the
// epoch of the ICU Universal Time Scale.
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time UniversalEpoch() {
// 719162 is the number of days from 0001-01-01 to 1970-01-01,
// assuming the Gregorian calendar.
return Time(
time_internal::MakeDuration(-24 * 719162 * int64_t{3600}, uint32_t{0}));
}
// InfiniteFuture()
//
// Returns an `absl::Time` that is infinitely far in the future.
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfiniteFuture() {
return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::max)(),
~uint32_t{0}));
}
// InfinitePast()
//
// Returns an `absl::Time` that is infinitely far in the past.
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time InfinitePast() {
return Time(time_internal::MakeDuration((std::numeric_limits<int64_t>::min)(),
~uint32_t{0}));
}
// FromUnixNanos()
// FromUnixMicros()
// FromUnixMillis()
// FromUnixSeconds()
// FromTimeT()
// FromUDate()
// FromUniversal()
//
// Creates an `absl::Time` from a variety of other representations. See
// https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixNanos(int64_t ns);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMicros(int64_t us);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixMillis(int64_t ms);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixSeconds(int64_t s);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromTimeT(time_t t);
ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUDate(double udate);
ABSL_ATTRIBUTE_CONST_FUNCTION Time FromUniversal(int64_t universal);
// ToUnixNanos()
// ToUnixMicros()
// ToUnixMillis()
// ToUnixSeconds()
// ToTimeT()
// ToUDate()
// ToUniversal()
//
// Converts an `absl::Time` to a variety of other representations. See
// https://unicode-org.github.io/icu/userguide/datetime/universaltimescale.html
//
// Note that these operations round down toward negative infinity where
// necessary to adjust to the resolution of the result type. Beware of
// possible time_t over/underflow in ToTime{T,val,spec}() on 32-bit platforms.
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixNanos(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMicros(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixMillis(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUnixSeconds(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION time_t ToTimeT(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToUDate(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToUniversal(Time t);
// DurationFromTimespec()
// DurationFromTimeval()
// ToTimespec()
// ToTimeval()
// TimeFromTimespec()
// TimeFromTimeval()
// ToTimespec()
// ToTimeval()
//
// Some APIs use a timespec or a timeval as a Duration (e.g., nanosleep(2)
// and select(2)), while others use them as a Time (e.g. clock_gettime(2)
// and gettimeofday(2)), so conversion functions are provided for both cases.
// The "to timespec/val" direction is easily handled via overloading, but
// for "from timespec/val" the desired type is part of the function name.
ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimespec(timespec ts);
ABSL_ATTRIBUTE_CONST_FUNCTION Duration DurationFromTimeval(timeval tv);
ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimespec(timespec ts);
ABSL_ATTRIBUTE_CONST_FUNCTION Time TimeFromTimeval(timeval tv);
ABSL_ATTRIBUTE_CONST_FUNCTION timespec ToTimespec(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION timeval ToTimeval(Time t);
// FromChrono()
//
// Converts a std::chrono::system_clock::time_point to an absl::Time.
//
// Example:
//
// auto tp = std::chrono::system_clock::from_time_t(123);
// absl::Time t = absl::FromChrono(tp);
// // t == absl::FromTimeT(123)
ABSL_ATTRIBUTE_PURE_FUNCTION Time
FromChrono(const std::chrono::system_clock::time_point& tp);
// ToChronoTime()
//
// Converts an absl::Time to a std::chrono::system_clock::time_point. If
// overflow would occur, the returned value will saturate at the min/max time
// point value instead.
//