1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18
19 #include <chrono>
20 #include <cstdint>
21
22 #include <grpc/support/time.h>
23 #include <grpcpp/support/time.h>
24
25 // IWYU pragma: no_include <ratio>
26
27 using std::chrono::duration_cast;
28 using std::chrono::high_resolution_clock;
29 using std::chrono::nanoseconds;
30 using std::chrono::seconds;
31 using std::chrono::system_clock;
32
33 namespace grpc {
34
Timepoint2Timespec(const system_clock::time_point & from,gpr_timespec * to)35 void Timepoint2Timespec(const system_clock::time_point& from,
36 gpr_timespec* to) {
37 system_clock::duration deadline = from.time_since_epoch();
38 seconds secs = duration_cast<seconds>(deadline);
39 if (from == system_clock::time_point::max() ||
40 secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec ||
41 secs.count() < 0) {
42 *to = gpr_inf_future(GPR_CLOCK_REALTIME);
43 return;
44 }
45 nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs);
46 to->tv_sec = static_cast<int64_t>(secs.count());
47 to->tv_nsec = static_cast<int32_t>(nsecs.count());
48 to->clock_type = GPR_CLOCK_REALTIME;
49 }
50
TimepointHR2Timespec(const high_resolution_clock::time_point & from,gpr_timespec * to)51 void TimepointHR2Timespec(const high_resolution_clock::time_point& from,
52 gpr_timespec* to) {
53 high_resolution_clock::duration deadline = from.time_since_epoch();
54 seconds secs = duration_cast<seconds>(deadline);
55 if (from == high_resolution_clock::time_point::max() ||
56 secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec ||
57 secs.count() < 0) {
58 *to = gpr_inf_future(GPR_CLOCK_REALTIME);
59 return;
60 }
61 nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs);
62 to->tv_sec = static_cast<int64_t>(secs.count());
63 to->tv_nsec = static_cast<int32_t>(nsecs.count());
64 to->clock_type = GPR_CLOCK_REALTIME;
65 }
66
Timespec2Timepoint(gpr_timespec t)67 system_clock::time_point Timespec2Timepoint(gpr_timespec t) {
68 if (gpr_time_cmp(t, gpr_inf_future(t.clock_type)) == 0) {
69 return system_clock::time_point::max();
70 }
71 t = gpr_convert_clock_type(t, GPR_CLOCK_REALTIME);
72 system_clock::time_point tp;
73 tp += duration_cast<system_clock::time_point::duration>(seconds(t.tv_sec));
74 tp +=
75 duration_cast<system_clock::time_point::duration>(nanoseconds(t.tv_nsec));
76 return tp;
77 }
78
79 } // namespace grpc
80