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
base / time / time_conversion_posix.cc [blame]
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/time/time.h"
#include <stdint.h>
#include <sys/time.h>
#include <time.h>
#include <limits>
#include "base/check_op.h"
namespace base {
// static
TimeDelta TimeDelta::FromTimeSpec(const timespec& ts) {
return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
}
struct timespec TimeDelta::ToTimeSpec() const {
int64_t microseconds = InMicroseconds();
time_t seconds = 0;
if (microseconds >= Time::kMicrosecondsPerSecond) {
seconds = static_cast<time_t>(InSeconds());
microseconds -= seconds * Time::kMicrosecondsPerSecond;
}
struct timespec result = {
seconds,
static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)};
return result;
}
// static
Time Time::FromTimeVal(struct timeval t) {
DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond));
DCHECK_GE(t.tv_usec, 0);
if (t.tv_usec == 0 && t.tv_sec == 0)
return Time();
if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 &&
t.tv_sec == std::numeric_limits<time_t>::max())
return Max();
return Time((static_cast<int64_t>(t.tv_sec) * Time::kMicrosecondsPerSecond) +
t.tv_usec + kTimeTToMicrosecondsOffset);
}
struct timeval Time::ToTimeVal() const {
struct timeval result;
if (is_null()) {
result.tv_sec = 0;
result.tv_usec = 0;
return result;
}
if (is_max()) {
result.tv_sec = std::numeric_limits<time_t>::max();
result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
return result;
}
int64_t us = us_ - kTimeTToMicrosecondsOffset;
result.tv_sec = static_cast<time_t>(us / Time::kMicrosecondsPerSecond);
result.tv_usec = us % Time::kMicrosecondsPerSecond;
return result;
}
} // namespace base