From fcb104594b0bb4b8ac306cb2f55ecdad40974683 Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Tue, 4 Dec 2018 11:01:12 -0800 Subject: Creation of LTS branch "lts_2018_12_18" - 44b0fafc62d9b8f192e8180cbe9c4b806b339d57 Export of internal Abseil changes. by Abseil Team - 926bfeb9fff223429c12224b7514243886323e8d Export of internal Abseil changes. by Abseil Team - 13327debebc5c2d1d4991b69fe50450e340e50e4 Export of internal Abseil changes. by Abseil Team - 3088e76c597e068479e82508b1770a7ad0c806b6 Export of internal Abseil changes. by Abseil Team - f6ae816808cd913e0e2b3e2af14f328fa1071af0 Export of internal Abseil changes. by Abseil Team - a06c4a1d9093137b7217a5aaba8920d62e835dc0 Export of internal Abseil changes. by Abseil Team - 7b46e1d31a6b08b1c6da2a13e7b151a20446fa07 Export of internal Abseil changes. by Abseil Team - 070f6e47b33a2909d039e620c873204f78809492 Export of internal Abseil changes. by Abseil Team - 7990fd459e9339467814ddb95000c87cb1e4d945 Export of internal Abseil changes. by Abseil Team - f95179062eb65ce40895cc76f1398cce25394369 Export of internal Abseil changes. by Abseil Team - cc8dcd307b76a575d2e3e0958a4fe4c7193c2f68 Export of internal Abseil changes. by Abseil Team - a705aa78dc76fc5c79d501e61dcc077eca68a8a4 Merge pull request #194 from Mizux/windows by Xiaoyi Zhang - a4c3ffff11eec0ee45742f915c255e9f870b7e0f Export of internal Abseil changes. by Abseil Team - 01174578651b73021d9b8c3820f6fea707dacdf0 Merge pull request #201 from ccawley2011/fix-byteswap by Matt Calabrese <38107210+mattcalabrese-google@users.noreply.github.com> - f86f9413856b65afdd61fea938d684b8ab73115a Export of internal Abseil changes. by Abseil Team - 94c298e2a0ae409e283cab96c954a685bd865a70 Export of internal Abseil changes. by Abseil Team - 0884a6a04e4497d11b1b398cc0e422b118bf977a Export of internal Abseil changes. by Abseil Team - c16d5557cd05119b5b7b1318ef778ebe3195b4a1 Export of internal Abseil changes. by Abseil Team - 45221ccc4ed643e4209b0cc5798e97203f108fa8 Export of internal Abseil changes. by Abseil Team - 2019e17a520575ab365b2b5134d71068182c70b8 Export of internal Abseil changes. by Abseil Team - 5b70a8910b2e6fb0ce5193a41873139a126d2f7f Export of internal Abseil changes. by Abseil Team - a00bdd176d66ef0b417d9576052a19091fbdf891 Export of internal Abseil changes. by Abseil Team - f340f773edab951656b19b6f1a77c964a78ec4c2 Export of internal Abseil changes. by Abseil Team - 445998d7ac4e5d3c50411d377e3b50e960d2d6c2 Export of internal Abseil changes. by Abseil Team - e821380d69a549dc64900693942789d21aa4df5e Export of internal Abseil changes. by Abseil Team - f21d187b80e3b7f08fb279775ea9c8b48c636030 Export of internal Abseil changes. by Abseil Team - 5441bbe1db5d0f2ca24b5b60166367b0966790af Fix code snippet in comment (#174) by Loo Rong Jie - 5aae0cffae8ffaacab965756169b34e511b353df Fix CMake build (#173) by Stephan Dollberg - 48cd2c3f351ff188bc85684b84a91b6e6d17d896 Export of internal Abseil changes. by Abseil Team - e291c279e458761e77a69b09b129d3d1e81f1e80 Export of internal Abseil changes. by Abseil Team - e01d95528ea2137a4a27a88d1f57c6cb260aafed Export of internal Abseil changes. by Abseil Team - 8ff1374008259719b54a8cb128ef951c02da164c Export of internal Abseil changes. by Abseil Team - 02451914b9ad5320f81f56a89f3eef1f8683227c Export of internal Abseil changes. by Abseil Team - 921fd5cf02ec0d665439a790148d59faa7d4a72c Merge pull request #166 from rongjiecomputer/cmake-test by Gennadiy Civil - fb462224c058487763f263b7995d70efd0242c17 Export of internal Abseil changes. by Abseil Team - c075ad321696fa5072e097f0a51e4fe76a6fe13e Export of internal Abseil changes. by Abseil Team - 0f4bc966754ec6cd28d5f03467d56f1efdc598e3 Export of internal Abseil changes. by Abseil Team - 6c7e5ffc43decd92f7bdfc510ad8a245a20b6dea Export of internal Abseil changes. by Abseil Team - d6df769173bf0263489f98874b93034db0e479a2 Export of internal Abseil changes. by Abseil Team - 28080f5f050c9530aa9f2b39c60d8217038d64ff Export of internal Abseil changes. by Abseil Team - 9c987f429bba32fb4446280fd3b91e2472d71d4d Export of internal Abseil changes. by Abseil Team - 5e7d459eeca7bc53deab0ee9634601386b53d7c0 Export of internal Abseil changes. by Abseil Team - bed5bd6e185c7e0311f3a1f2dab4c96083dac636 Export of internal Abseil changes. by Abseil Team - fefc83638fb69395d259ed245699310610429064 Export of internal Abseil changes. by Abseil Team - d8cfe9f2a77fbee02c09642491e62a3f3677e0f6 Export of internal Abseil changes. by Abseil Team - ad5c960b2eb914881d1ceba0e996a0a8f3f6ca59 Export of internal Abseil changes. by Abseil Team - 86f0fe93ad9d6d033a319476736a3256369c1f75 Export of internal Abseil changes. by Abseil Team - f0f15c2778b0e4959244dd25e63f445a455870f5 Export of internal Abseil changes. by Abseil Team - 29ff6d4860070bf8fcbd39c8805d0c32d56628a3 Removed "warning treated as error" flag from MSVC (#153) by vocaviking - 083d04dd4a62ebbf037079b06e49b323c5e1192a Export of internal Abseil changes. by Abseil Team - bea85b52733022294eef108a2e42d77b616ddca2 Export of internal Abseil changes. by Abseil Team - 8f96be6ca60d967bd4b37f93d0a03bcff4145200 Export of internal Abseil changes. by Abseil Team - 92e07e5590752d6b8e67f7f2f86c6286561e8cea Merge pull request #152 from clnperez/fix-multi-defines-p... by Derek Mauro <761129+derekmauro@users.noreply.github.com> - 2125e6444a9de9e41f21ecdc674dd7d8759c149d Export of internal Abseil changes. by Abseil Team - 9acad869d21731f5bc50430a33fe61cc0ffcbb0b Merge pull request #150 from OlafvdSpek/patch-2 by Jonathan Cohen - c2e00d341913bf03b4597ade5b056042e23e8c58 Export of internal Abseil changes. by Abseil Team - 9e060686d1c325f34f9806b45fe77bafeed00aee Export of internal Abseil changes. by Abseil Team - 7aa411ceafc1272a28579cca739a97a2fb79055a Export of internal Abseil changes. by Abseil Team - 2c5af55ed34850d8b7dd46177c8ca53fdfda920e Export of internal Abseil changes. by Abseil Team - 44aa275286baf97fc13529aca547a88b180beb08 Merge pull request #143 from rongjiecomputer/kernel by Xiaoyi Zhang - 42f22a28401c952f1fc5942231c7fdac80811bf5 Export of internal Abseil changes. by Abseil Team - b973bc53ef366f0253b85eeed9a79b241884a843 Merge pull request #139 from siepkes/smartos-support by ahedberg - e0def7473e52336f58759e11db4cd9467e5e0356 Export of internal Abseil changes. by Abseil Team - f826f1d489b61b64df1d94afbe5981841a82e5fa Merge pull request #138 from edbaunton/remove-deprecated-... by ahedberg - 7b50a4a94b0c7df68b3a854c850b551aaef0a8b4 Export of internal Abseil changes. by Abseil Team - a5030ca5125b9d557ecfeea8acc8b1a8e49f6d27 Merge pull request #144 from rongjiecomputer/winsock2 by Xiaoyi Zhang - 02687955b7ca8fc02ada9b14bc247deeb108d341 Export of internal Abseil changes. by Abseil Team - 8f612ebb152fb7e05643a2bcf78cb89a8c0641ad Export of internal Abseil changes. by Abseil Team - 134496a31d8b324f762de3bee9a002658c984456 Export of internal Abseil changes. by Abseil Team - ba8d6cf07766263723e86736f20a51c1c9c67b19 Export of internal Abseil changes. by Abseil Team - be1e84b988fceabcea4fc9e93f899539f0c81901 Export of internal Abseil changes. by Abseil Team - 16ac2ec2e38cdf47f9330a312e319d57da659c10 Merge pull request #134 from rongjiecomputer/cmake by Alex Strelnikov - 7efd8dc0f1075356e9c7caa950afd1ecf854e8b9 Export of internal Abseil changes. by Abseil Team - 87a4c07856e7dc69958019d47b2f02ae47746ec0 Export of internal Abseil changes. by Abseil Team - 4491d606df34c44efda47b6d17b605262f17e182 Export of internal Abseil changes. by Abseil Team GitOrigin-RevId: 44b0fafc62d9b8f192e8180cbe9c4b806b339d57 Change-Id: I2c427b5b41b2d34101922048b00f3d9dafcb498d --- absl/time/time.h | 843 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 533 insertions(+), 310 deletions(-) (limited to 'absl/time/time.h') diff --git a/absl/time/time.h b/absl/time/time.h index 3b5739ff..3afec565 100644 --- a/absl/time/time.h +++ b/absl/time/time.h @@ -25,17 +25,29 @@ // * `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. +// // 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::Time takeoff = absl::FromDateTime(2017, 1, 2, 3, 4, 5, nyc); +// 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; // @@ -47,15 +59,17 @@ // "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(_WIN32) +#if !defined(_MSC_VER) #include #else #include #endif #include // NOLINT(build/c++11) +#include #include #include #include @@ -65,10 +79,11 @@ #include "absl/base/port.h" // Needed for string vs std::string #include "absl/strings/string_view.h" +#include "absl/time/civil_time.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" namespace absl { -inline namespace lts_2018_06_20 { +inline namespace lts_2018_12_18 { class Duration; // Defined below class Time; // Defined below @@ -82,6 +97,7 @@ constexpr int64_t GetRepHi(Duration d); constexpr uint32_t GetRepLo(Duration d); constexpr Duration MakeDuration(int64_t hi, uint32_t lo); constexpr Duration MakeDuration(int64_t hi, int64_t lo); +inline Duration MakePosDoubleDuration(double n); constexpr int64_t kTicksPerNanosecond = 4; constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond; template @@ -139,6 +155,16 @@ class Duration { // Value semantics. constexpr Duration() : rep_hi_(0), rep_lo_(0) {} // zero-length duration + // Copyable. +#if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1910 + // 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); @@ -162,6 +188,11 @@ class Duration { Duration& operator*=(float r) { return *this *= static_cast(r); } Duration& operator/=(float r) { return *this /= static_cast(r); } + template + friend H AbslHashValue(H h, Duration d) { + return H::combine(std::move(h), d.rep_hi_, d.rep_lo_); + } + private: friend constexpr int64_t time_internal::GetRepHi(Duration d); friend constexpr uint32_t time_internal::GetRepLo(Duration d); @@ -296,6 +327,42 @@ Duration Floor(Duration d, Duration unit); // absl::Duration c = absl::Ceil(d, absl::Microseconds(1)); // 123457us 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()`. +constexpr Duration InfiniteDuration(); + // Nanoseconds() // Microseconds() // Milliseconds() @@ -306,11 +373,11 @@ Duration Ceil(Duration d, Duration unit); // Factory functions for constructing `Duration` values from an integral number // of the unit indicated by the factory function's name. // -// 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)`. -// +// 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: // @@ -329,6 +396,7 @@ constexpr Duration Hours(int64_t n); // factories, which should be preferred. // // Example: +// // auto a = absl::Seconds(1.5); // OK // auto b = absl::Milliseconds(1500); // BETTER template = 0> @@ -345,7 +413,15 @@ Duration Milliseconds(T n) { } template = 0> Duration Seconds(T n) { - return n * Seconds(1); + if (n >= 0) { // Note: `NaN >= 0` is false. + if (n >= (std::numeric_limits::max)()) return InfiniteDuration(); + return time_internal::MakePosDoubleDuration(n); + } else { + if (std::isnan(n)) + return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration(); + if (n <= (std::numeric_limits::min)()) return -InfiniteDuration(); + return -time_internal::MakePosDoubleDuration(-n); + } } template = 0> Duration Minutes(T n) { @@ -440,42 +516,9 @@ std::chrono::seconds ToChronoSeconds(Duration d); std::chrono::minutes ToChronoMinutes(Duration d); std::chrono::hours ToChronoHours(Duration d); -// 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 -// -// // 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()`. -constexpr Duration InfiniteDuration(); - // FormatDuration() // -// Returns a std::string representing the duration in the form "72h3m0.5s". +// Returns a string representing the duration in the form "72h3m0.5s". // Returns "inf" or "-inf" for +/- `InfiniteDuration()`. std::string FormatDuration(Duration d); @@ -486,19 +529,16 @@ inline std::ostream& operator<<(std::ostream& os, Duration d) { // ParseDuration() // -// Parses a duration std::string consisting of a possibly signed sequence of +// 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()`. +// `ZeroDuration()`. Parses "inf" and "-inf" as +/- `InfiniteDuration()`. bool ParseDuration(const std::string& dur_string, Duration* d); -// ParseFlag() -// +// Support for flag values of type Duration. Duration flags must be specified +// in a format that is valid input for absl::ParseDuration(). bool ParseFlag(const std::string& text, Duration* dst, std::string* error); - -// UnparseFlag() -// std::string UnparseFlag(Duration d); // Time @@ -534,7 +574,7 @@ std::string UnparseFlag(Duration d); // // `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., precision +// 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. @@ -544,7 +584,6 @@ std::string UnparseFlag(Duration d); // absl::Time t1 = ...; // absl::Time t2 = t1 + absl::Minutes(2); // absl::Duration d = t2 - t1; // == absl::Minutes(2) -// absl::Time::Breakdown bd = t1.In(absl::LocalTimeZone()); // class Time { public: @@ -559,7 +598,11 @@ class Time { // absl::Time t = absl::Now(); // absl::Time t = absl::TimeFromTimeval(tv); // absl::Time t = absl::InfinitePast(); - constexpr Time() {} + constexpr Time() = default; + + // Copyable. + constexpr Time(const Time& t) = default; + Time& operator=(const Time& t) = default; // Assignment operators. Time& operator+=(Duration d) { @@ -578,7 +621,10 @@ class Time { // 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`. - struct Breakdown { + // + // Deprecated. Use `absl::TimeZone::CivilInfo`. + struct + Breakdown { int64_t year; // year (e.g., 2013) int month; // month of year [1:12] int day; // day of month [1:31] @@ -602,8 +648,15 @@ class Time { // Time::In() // // Returns the breakdown of this instant in the given TimeZone. + // + // Deprecated. Use `absl::TimeZone::At(Time)`. Breakdown In(TimeZone tz) const; + template + 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); @@ -651,7 +704,7 @@ constexpr Time UniversalEpoch() { // Returns an `absl::Time` that is infinitely far in the future. constexpr Time InfiniteFuture() { return Time( - time_internal::MakeDuration(std::numeric_limits::max(), ~0U)); + time_internal::MakeDuration((std::numeric_limits::max)(), ~0U)); } // InfinitePast() @@ -659,125 +712,9 @@ constexpr Time InfiniteFuture() { // Returns an `absl::Time` that is infinitely far in the past. constexpr Time InfinitePast() { return Time( - time_internal::MakeDuration(std::numeric_limits::min(), ~0U)); + time_internal::MakeDuration((std::numeric_limits::min)(), ~0U)); } -// TimeConversion -// -// An `absl::TimeConversion` represents the conversion of year, month, day, -// hour, minute, and second values (i.e., a civil time), in a particular -// `absl::TimeZone`, to a time instant (an absolute time), as returned by -// `absl::ConvertDateTime()`. (Subseconds must be handled separately.) -// -// It is possible, though, for a caller to try to convert values that -// do not represent an actual or unique instant in time (due to a shift -// in UTC offset in the `absl::TimeZone`, which results in a discontinuity in -// the civil-time components). For example, a daylight-saving-time -// transition skips or repeats civil times---in the United States, March -// 13, 2011 02:15 never occurred, while November 6, 2011 01:15 occurred -// twice---so requests for such times are not well-defined. -// -// To account for these possibilities, `absl::TimeConversion` is richer -// than just a single `absl::Time`. When the civil time is skipped or -// repeated, `absl::ConvertDateTime()` returns times calculated using the -// pre-transition and post-transition UTC offsets, plus the transition -// time itself. -// -// Examples: -// -// absl::TimeZone lax; -// if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) { ... } -// -// // A unique civil time -// absl::TimeConversion jan01 = -// absl::ConvertDateTime(2011, 1, 1, 0, 0, 0, lax); -// // jan01.kind == TimeConversion::UNIQUE -// // jan01.pre is 2011/01/01 00:00:00 -0800 -// // jan01.trans is 2011/01/01 00:00:00 -0800 -// // jan01.post is 2011/01/01 00:00:00 -0800 -// -// // A Spring DST transition, when there is a gap in civil time -// absl::TimeConversion mar13 = -// absl::ConvertDateTime(2011, 3, 13, 2, 15, 0, lax); -// // mar13.kind == TimeConversion::SKIPPED -// // mar13.pre is 2011/03/13 03:15:00 -0700 -// // mar13.trans is 2011/03/13 03:00:00 -0700 -// // mar13.post is 2011/03/13 01:15:00 -0800 -// -// // A Fall DST transition, when civil times are repeated -// absl::TimeConversion nov06 = -// absl::ConvertDateTime(2011, 11, 6, 1, 15, 0, lax); -// // nov06.kind == TimeConversion::REPEATED -// // nov06.pre is 2011/11/06 01:15:00 -0700 -// // nov06.trans is 2011/11/06 01:00:00 -0800 -// // nov06.post is 2011/11/06 01:15:00 -0800 -// -// The input month, day, hour, minute, and second values can also be -// outside of their valid ranges, in which case they will be "normalized" -// during the conversion. -// -// Example: -// -// // "October 32" normalizes to "November 1". -// absl::TimeZone tz = absl::LocalTimeZone(); -// absl::TimeConversion tc = -// absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, tz); -// // tc.kind == TimeConversion::UNIQUE && tc.normalized == true -// // tc.pre.In(tz).month == 11 && tc.pre.In(tz).day == 1 -struct TimeConversion { - Time pre; // time calculated using the pre-transition offset - Time trans; // when the civil-time discontinuity occurred - Time post; // time calculated using the post-transition offset - - enum Kind { - UNIQUE, // the civil time was singular (pre == trans == post) - SKIPPED, // the civil time did not exist - REPEATED, // the civil time was ambiguous - }; - Kind kind; - - bool normalized; // input values were outside their valid ranges -}; - -// ConvertDateTime() -// -// The full generality of a civil time to absl::Time conversion. -TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour, - int min, int sec, TimeZone tz); - -// FromDateTime() -// -// A convenience wrapper for `absl::ConvertDateTime()` that simply returns the -// "pre" `absl::Time`. That is, the unique result, or the instant that -// is correct using the pre-transition offset (as if the transition -// never happened). This is typically the answer that humans expected when -// faced with non-unique times, such as near daylight-saving time transitions. -// -// Example: -// -// absl::TimeZone seattle; -// if (!absl::LoadTimeZone("America/Los_Angeles", &seattle)) { ... } -// absl::Time t = absl::FromDateTime(2017, 9, 26, 9, 30, 0, seattle); -Time FromDateTime(int64_t year, int mon, int day, int hour, int min, int sec, - TimeZone tz); - -// FromTM() -// -// Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and -// `tm_sec` fields to an `absl::Time` using the given time zone. See ctime(3) -// for a description of the expected values of the tm fields. IFF the indicated -// time instant is not unique (see `absl::ConvertDateTime()` above), the -// `tm_isdst` field is consulted to select the desired instant (`tm_isdst` > 0 -// means DST, `tm_isdst` == 0 means no DST, `tm_isdst` < 0 means use the default -// like `absl::FromDateTime()`). -Time FromTM(const struct tm& tm, TimeZone tz); - -// ToTM() -// -// Converts the given `absl::Time` to a struct tm using the given time zone. -// See ctime(3) for a description of the values of the tm fields. -struct tm ToTM(Time t, TimeZone tz); - // FromUnixNanos() // FromUnixMicros() // FromUnixMillis() @@ -862,14 +799,390 @@ Time FromChrono(const std::chrono::system_clock::time_point& tp); // // tp == std::chrono::system_clock::from_time_t(123); std::chrono::system_clock::time_point ToChronoTime(Time); +// Support for flag values of type Time. Time flags must be specified in a +// format that matches absl::RFC3339_full. For example: +// +// --start_time=2016-01-02T03:04:05.678+08:00 +// +// Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required. +// +// Additionally, if you'd like to specify a time as a count of +// seconds/milliseconds/etc from the Unix epoch, use an absl::Duration flag +// and add that duration to absl::UnixEpoch() to get an absl::Time. +bool ParseFlag(const std::string& text, Time* t, std::string* error); +std::string UnparseFlag(Time t); + +// TimeZone +// +// The `absl::TimeZone` is an opaque, small, value-type class representing a +// geo-political region within which particular rules are used for converting +// between absolute and civil times (see https://git.io/v59Ly). `absl::TimeZone` +// values are named using the TZ identifiers from the IANA Time Zone Database, +// such as "America/Los_Angeles" or "Australia/Sydney". `absl::TimeZone` values +// are created from factory functions such as `absl::LoadTimeZone()`. Note: +// strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by +// value rather than const reference. +// +// For more on the fundamental concepts of time zones, absolute times, and civil +// times, see https://github.com/google/cctz#fundamental-concepts +// +// Examples: +// +// absl::TimeZone utc = absl::UTCTimeZone(); +// absl::TimeZone pst = absl::FixedTimeZone(-8 * 60 * 60); +// absl::TimeZone loc = absl::LocalTimeZone(); +// absl::TimeZone lax; +// if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) { +// // handle error case +// } +// +// See also: +// - https://github.com/google/cctz +// - http://www.iana.org/time-zones +// - http://en.wikipedia.org/wiki/Zoneinfo +class TimeZone { + public: + explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {} + TimeZone() = default; // UTC, but prefer UTCTimeZone() to be explicit. + + // Copyable. + TimeZone(const TimeZone&) = default; + TimeZone& operator=(const TimeZone&) = default; + + explicit operator time_internal::cctz::time_zone() const { return cz_; } + + std::string name() const { return cz_.name(); } + + // TimeZone::CivilInfo + // + // Information about the civil time corresponding to an absolute time. + // This struct is not intended to represent an instant in time. So, rather + // than passing a `TimeZone::CivilInfo` to a function, pass an `absl::Time` + // and an `absl::TimeZone`. + struct CivilInfo { + CivilSecond cs; + Duration subsecond; + + // 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") + }; + + // TimeZone::At(Time) + // + // Returns the civil time for this TimeZone at a certain `absl::Time`. + // If the input time is infinite, the output civil second will be set to + // CivilSecond::max() or min(), and the subsecond will be infinite. + // + // Example: + // + // const auto epoch = lax.At(absl::UnixEpoch()); + // // epoch.cs == 1969-12-31 16:00:00 + // // epoch.subsecond == absl::ZeroDuration() + // // epoch.offset == -28800 + // // epoch.is_dst == false + // // epoch.abbr == "PST" + CivilInfo At(Time t) const; + + // TimeZone::TimeInfo + // + // Information about the absolute times corresponding to a civil time. + // (Subseconds must be handled separately.) + // + // It is possible for a caller to pass a civil-time value that does + // not represent an actual or unique instant in time (due to a shift + // in UTC offset in the TimeZone, which results in a discontinuity in + // the civil-time components). For example, a daylight-saving-time + // transition skips or repeats civil times---in the United States, + // March 13, 2011 02:15 never occurred, while November 6, 2011 01:15 + // occurred twice---so requests for such times are not well-defined. + // To account for these possibilities, `absl::TimeZone::TimeInfo` is + // richer than just a single `absl::Time`. + struct TimeInfo { + enum CivilKind { + UNIQUE, // the civil time was singular (pre == trans == post) + SKIPPED, // the civil time did not exist (pre >= trans > post) + REPEATED, // the civil time was ambiguous (pre < trans <= post) + } kind; + Time pre; // time calculated using the pre-transition offset + Time trans; // when the civil-time discontinuity occurred + Time post; // time calculated using the post-transition offset + }; + + // TimeZone::At(CivilSecond) + // + // Returns an `absl::TimeInfo` containing the absolute time(s) for this + // TimeZone at an `absl::CivilSecond`. When the civil time is skipped or + // repeated, returns times calculated using the pre-transition and post- + // transition UTC offsets, plus the transition time itself. + // + // Examples: + // + // // A unique civil time + // const auto jan01 = lax.At(absl::CivilSecond(2011, 1, 1, 0, 0, 0)); + // // jan01.kind == TimeZone::TimeInfo::UNIQUE + // // jan01.pre is 2011-01-01 00:00:00 -0800 + // // jan01.trans is 2011-01-01 00:00:00 -0800 + // // jan01.post is 2011-01-01 00:00:00 -0800 + // + // // A Spring DST transition, when there is a gap in civil time + // const auto mar13 = lax.At(absl::CivilSecond(2011, 3, 13, 2, 15, 0)); + // // mar13.kind == TimeZone::TimeInfo::SKIPPED + // // mar13.pre is 2011-03-13 03:15:00 -0700 + // // mar13.trans is 2011-03-13 03:00:00 -0700 + // // mar13.post is 2011-03-13 01:15:00 -0800 + // + // // A Fall DST transition, when civil times are repeated + // const auto nov06 = lax.At(absl::CivilSecond(2011, 11, 6, 1, 15, 0)); + // // nov06.kind == TimeZone::TimeInfo::REPEATED + // // nov06.pre is 2011-11-06 01:15:00 -0700 + // // nov06.trans is 2011-11-06 01:00:00 -0800 + // // nov06.post is 2011-11-06 01:15:00 -0800 + TimeInfo At(CivilSecond ct) const; + + // TimeZone::NextTransition() + // TimeZone::PrevTransition() + // + // Finds the time of the next/previous offset change in this time zone. + // + // By definition, `NextTransition(t, &trans)` returns false when `t` is + // `InfiniteFuture()`, and `PrevTransition(t, &trans)` returns false + // when `t` is `InfinitePast()`. If the zone has no transitions, the + // result will also be false no matter what the argument. + // + // Otherwise, when `t` is `InfinitePast()`, `NextTransition(t, &trans)` + // returns true and sets `trans` to the first recorded transition. Chains + // of calls to `NextTransition()/PrevTransition()` will eventually return + // false, but it is unspecified exactly when `NextTransition(t, &trans)` + // jumps to false, or what time is set by `PrevTransition(t, &trans)` for + // a very distant `t`. + // + // Note: Enumeration of time-zone transitions is for informational purposes + // only. Modern time-related code should not care about when offset changes + // occur. + // + // Example: + // absl::TimeZone nyc; + // if (!absl::LoadTimeZone("America/New_York", &nyc)) { ... } + // const auto now = absl::Now(); + // auto t = absl::InfinitePast(); + // absl::TimeZone::CivilTransition trans; + // while (t <= now && nyc.NextTransition(t, &trans)) { + // // transition: trans.from -> trans.to + // t = nyc.At(trans.to).trans; + // } + struct CivilTransition { + CivilSecond from; // the civil time we jump from + CivilSecond to; // the civil time we jump to + }; + bool NextTransition(Time t, CivilTransition* trans) const; + bool PrevTransition(Time t, CivilTransition* trans) const; + + template + friend H AbslHashValue(H h, TimeZone tz) { + return H::combine(std::move(h), tz.cz_); + } + + private: + friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; } + friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; } + friend std::ostream& operator<<(std::ostream& os, TimeZone tz) { + return os << tz.name(); + } + + time_internal::cctz::time_zone cz_; +}; + +// LoadTimeZone() +// +// Loads the named zone. May perform I/O on the initial load of the named +// zone. If the name is invalid, or some other kind of error occurs, returns +// `false` and `*tz` is set to the UTC time zone. +inline bool LoadTimeZone(const std::string& name, TimeZone* tz) { + if (name == "localtime") { + *tz = TimeZone(time_internal::cctz::local_time_zone()); + return true; + } + time_internal::cctz::time_zone cz; + const bool b = time_internal::cctz::load_time_zone(name, &cz); + *tz = TimeZone(cz); + return b; +} + +// FixedTimeZone() +// +// Returns a TimeZone that is a fixed offset (seconds east) from UTC. +// Note: If the absolute value of the offset is greater than 24 hours +// you'll get UTC (i.e., no offset) instead. +inline TimeZone FixedTimeZone(int seconds) { + return TimeZone( + time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds))); +} + +// UTCTimeZone() +// +// Convenience method returning the UTC time zone. +inline TimeZone UTCTimeZone() { + return TimeZone(time_internal::cctz::utc_time_zone()); +} + +// LocalTimeZone() +// +// Convenience method returning the local time zone, or UTC if there is +// no configured local zone. Warning: Be wary of using LocalTimeZone(), +// and particularly so in a server process, as the zone configured for the +// local machine should be irrelevant. Prefer an explicit zone name. +inline TimeZone LocalTimeZone() { + return TimeZone(time_internal::cctz::local_time_zone()); +} + +// ToCivilSecond() +// ToCivilMinute() +// ToCivilHour() +// ToCivilDay() +// ToCivilMonth() +// ToCivilYear() +// +// Helpers for TimeZone::At(Time) to return particularly aligned civil times. +// +// Example: +// +// absl::Time t = ...; +// absl::TimeZone tz = ...; +// const auto cd = absl::ToCivilDay(t, tz); +inline CivilSecond ToCivilSecond(Time t, TimeZone tz) { + return tz.At(t).cs; // already a CivilSecond +} +inline CivilMinute ToCivilMinute(Time t, TimeZone tz) { + return CivilMinute(tz.At(t).cs); +} +inline CivilHour ToCivilHour(Time t, TimeZone tz) { + return CivilHour(tz.At(t).cs); +} +inline CivilDay ToCivilDay(Time t, TimeZone tz) { + return CivilDay(tz.At(t).cs); +} +inline CivilMonth ToCivilMonth(Time t, TimeZone tz) { + return CivilMonth(tz.At(t).cs); +} +inline CivilYear ToCivilYear(Time t, TimeZone tz) { + return CivilYear(tz.At(t).cs); +} + +// FromCivil() +// +// Helper for TimeZone::At(CivilSecond) that provides "order-preserving +// semantics." If the civil time maps to a unique time, that time is +// returned. If the civil time is repeated in the given time zone, the +// time using the pre-transition offset is returned. Otherwise, the +// civil time is skipped in the given time zone, and the transition time +// is returned. This means that for any two civil times, ct1 and ct2, +// (ct1 < ct2) => (FromCivil(ct1) <= FromCivil(ct2)), the equal case +// being when two non-existent civil times map to the same transition time. +// +// Note: Accepts civil times of any alignment. +inline Time FromCivil(CivilSecond ct, TimeZone tz) { + const auto ti = tz.At(ct); + if (ti.kind == TimeZone::TimeInfo::SKIPPED) return ti.trans; + return ti.pre; +} + +// TimeConversion +// +// An `absl::TimeConversion` represents the conversion of year, month, day, +// hour, minute, and second values (i.e., a civil time), in a particular +// `absl::TimeZone`, to a time instant (an absolute time), as returned by +// `absl::ConvertDateTime()`. Lecacy version of `absl::TimeZone::TimeInfo`. +// +// Deprecated. Use `absl::TimeZone::TimeInfo`. +struct + TimeConversion { + Time pre; // time calculated using the pre-transition offset + Time trans; // when the civil-time discontinuity occurred + Time post; // time calculated using the post-transition offset + + enum Kind { + UNIQUE, // the civil time was singular (pre == trans == post) + SKIPPED, // the civil time did not exist + REPEATED, // the civil time was ambiguous + }; + Kind kind; + + bool normalized; // input values were outside their valid ranges +}; + +// ConvertDateTime() +// +// Legacy version of `absl::TimeZone::At(absl::CivilSecond)` that takes +// the civil time as six, separate values (YMDHMS). +// +// The input month, day, hour, minute, and second values can be outside +// of their valid ranges, in which case they will be "normalized" during +// the conversion. +// +// Example: +// +// // "October 32" normalizes to "November 1". +// absl::TimeConversion tc = +// absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, lax); +// // tc.kind == TimeConversion::UNIQUE && tc.normalized == true +// // absl::ToCivilDay(tc.pre, tz).month() == 11 +// // absl::ToCivilDay(tc.pre, tz).day() == 1 +// +// Deprecated. Use `absl::TimeZone::At(CivilSecond)`. +TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour, + int min, int sec, TimeZone tz); + +// FromDateTime() +// +// A convenience wrapper for `absl::ConvertDateTime()` that simply returns +// the "pre" `absl::Time`. That is, the unique result, or the instant that +// is correct using the pre-transition offset (as if the transition never +// happened). +// +// Example: +// +// absl::Time t = absl::FromDateTime(2017, 9, 26, 9, 30, 0, lax); +// // t = 2017-09-26 09:30:00 -0700 +// +// Deprecated. Use `absl::TimeZone::At(CivilSecond).pre`. +inline Time FromDateTime(int64_t year, int mon, int day, int hour, + int min, int sec, TimeZone tz) { + return ConvertDateTime(year, mon, day, hour, min, sec, tz).pre; +} + +// FromTM() +// +// Converts the `tm_year`, `tm_mon`, `tm_mday`, `tm_hour`, `tm_min`, and +// `tm_sec` fields to an `absl::Time` using the given time zone. See ctime(3) +// for a description of the expected values of the tm fields. If the indicated +// time instant is not unique (see `absl::TimeZone::At(absl::CivilSecond)` +// above), the `tm_isdst` field is consulted to select the desired instant +// (`tm_isdst` > 0 means DST, `tm_isdst` == 0 means no DST, `tm_isdst` < 0 +// means use the post-transition offset). +Time FromTM(const struct tm& tm, TimeZone tz); + +// ToTM() +// +// Converts the given `absl::Time` to a struct tm using the given time zone. +// See ctime(3) for a description of the values of the tm fields. +struct tm ToTM(Time t, TimeZone tz); + // RFC3339_full // RFC3339_sec // // FormatTime()/ParseTime() format specifiers for RFC3339 date/time strings, // with trailing zeros trimmed or with fractional seconds omitted altogether. // -// Note that RFC3339_sec[] matches an ISO 8601 extended format for date -// and time with UTC offset. +// Note that RFC3339_sec[] matches an ISO 8601 extended format for date and +// time with UTC offset. Also note the use of "%Y": RFC3339 mandates that +// years have exactly four digits, but we allow them to take their natural +// width. extern const char RFC3339_full[]; // %Y-%m-%dT%H:%M:%E*S%Ez extern const char RFC3339_sec[]; // %Y-%m-%dT%H:%M:%S%Ez @@ -883,7 +1196,7 @@ extern const char RFC1123_no_wday[]; // %d %b %E4Y %H:%M:%S %z // FormatTime() // // Formats the given `absl::Time` in the `absl::TimeZone` according to the -// provided format std::string. Uses strftime()-like formatting options, with +// provided format string. Uses strftime()-like formatting options, with // the following extensions: // // - %Ez - RFC3339-compatible numeric UTC offset (+hh:mm or -hh:mm) @@ -906,17 +1219,15 @@ extern const char RFC1123_no_wday[]; // %d %b %E4Y %H:%M:%S %z // // Example: // -// absl::TimeZone lax; -// if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) { ... } -// absl::Time t = absl::FromDateTime(2013, 1, 2, 3, 4, 5, lax); -// -// std::string f = absl::FormatTime("%H:%M:%S", t, lax); // "03:04:05" +// absl::CivilSecond cs(2013, 1, 2, 3, 4, 5); +// absl::Time t = absl::FromCivil(cs, lax); +// string f = absl::FormatTime("%H:%M:%S", t, lax); // "03:04:05" // f = absl::FormatTime("%H:%M:%E3S", t, lax); // "03:04:05.000" // // Note: If the given `absl::Time` is `absl::InfiniteFuture()`, the returned -// std::string will be exactly "infinite-future". If the given `absl::Time` is -// `absl::InfinitePast()`, the returned std::string will be exactly "infinite-past". -// In both cases the given format std::string and `absl::TimeZone` are ignored. +// string will be exactly "infinite-future". If the given `absl::Time` is +// `absl::InfinitePast()`, the returned string will be exactly "infinite-past". +// In both cases the given format string and `absl::TimeZone` are ignored. // std::string FormatTime(const std::string& format, Time t, TimeZone tz); @@ -933,7 +1244,7 @@ inline std::ostream& operator<<(std::ostream& os, Time t) { // ParseTime() // -// Parses an input std::string according to the provided format std::string and +// Parses an input string according to the provided format string and // returns the corresponding `absl::Time`. Uses strftime()-like formatting // options, with the same extensions as FormatTime(), but with the // exceptions that %E#S is interpreted as %E*S, and %E#f as %E*f. %Ez @@ -947,7 +1258,7 @@ inline std::ostream& operator<<(std::ostream& os, Time t) { // // "1970-01-01 00:00:00.0 +0000" // -// For example, parsing a std::string of "15:45" (%H:%M) will return an absl::Time +// For example, parsing a string of "15:45" (%H:%M) will return an absl::Time // that represents "1970-01-01 15:45:00.0 +0000". // // Note that since ParseTime() returns time instants, it makes the most sense @@ -960,7 +1271,7 @@ inline std::ostream& operator<<(std::ostream& os, Time t) { // in the conversion. // // Date and time fields that are out-of-range will be treated as errors -// rather than normalizing them like `absl::FromDateTime()` does. For example, +// rather than normalizing them like `absl::CivilSecond` does. For example, // it is an error to parse the date "Oct 32, 2013" because 32 is out of range. // // A leap second of ":60" is normalized to ":00" of the following minute @@ -974,130 +1285,24 @@ inline std::ostream& operator<<(std::ostream& os, Time t) { // Errors are indicated by returning false and assigning an error message // to the "err" out param if it is non-null. // -// Note: If the input std::string is exactly "infinite-future", the returned +// Note: If the input string is exactly "infinite-future", the returned // `absl::Time` will be `absl::InfiniteFuture()` and `true` will be returned. -// If the input std::string is "infinite-past", the returned `absl::Time` will be +// If the input string is "infinite-past", the returned `absl::Time` will be // `absl::InfinitePast()` and `true` will be returned. // bool ParseTime(const std::string& format, const std::string& input, Time* time, std::string* err); -// Like ParseTime() above, but if the format std::string does not contain a UTC +// Like ParseTime() above, but if the format string does not contain a UTC // offset specification (%z/%Ez/%E*z) then the input is interpreted in the // given TimeZone. This means that the input, by itself, does not identify a // unique instant. Being time-zone dependent, it also admits the possibility // of ambiguity or non-existence, in which case the "pre" time (as defined -// for ConvertDateTime()) is returned. For these reasons we recommend that +// by TimeZone::TimeInfo) is returned. For these reasons we recommend that // all date/time strings include a UTC offset so they're context independent. bool ParseTime(const std::string& format, const std::string& input, TimeZone tz, Time* time, std::string* err); -// ParseFlag() -// UnparseFlag() -// -// Support for flag values of type Time. Time flags must be specified in a -// format that matches absl::RFC3339_full. For example: -// -// --start_time=2016-01-02T03:04:05.678+08:00 -// -// Note: A UTC offset (or 'Z' indicating a zero-offset from UTC) is required. -// -// Additionally, if you'd like to specify a time as a count of -// seconds/milliseconds/etc from the Unix epoch, use an absl::Duration flag -// and add that duration to absl::UnixEpoch() to get an absl::Time. -bool ParseFlag(const std::string& text, Time* t, std::string* error); -std::string UnparseFlag(Time t); - -// TimeZone -// -// The `absl::TimeZone` is an opaque, small, value-type class representing a -// geo-political region within which particular rules are used for converting -// between absolute and civil times (see https://git.io/v59Ly). `absl::TimeZone` -// values are named using the TZ identifiers from the IANA Time Zone Database, -// such as "America/Los_Angeles" or "Australia/Sydney". `absl::TimeZone` values -// are created from factory functions such as `absl::LoadTimeZone()`. Note: -// strings like "PST" and "EDT" are not valid TZ identifiers. Prefer to pass by -// value rather than const reference. -// -// For more on the fundamental concepts of time zones, absolute times, and civil -// times, see https://github.com/google/cctz#fundamental-concepts -// -// Examples: -// -// absl::TimeZone utc = absl::UTCTimeZone(); -// absl::TimeZone pst = absl::FixedTimeZone(-8 * 60 * 60); -// absl::TimeZone loc = absl::LocalTimeZone(); -// absl::TimeZone lax; -// if (!absl::LoadTimeZone("America/Los_Angeles", &lax)) { ... } -// -// See also: -// - https://github.com/google/cctz -// - http://www.iana.org/time-zones -// - http://en.wikipedia.org/wiki/Zoneinfo -class TimeZone { - public: - explicit TimeZone(time_internal::cctz::time_zone tz) : cz_(tz) {} - TimeZone() = default; // UTC, but prefer UTCTimeZone() to be explicit. - TimeZone(const TimeZone&) = default; - TimeZone& operator=(const TimeZone&) = default; - - explicit operator time_internal::cctz::time_zone() const { return cz_; } - - std::string name() const { return cz_.name(); } - - private: - friend bool operator==(TimeZone a, TimeZone b) { return a.cz_ == b.cz_; } - friend bool operator!=(TimeZone a, TimeZone b) { return a.cz_ != b.cz_; } - friend std::ostream& operator<<(std::ostream& os, TimeZone tz) { - return os << tz.name(); - } - - time_internal::cctz::time_zone cz_; -}; - -// LoadTimeZone() -// -// Loads the named zone. May perform I/O on the initial load of the named -// zone. If the name is invalid, or some other kind of error occurs, returns -// `false` and `*tz` is set to the UTC time zone. -inline bool LoadTimeZone(const std::string& name, TimeZone* tz) { - if (name == "localtime") { - *tz = TimeZone(time_internal::cctz::local_time_zone()); - return true; - } - time_internal::cctz::time_zone cz; - const bool b = time_internal::cctz::load_time_zone(name, &cz); - *tz = TimeZone(cz); - return b; -} - -// FixedTimeZone() -// -// Returns a TimeZone that is a fixed offset (seconds east) from UTC. -// Note: If the absolute value of the offset is greater than 24 hours -// you'll get UTC (i.e., no offset) instead. -inline TimeZone FixedTimeZone(int seconds) { - return TimeZone( - time_internal::cctz::fixed_time_zone(std::chrono::seconds(seconds))); -} - -// UTCTimeZone() -// -// Convenience method returning the UTC time zone. -inline TimeZone UTCTimeZone() { - return TimeZone(time_internal::cctz::utc_time_zone()); -} - -// LocalTimeZone() -// -// Convenience method returning the local time zone, or UTC if there is -// no configured local zone. Warning: Be wary of using LocalTimeZone(), -// and particularly so in a server process, as the zone configured for the -// local machine should be irrelevant. Prefer an explicit zone name. -inline TimeZone LocalTimeZone() { - return TimeZone(time_internal::cctz::local_time_zone()); -} - // ============================================================================ // Implementation Details Follow // ============================================================================ @@ -1115,6 +1320,18 @@ constexpr Duration MakeDuration(int64_t hi, int64_t lo) { return MakeDuration(hi, static_cast(lo)); } +// Make a Duration value from a floating-point number, as long as that number +// is in the range [ 0 .. numeric_limits::max ), that is, as long as +// it's positive and can be converted to int64_t without risk of UB. +inline Duration MakePosDoubleDuration(double n) { + const int64_t int_secs = static_cast(n); + const uint32_t ticks = + static_cast((n - int_secs) * kTicksPerSecond + 0.5); + return ticks < kTicksPerSecond + ? MakeDuration(int_secs, ticks) + : MakeDuration(int_secs + 1, ticks - kTicksPerSecond); +} + // Creates a normalized Duration from an almost-normalized (sec,ticks) // pair. sec may be positive or negative. ticks must be in the range // -kTicksPerSecond < *ticks < kTicksPerSecond. If ticks is negative it @@ -1123,17 +1340,20 @@ constexpr Duration MakeNormalizedDuration(int64_t sec, int64_t ticks) { return (ticks < 0) ? MakeDuration(sec - 1, ticks + kTicksPerSecond) : MakeDuration(sec, ticks); } + // Provide access to the Duration representation. constexpr int64_t GetRepHi(Duration d) { return d.rep_hi_; } constexpr uint32_t GetRepLo(Duration d) { return d.rep_lo_; } + +// Returns true iff d is positive or negative infinity. constexpr bool IsInfiniteDuration(Duration d) { return GetRepLo(d) == ~0U; } // Returns an infinite Duration with the opposite sign. // REQUIRES: IsInfiniteDuration(d) constexpr Duration OppositeInfinity(Duration d) { return GetRepHi(d) < 0 - ? MakeDuration(std::numeric_limits::max(), ~0U) - : MakeDuration(std::numeric_limits::min(), ~0U); + ? MakeDuration((std::numeric_limits::max)(), ~0U) + : MakeDuration((std::numeric_limits::min)(), ~0U); } // Returns (-n)-1 (equivalently -(n+1)) without avoidable overflow. @@ -1158,14 +1378,14 @@ constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) { v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N); } constexpr Duration FromInt64(int64_t v, std::ratio<60>) { - return (v <= std::numeric_limits::max() / 60 && - v >= std::numeric_limits::min() / 60) + return (v <= (std::numeric_limits::max)() / 60 && + v >= (std::numeric_limits::min)() / 60) ? MakeDuration(v * 60) : v > 0 ? InfiniteDuration() : -InfiniteDuration(); } constexpr Duration FromInt64(int64_t v, std::ratio<3600>) { - return (v <= std::numeric_limits::max() / 3600 && - v >= std::numeric_limits::min() / 3600) + return (v <= (std::numeric_limits::max)() / 3600 && + v >= (std::numeric_limits::min)() / 3600) ? MakeDuration(v * 3600) : v > 0 ? InfiniteDuration() : -InfiniteDuration(); } @@ -1224,8 +1444,8 @@ T ToChronoDuration(Duration d) { if (time_internal::IsInfiniteDuration(d)) return d < ZeroDuration() ? T::min() : T::max(); const auto v = ToInt64(d, Period{}); - if (v > std::numeric_limits::max()) return T::max(); - if (v < std::numeric_limits::min()) return T::min(); + if (v > (std::numeric_limits::max)()) return T::max(); + if (v < (std::numeric_limits::min)()) return T::min(); return T{v}; } @@ -1252,7 +1472,8 @@ constexpr Duration Hours(int64_t n) { constexpr bool operator<(Duration lhs, Duration rhs) { return time_internal::GetRepHi(lhs) != time_internal::GetRepHi(rhs) ? time_internal::GetRepHi(lhs) < time_internal::GetRepHi(rhs) - : time_internal::GetRepHi(lhs) == std::numeric_limits::min() + : time_internal::GetRepHi(lhs) == + (std::numeric_limits::min)() ? time_internal::GetRepLo(lhs) + 1 < time_internal::GetRepLo(rhs) + 1 : time_internal::GetRepLo(lhs) < @@ -1277,7 +1498,8 @@ constexpr Duration operator-(Duration d) { // a second's worth of ticks and avoid overflow (as negating int64_t-min + 1 // is safe). return time_internal::GetRepLo(d) == 0 - ? time_internal::GetRepHi(d) == std::numeric_limits::min() + ? time_internal::GetRepHi(d) == + (std::numeric_limits::min)() ? InfiniteDuration() : time_internal::MakeDuration(-time_internal::GetRepHi(d)) : time_internal::IsInfiniteDuration(d) @@ -1290,7 +1512,8 @@ constexpr Duration operator-(Duration d) { } constexpr Duration InfiniteDuration() { - return time_internal::MakeDuration(std::numeric_limits::max(), ~0U); + return time_internal::MakeDuration((std::numeric_limits::max)(), + ~0U); } constexpr Duration FromChrono(const std::chrono::nanoseconds& d) { @@ -1332,7 +1555,7 @@ constexpr Time FromTimeT(time_t t) { return time_internal::FromUnixDuration(Seconds(t)); } -} // inline namespace lts_2018_06_20 +} // inline namespace lts_2018_12_18 } // namespace absl #endif // ABSL_TIME_TIME_H_ -- cgit v1.2.3