1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/time/time.h"
6 
7 #include <cmath>
8 #include <ios>
9 #include <limits>
10 #include <ostream>
11 #include <sstream>
12 
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/macros.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/third_party/nspr/prtime.h"
18 #include "build/build_config.h"
19 
20 namespace base {
21 
22 // TimeDelta ------------------------------------------------------------------
23 
24 // static
Max()25 TimeDelta TimeDelta::Max() {
26   return TimeDelta(std::numeric_limits<int64_t>::max());
27 }
28 
InDays() const29 int TimeDelta::InDays() const {
30   if (is_max()) {
31     // Preserve max to prevent overflow.
32     return std::numeric_limits<int>::max();
33   }
34   return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
35 }
36 
InHours() const37 int TimeDelta::InHours() const {
38   if (is_max()) {
39     // Preserve max to prevent overflow.
40     return std::numeric_limits<int>::max();
41   }
42   return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
43 }
44 
InMinutes() const45 int TimeDelta::InMinutes() const {
46   if (is_max()) {
47     // Preserve max to prevent overflow.
48     return std::numeric_limits<int>::max();
49   }
50   return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
51 }
52 
InSecondsF() const53 double TimeDelta::InSecondsF() const {
54   if (is_max()) {
55     // Preserve max to prevent overflow.
56     return std::numeric_limits<double>::infinity();
57   }
58   return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
59 }
60 
InSeconds() const61 int64_t TimeDelta::InSeconds() const {
62   if (is_max()) {
63     // Preserve max to prevent overflow.
64     return std::numeric_limits<int64_t>::max();
65   }
66   return delta_ / Time::kMicrosecondsPerSecond;
67 }
68 
InMillisecondsF() const69 double TimeDelta::InMillisecondsF() const {
70   if (is_max()) {
71     // Preserve max to prevent overflow.
72     return std::numeric_limits<double>::infinity();
73   }
74   return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
75 }
76 
InMilliseconds() const77 int64_t TimeDelta::InMilliseconds() const {
78   if (is_max()) {
79     // Preserve max to prevent overflow.
80     return std::numeric_limits<int64_t>::max();
81   }
82   return delta_ / Time::kMicrosecondsPerMillisecond;
83 }
84 
InMillisecondsRoundedUp() const85 int64_t TimeDelta::InMillisecondsRoundedUp() const {
86   if (is_max()) {
87     // Preserve max to prevent overflow.
88     return std::numeric_limits<int64_t>::max();
89   }
90   return (delta_ + Time::kMicrosecondsPerMillisecond - 1) /
91       Time::kMicrosecondsPerMillisecond;
92 }
93 
InMicroseconds() const94 int64_t TimeDelta::InMicroseconds() const {
95   if (is_max()) {
96     // Preserve max to prevent overflow.
97     return std::numeric_limits<int64_t>::max();
98   }
99   return delta_;
100 }
101 
102 namespace time_internal {
103 
SaturatedAdd(TimeDelta delta,int64_t value)104 int64_t SaturatedAdd(TimeDelta delta, int64_t value) {
105   CheckedNumeric<int64_t> rv(delta.delta_);
106   rv += value;
107   return FromCheckedNumeric(rv);
108 }
109 
SaturatedSub(TimeDelta delta,int64_t value)110 int64_t SaturatedSub(TimeDelta delta, int64_t value) {
111   CheckedNumeric<int64_t> rv(delta.delta_);
112   rv -= value;
113   return FromCheckedNumeric(rv);
114 }
115 
FromCheckedNumeric(const CheckedNumeric<int64_t> value)116 int64_t FromCheckedNumeric(const CheckedNumeric<int64_t> value) {
117   if (value.IsValid())
118     return value.ValueUnsafe();
119 
120   // We could return max/min but we don't really expose what the maximum delta
121   // is. Instead, return max/(-max), which is something that clients can reason
122   // about.
123   // TODO(rvargas) crbug.com/332611: don't use internal values.
124   int64_t limit = std::numeric_limits<int64_t>::max();
125   if (value.validity() == internal::RANGE_UNDERFLOW)
126     limit = -limit;
127   return value.ValueOrDefault(limit);
128 }
129 
130 }  // namespace time_internal
131 
operator <<(std::ostream & os,TimeDelta time_delta)132 std::ostream& operator<<(std::ostream& os, TimeDelta time_delta) {
133   return os << time_delta.InSecondsF() << "s";
134 }
135 
136 // Time -----------------------------------------------------------------------
137 
138 // static
Max()139 Time Time::Max() {
140   return Time(std::numeric_limits<int64_t>::max());
141 }
142 
143 // static
FromTimeT(time_t tt)144 Time Time::FromTimeT(time_t tt) {
145   if (tt == 0)
146     return Time();  // Preserve 0 so we can tell it doesn't exist.
147   if (tt == std::numeric_limits<time_t>::max())
148     return Max();
149   return Time(kTimeTToMicrosecondsOffset) + TimeDelta::FromSeconds(tt);
150 }
151 
ToTimeT() const152 time_t Time::ToTimeT() const {
153   if (is_null())
154     return 0;  // Preserve 0 so we can tell it doesn't exist.
155   if (is_max()) {
156     // Preserve max without offset to prevent overflow.
157     return std::numeric_limits<time_t>::max();
158   }
159   if (std::numeric_limits<int64_t>::max() - kTimeTToMicrosecondsOffset <= us_) {
160     DLOG(WARNING) << "Overflow when converting base::Time with internal " <<
161                      "value " << us_ << " to time_t.";
162     return std::numeric_limits<time_t>::max();
163   }
164   return (us_ - kTimeTToMicrosecondsOffset) / kMicrosecondsPerSecond;
165 }
166 
167 // static
FromDoubleT(double dt)168 Time Time::FromDoubleT(double dt) {
169   if (dt == 0 || std::isnan(dt))
170     return Time();  // Preserve 0 so we can tell it doesn't exist.
171   return Time(kTimeTToMicrosecondsOffset) + TimeDelta::FromSecondsD(dt);
172 }
173 
ToDoubleT() const174 double Time::ToDoubleT() const {
175   if (is_null())
176     return 0;  // Preserve 0 so we can tell it doesn't exist.
177   if (is_max()) {
178     // Preserve max without offset to prevent overflow.
179     return std::numeric_limits<double>::infinity();
180   }
181   return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) /
182           static_cast<double>(kMicrosecondsPerSecond));
183 }
184 
185 #if defined(OS_POSIX)
186 // static
FromTimeSpec(const timespec & ts)187 Time Time::FromTimeSpec(const timespec& ts) {
188   return FromDoubleT(ts.tv_sec +
189                      static_cast<double>(ts.tv_nsec) /
190                          base::Time::kNanosecondsPerSecond);
191 }
192 #endif
193 
194 // static
FromJsTime(double ms_since_epoch)195 Time Time::FromJsTime(double ms_since_epoch) {
196   // The epoch is a valid time, so this constructor doesn't interpret
197   // 0 as the null time.
198   return Time(kTimeTToMicrosecondsOffset) +
199          TimeDelta::FromMillisecondsD(ms_since_epoch);
200 }
201 
ToJsTime() const202 double Time::ToJsTime() const {
203   if (is_null()) {
204     // Preserve 0 so the invalid result doesn't depend on the platform.
205     return 0;
206   }
207   if (is_max()) {
208     // Preserve max without offset to prevent overflow.
209     return std::numeric_limits<double>::infinity();
210   }
211   return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) /
212           kMicrosecondsPerMillisecond);
213 }
214 
ToJavaTime() const215 int64_t Time::ToJavaTime() const {
216   if (is_null()) {
217     // Preserve 0 so the invalid result doesn't depend on the platform.
218     return 0;
219   }
220   if (is_max()) {
221     // Preserve max without offset to prevent overflow.
222     return std::numeric_limits<int64_t>::max();
223   }
224   return ((us_ - kTimeTToMicrosecondsOffset) /
225           kMicrosecondsPerMillisecond);
226 }
227 
228 // static
UnixEpoch()229 Time Time::UnixEpoch() {
230   Time time;
231   time.us_ = kTimeTToMicrosecondsOffset;
232   return time;
233 }
234 
LocalMidnight() const235 Time Time::LocalMidnight() const {
236   Exploded exploded;
237   LocalExplode(&exploded);
238   exploded.hour = 0;
239   exploded.minute = 0;
240   exploded.second = 0;
241   exploded.millisecond = 0;
242   return FromLocalExploded(exploded);
243 }
244 
245 // static
FromStringInternal(const char * time_string,bool is_local,Time * parsed_time)246 bool Time::FromStringInternal(const char* time_string,
247                               bool is_local,
248                               Time* parsed_time) {
249   DCHECK((time_string != NULL) && (parsed_time != NULL));
250 
251   if (time_string[0] == '\0')
252     return false;
253 
254   PRTime result_time = 0;
255   PRStatus result = PR_ParseTimeString(time_string,
256                                        is_local ? PR_FALSE : PR_TRUE,
257                                        &result_time);
258   if (PR_SUCCESS != result)
259     return false;
260 
261   result_time += kTimeTToMicrosecondsOffset;
262   *parsed_time = Time(result_time);
263   return true;
264 }
265 
operator <<(std::ostream & os,Time time)266 std::ostream& operator<<(std::ostream& os, Time time) {
267   Time::Exploded exploded;
268   time.UTCExplode(&exploded);
269   // Use StringPrintf because iostreams formatting is painful.
270   return os << StringPrintf("%04d-%02d-%02d %02d:%02d:%02d.%03d UTC",
271                             exploded.year,
272                             exploded.month,
273                             exploded.day_of_month,
274                             exploded.hour,
275                             exploded.minute,
276                             exploded.second,
277                             exploded.millisecond);
278 }
279 
280 // Local helper class to hold the conversion from Time to TickTime at the
281 // time of the Unix epoch.
282 class UnixEpochSingleton {
283  public:
UnixEpochSingleton()284   UnixEpochSingleton()
285       : unix_epoch_(TimeTicks::Now() - (Time::Now() - Time::UnixEpoch())) {}
286 
unix_epoch() const287   TimeTicks unix_epoch() const { return unix_epoch_; }
288 
289  private:
290   const TimeTicks unix_epoch_;
291 
292   DISALLOW_COPY_AND_ASSIGN(UnixEpochSingleton);
293 };
294 
295 static LazyInstance<UnixEpochSingleton>::Leaky
296     leaky_unix_epoch_singleton_instance = LAZY_INSTANCE_INITIALIZER;
297 
298 // Static
UnixEpoch()299 TimeTicks TimeTicks::UnixEpoch() {
300   return leaky_unix_epoch_singleton_instance.Get().unix_epoch();
301 }
302 
SnappedToNextTick(TimeTicks tick_phase,TimeDelta tick_interval) const303 TimeTicks TimeTicks::SnappedToNextTick(TimeTicks tick_phase,
304                                        TimeDelta tick_interval) const {
305   // |interval_offset| is the offset from |this| to the next multiple of
306   // |tick_interval| after |tick_phase|, possibly negative if in the past.
307   TimeDelta interval_offset = (tick_phase - *this) % tick_interval;
308   // If |this| is exactly on the interval (i.e. offset==0), don't adjust.
309   // Otherwise, if |tick_phase| was in the past, adjust forward to the next
310   // tick after |this|.
311   if (!interval_offset.is_zero() && tick_phase < *this)
312     interval_offset += tick_interval;
313   return *this + interval_offset;
314 }
315 
operator <<(std::ostream & os,TimeTicks time_ticks)316 std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks) {
317   // This function formats a TimeTicks object as "bogo-microseconds".
318   // The origin and granularity of the count are platform-specific, and may very
319   // from run to run. Although bogo-microseconds usually roughly correspond to
320   // real microseconds, the only real guarantee is that the number never goes
321   // down during a single run.
322   const TimeDelta as_time_delta = time_ticks - TimeTicks();
323   return os << as_time_delta.InMicroseconds() << " bogo-microseconds";
324 }
325 
operator <<(std::ostream & os,ThreadTicks thread_ticks)326 std::ostream& operator<<(std::ostream& os, ThreadTicks thread_ticks) {
327   const TimeDelta as_time_delta = thread_ticks - ThreadTicks();
328   return os << as_time_delta.InMicroseconds() << " bogo-thread-microseconds";
329 }
330 
331 // Time::Exploded -------------------------------------------------------------
332 
is_in_range(int value,int lo,int hi)333 inline bool is_in_range(int value, int lo, int hi) {
334   return lo <= value && value <= hi;
335 }
336 
HasValidValues() const337 bool Time::Exploded::HasValidValues() const {
338   return is_in_range(month, 1, 12) &&
339          is_in_range(day_of_week, 0, 6) &&
340          is_in_range(day_of_month, 1, 31) &&
341          is_in_range(hour, 0, 23) &&
342          is_in_range(minute, 0, 59) &&
343          is_in_range(second, 0, 60) &&
344          is_in_range(millisecond, 0, 999);
345 }
346 
347 }  // namespace base
348