1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // The implementation of the absl::Time class, which is declared in
16 // //absl/time.h.
17 //
18 // The representation for an absl::Time is an absl::Duration offset from the
19 // epoch.  We use the traditional Unix epoch (1970-01-01 00:00:00 +0000)
20 // for convenience, but this is not exposed in the API and could be changed.
21 //
22 // NOTE: To keep type verbosity to a minimum, the following variable naming
23 // conventions are used throughout this file.
24 //
25 // cz: A cctz::time_zone
26 // tz: An absl::TimeZone
27 // cl: A cctz::time_zone::civil_lookup
28 // al: A cctz::time_zone::absolute_lookup
29 // cd: A cctz::civil_day
30 // cs: A cctz::civil_second
31 // bd: An absl::Time::Breakdown
32 
33 #include "absl/time/time.h"
34 
35 #include <cstring>
36 #include <ctime>
37 #include <limits>
38 
39 #include "absl/time/internal/cctz/include/cctz/civil_time.h"
40 #include "absl/time/internal/cctz/include/cctz/time_zone.h"
41 
42 namespace cctz = absl::time_internal::cctz;
43 namespace absl {
44 
45 namespace {
46 
unix_epoch()47 inline cctz::time_point<cctz::seconds> unix_epoch() {
48   return std::chrono::time_point_cast<cctz::seconds>(
49       std::chrono::system_clock::from_time_t(0));
50 }
51 
52 // Floors d to the next unit boundary closer to negative infinity.
FloorToUnit(absl::Duration d,absl::Duration unit)53 inline int64_t FloorToUnit(absl::Duration d, absl::Duration unit) {
54   absl::Duration rem;
55   int64_t q = absl::IDivDuration(d, unit, &rem);
56   return (q > 0 ||
57           rem >= ZeroDuration() ||
58           q == std::numeric_limits<int64_t>::min()) ? q : q - 1;
59 }
60 
InfiniteFutureBreakdown()61 inline absl::Time::Breakdown InfiniteFutureBreakdown() {
62   absl::Time::Breakdown bd;
63   bd.year = std::numeric_limits<int64_t>::max();
64   bd.month = 12;
65   bd.day = 31;
66   bd.hour = 23;
67   bd.minute = 59;
68   bd.second = 59;
69   bd.subsecond = absl::InfiniteDuration();
70   bd.weekday = 4;
71   bd.yearday = 365;
72   bd.offset = 0;
73   bd.is_dst = false;
74   bd.zone_abbr = "-00";
75   return bd;
76 }
77 
InfinitePastBreakdown()78 inline Time::Breakdown InfinitePastBreakdown() {
79   Time::Breakdown bd;
80   bd.year = std::numeric_limits<int64_t>::min();
81   bd.month = 1;
82   bd.day = 1;
83   bd.hour = 0;
84   bd.minute = 0;
85   bd.second = 0;
86   bd.subsecond = -absl::InfiniteDuration();
87   bd.weekday = 7;
88   bd.yearday = 1;
89   bd.offset = 0;
90   bd.is_dst = false;
91   bd.zone_abbr = "-00";
92   return bd;
93 }
94 
InfiniteFutureTimeConversion()95 inline absl::TimeConversion InfiniteFutureTimeConversion() {
96   absl::TimeConversion tc;
97   tc.pre = tc.trans = tc.post = absl::InfiniteFuture();
98   tc.kind = absl::TimeConversion::UNIQUE;
99   tc.normalized = true;
100   return tc;
101 }
102 
InfinitePastTimeConversion()103 inline TimeConversion InfinitePastTimeConversion() {
104   absl::TimeConversion tc;
105   tc.pre = tc.trans = tc.post = absl::InfinitePast();
106   tc.kind = absl::TimeConversion::UNIQUE;
107   tc.normalized = true;
108   return tc;
109 }
110 
111 // Makes a Time from sec, overflowing to InfiniteFuture/InfinitePast as
112 // necessary. If sec is min/max, then consult cs+tz to check for overlow.
MakeTimeWithOverflow(const cctz::time_point<cctz::seconds> & sec,const cctz::civil_second & cs,const cctz::time_zone & tz,bool * normalized=nullptr)113 Time MakeTimeWithOverflow(const cctz::time_point<cctz::seconds>& sec,
114                           const cctz::civil_second& cs,
115                           const cctz::time_zone& tz,
116                           bool* normalized = nullptr) {
117   const auto max = cctz::time_point<cctz::seconds>::max();
118   const auto min = cctz::time_point<cctz::seconds>::min();
119   if (sec == max) {
120     const auto al = tz.lookup(max);
121     if (cs > al.cs) {
122       if (normalized) *normalized = true;
123       return absl::InfiniteFuture();
124     }
125   }
126   if (sec == min) {
127     const auto al = tz.lookup(min);
128     if (cs < al.cs) {
129       if (normalized) *normalized = true;
130       return absl::InfinitePast();
131     }
132   }
133   const auto hi = (sec - unix_epoch()).count();
134   return time_internal::FromUnixDuration(time_internal::MakeDuration(hi));
135 }
136 
MapKind(const cctz::time_zone::civil_lookup::civil_kind & kind)137 inline absl::TimeConversion::Kind MapKind(
138     const cctz::time_zone::civil_lookup::civil_kind& kind) {
139   switch (kind) {
140     case cctz::time_zone::civil_lookup::UNIQUE:
141       return absl::TimeConversion::UNIQUE;
142     case cctz::time_zone::civil_lookup::SKIPPED:
143       return absl::TimeConversion::SKIPPED;
144     case cctz::time_zone::civil_lookup::REPEATED:
145       return absl::TimeConversion::REPEATED;
146   }
147   return absl::TimeConversion::UNIQUE;
148 }
149 
150 // Returns Mon=1..Sun=7.
MapWeekday(const cctz::weekday & wd)151 inline int MapWeekday(const cctz::weekday& wd) {
152   switch (wd) {
153     case cctz::weekday::monday:
154       return 1;
155     case cctz::weekday::tuesday:
156       return 2;
157     case cctz::weekday::wednesday:
158       return 3;
159     case cctz::weekday::thursday:
160       return 4;
161     case cctz::weekday::friday:
162       return 5;
163     case cctz::weekday::saturday:
164       return 6;
165     case cctz::weekday::sunday:
166       return 7;
167   }
168   return 1;
169 }
170 
171 }  // namespace
172 
In(absl::TimeZone tz) const173 absl::Time::Breakdown Time::In(absl::TimeZone tz) const {
174   if (*this == absl::InfiniteFuture()) return absl::InfiniteFutureBreakdown();
175   if (*this == absl::InfinitePast()) return absl::InfinitePastBreakdown();
176 
177   const auto tp = unix_epoch() + cctz::seconds(time_internal::GetRepHi(rep_));
178   const auto al = cctz::time_zone(tz).lookup(tp);
179   const auto cs = al.cs;
180   const auto cd = cctz::civil_day(cs);
181 
182   absl::Time::Breakdown bd;
183   bd.year = cs.year();
184   bd.month = cs.month();
185   bd.day = cs.day();
186   bd.hour = cs.hour();
187   bd.minute = cs.minute();
188   bd.second = cs.second();
189   bd.subsecond = time_internal::MakeDuration(0, time_internal::GetRepLo(rep_));
190   bd.weekday = MapWeekday(get_weekday(cd));
191   bd.yearday = get_yearday(cd);
192   bd.offset = al.offset;
193   bd.is_dst = al.is_dst;
194   bd.zone_abbr = al.abbr;
195   return bd;
196 }
197 
FromTM(const struct tm & tm,absl::TimeZone tz)198 absl::Time FromTM(const struct tm& tm, absl::TimeZone tz) {
199   const auto cz = cctz::time_zone(tz);
200   const auto cs =
201       cctz::civil_second(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
202                          tm.tm_hour, tm.tm_min, tm.tm_sec);
203   const auto cl = cz.lookup(cs);
204   const auto tp = tm.tm_isdst == 0 ? cl.post : cl.pre;
205   return MakeTimeWithOverflow(tp, cs, cz);
206 }
207 
ToTM(absl::Time t,absl::TimeZone tz)208 struct tm ToTM(absl::Time t, absl::TimeZone tz) {
209   const absl::Time::Breakdown bd = t.In(tz);
210   struct tm tm;
211   std::memset(&tm, 0, sizeof(tm));
212   tm.tm_sec = bd.second;
213   tm.tm_min = bd.minute;
214   tm.tm_hour = bd.hour;
215   tm.tm_mday = bd.day;
216   tm.tm_mon = bd.month - 1;
217 
218   // Saturates tm.tm_year in cases of over/underflow, accounting for the fact
219   // that tm.tm_year is years since 1900.
220   if (bd.year < std::numeric_limits<int>::min() + 1900) {
221     tm.tm_year = std::numeric_limits<int>::min();
222   } else if (bd.year > std::numeric_limits<int>::max()) {
223     tm.tm_year = std::numeric_limits<int>::max() - 1900;
224   } else {
225     tm.tm_year = static_cast<int>(bd.year - 1900);
226   }
227 
228   tm.tm_wday = bd.weekday % 7;
229   tm.tm_yday = bd.yearday - 1;
230   tm.tm_isdst = bd.is_dst ? 1 : 0;
231 
232   return tm;
233 }
234 
235 //
236 // Factory functions.
237 //
238 
ConvertDateTime(int64_t year,int mon,int day,int hour,int min,int sec,TimeZone tz)239 absl::TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour,
240                                      int min, int sec, TimeZone tz) {
241   // Avoids years that are too extreme for civil_second to normalize.
242   if (year > 300000000000) return InfiniteFutureTimeConversion();
243   if (year < -300000000000) return InfinitePastTimeConversion();
244   const auto cz = cctz::time_zone(tz);
245   const auto cs = cctz::civil_second(year, mon, day, hour, min, sec);
246   absl::TimeConversion tc;
247   tc.normalized = year != cs.year() || mon != cs.month() || day != cs.day() ||
248                   hour != cs.hour() || min != cs.minute() || sec != cs.second();
249   const auto cl = cz.lookup(cs);
250   // Converts the civil_lookup struct to a TimeConversion.
251   tc.pre = MakeTimeWithOverflow(cl.pre, cs, cz, &tc.normalized);
252   tc.trans = MakeTimeWithOverflow(cl.trans, cs, cz, &tc.normalized);
253   tc.post = MakeTimeWithOverflow(cl.post, cs, cz, &tc.normalized);
254   tc.kind = MapKind(cl.kind);
255   return tc;
256 }
257 
FromDateTime(int64_t year,int mon,int day,int hour,int min,int sec,TimeZone tz)258 absl::Time FromDateTime(int64_t year, int mon, int day, int hour, int min,
259                         int sec, TimeZone tz) {
260   if (year > 300000000000) return InfiniteFuture();
261   if (year < -300000000000) return InfinitePast();
262   const auto cz = cctz::time_zone(tz);
263   const auto cs = cctz::civil_second(year, mon, day, hour, min, sec);
264   const auto cl = cz.lookup(cs);
265   return MakeTimeWithOverflow(cl.pre, cs, cz);
266 }
267 
TimeFromTimespec(timespec ts)268 absl::Time TimeFromTimespec(timespec ts) {
269   return time_internal::FromUnixDuration(absl::DurationFromTimespec(ts));
270 }
271 
TimeFromTimeval(timeval tv)272 absl::Time TimeFromTimeval(timeval tv) {
273   return time_internal::FromUnixDuration(absl::DurationFromTimeval(tv));
274 }
275 
FromUDate(double udate)276 absl::Time FromUDate(double udate) {
277   return time_internal::FromUnixDuration(absl::Milliseconds(udate));
278 }
279 
FromUniversal(int64_t universal)280 absl::Time FromUniversal(int64_t universal) {
281   return absl::UniversalEpoch() + 100 * absl::Nanoseconds(universal);
282 }
283 
284 //
285 // Conversion to other time types.
286 //
287 
ToUnixNanos(Time t)288 int64_t ToUnixNanos(Time t) {
289   if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 &&
290       time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 33 == 0) {
291     return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) *
292             1000 * 1000 * 1000) +
293            (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / 4);
294   }
295   return FloorToUnit(time_internal::ToUnixDuration(t), absl::Nanoseconds(1));
296 }
297 
ToUnixMicros(Time t)298 int64_t ToUnixMicros(Time t) {
299   if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 &&
300       time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 43 == 0) {
301     return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) *
302             1000 * 1000) +
303            (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / 4000);
304   }
305   return FloorToUnit(time_internal::ToUnixDuration(t), absl::Microseconds(1));
306 }
307 
ToUnixMillis(Time t)308 int64_t ToUnixMillis(Time t) {
309   if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 &&
310       time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 53 == 0) {
311     return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) * 1000) +
312            (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) /
313             (4000 * 1000));
314   }
315   return FloorToUnit(time_internal::ToUnixDuration(t), absl::Milliseconds(1));
316 }
317 
ToUnixSeconds(Time t)318 int64_t ToUnixSeconds(Time t) {
319   return time_internal::GetRepHi(time_internal::ToUnixDuration(t));
320 }
321 
ToTimeT(Time t)322 time_t ToTimeT(Time t) { return absl::ToTimespec(t).tv_sec; }
323 
ToTimespec(Time t)324 timespec ToTimespec(Time t) {
325   timespec ts;
326   absl::Duration d = time_internal::ToUnixDuration(t);
327   if (!time_internal::IsInfiniteDuration(d)) {
328     ts.tv_sec = time_internal::GetRepHi(d);
329     if (ts.tv_sec == time_internal::GetRepHi(d)) {  // no time_t narrowing
330       ts.tv_nsec = time_internal::GetRepLo(d) / 4;  // floor
331       return ts;
332     }
333   }
334   if (d >= absl::ZeroDuration()) {
335     ts.tv_sec = std::numeric_limits<time_t>::max();
336     ts.tv_nsec = 1000 * 1000 * 1000 - 1;
337   } else {
338     ts.tv_sec = std::numeric_limits<time_t>::min();
339     ts.tv_nsec = 0;
340   }
341   return ts;
342 }
343 
ToTimeval(Time t)344 timeval ToTimeval(Time t) {
345   timeval tv;
346   timespec ts = absl::ToTimespec(t);
347   tv.tv_sec = ts.tv_sec;
348   if (tv.tv_sec != ts.tv_sec) {  // narrowing
349     if (ts.tv_sec < 0) {
350       tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min();
351       tv.tv_usec = 0;
352     } else {
353       tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max();
354       tv.tv_usec = 1000 * 1000 - 1;
355     }
356     return tv;
357   }
358   tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000);  // suseconds_t
359   return tv;
360 }
361 
ToUDate(Time t)362 double ToUDate(Time t) {
363   return absl::FDivDuration(time_internal::ToUnixDuration(t),
364                             absl::Milliseconds(1));
365 }
366 
ToUniversal(absl::Time t)367 int64_t ToUniversal(absl::Time t) {
368   return absl::FloorToUnit(t - absl::UniversalEpoch(), absl::Nanoseconds(100));
369 }
370 
FromChrono(const std::chrono::system_clock::time_point & tp)371 Time FromChrono(const std::chrono::system_clock::time_point& tp) {
372   return time_internal::FromUnixDuration(time_internal::FromChrono(
373       tp - std::chrono::system_clock::from_time_t(0)));
374 }
375 
ToChronoTime(absl::Time t)376 std::chrono::system_clock::time_point ToChronoTime(absl::Time t) {
377   using D = std::chrono::system_clock::duration;
378   auto d = time_internal::ToUnixDuration(t);
379   if (d < ZeroDuration()) d = Floor(d, FromChrono(D{1}));
380   return std::chrono::system_clock::from_time_t(0) +
381          time_internal::ToChronoDuration<D>(d);
382 }
383 
384 }  // namespace absl
385