Debian Codegraph @

src/cpp/util/time_cc.cc

raw
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/impl/codegen/gpr_types.h>
23 #include <grpc/support/time.h>
24 #include <grpcpp/support/time.h>
25
26 // IWYU pragma: no_include <ratio>
27
28 using std::chrono::duration_cast;
29 using std::chrono::high_resolution_clock;
30 using std::chrono::nanoseconds;
31 using std::chrono::seconds;
32 using std::chrono::system_clock;
33
34 namespace grpc {
35
36 void Timepoint2Timespec(const system_clock::time_point& from,
37 gpr_timespec* to) {
38 system_clock::duration deadline = from.time_since_epoch();
39 seconds secs = duration_cast<seconds>(deadline);
40 if (from == system_clock::time_point::max() ||
41 secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec ||
42 secs.count() < 0) {
43 *to = gpr_inf_future(GPR_CLOCK_REALTIME);
44 return;
45 }
46 nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs);
47 to->tv_sec = static_cast<int64_t>(secs.count());
48 to->tv_nsec = static_cast<int32_t>(nsecs.count());
49 to->clock_type = GPR_CLOCK_REALTIME;
50 }
51
52 void TimepointHR2Timespec(const high_resolution_clock::time_point& from,
53 gpr_timespec* to) {
54 high_resolution_clock::duration deadline = from.time_since_epoch();
55 seconds secs = duration_cast<seconds>(deadline);
56 if (from == high_resolution_clock::time_point::max() ||
57 secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec ||
58 secs.count() < 0) {
59 *to = gpr_inf_future(GPR_CLOCK_REALTIME);
60 return;
61 }
62 nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs);
63 to->tv_sec = static_cast<int64_t>(secs.count());
64 to->tv_nsec = static_cast<int32_t>(nsecs.count());
65 to->clock_type = GPR_CLOCK_REALTIME;
66 }
67
68 system_clock::time_point Timespec2Timepoint(gpr_timespec t) {
69 if (gpr_time_cmp(t, gpr_inf_future(t.clock_type)) == 0) {
70 return system_clock::time_point::max();
71 }
72 t = gpr_convert_clock_type(t, GPR_CLOCK_REALTIME);
73 system_clock::time_point tp;
74 tp += duration_cast<system_clock::time_point::duration>(seconds(t.tv_sec));
75 tp +=
76 duration_cast<system_clock::time_point::duration>(nanoseconds(t.tv_nsec));
77 return tp;
78 }
79
80 } // namespace grpc