1 //
2 // Copyright 2021 the gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #include <grpc/support/port_platform.h>
18
19 #include <grpc/support/log.h>
20
21 #include "src/core/lib/gprpp/time_util.h"
22
23 namespace grpc_core {
24
ToGprTimeSpec(absl::Duration duration)25 gpr_timespec ToGprTimeSpec(absl::Duration duration) {
26 if (duration == absl::InfiniteDuration()) {
27 return gpr_inf_future(GPR_TIMESPAN);
28 } else if (duration == -absl::InfiniteDuration()) {
29 return gpr_inf_past(GPR_TIMESPAN);
30 } else {
31 int64_t s = absl::IDivDuration(duration, absl::Seconds(1), &duration);
32 int64_t n = absl::IDivDuration(duration, absl::Nanoseconds(1), &duration);
33 return gpr_time_add(gpr_time_from_seconds(s, GPR_TIMESPAN),
34 gpr_time_from_nanos(n, GPR_TIMESPAN));
35 }
36 }
37
ToGprTimeSpec(absl::Time time)38 gpr_timespec ToGprTimeSpec(absl::Time time) {
39 if (time == absl::InfiniteFuture()) {
40 return gpr_inf_future(GPR_CLOCK_REALTIME);
41 } else if (time == absl::InfinitePast()) {
42 return gpr_inf_past(GPR_CLOCK_REALTIME);
43 } else {
44 timespec ts = absl::ToTimespec(time);
45 gpr_timespec out;
46 out.tv_sec = static_cast<decltype(out.tv_sec)>(ts.tv_sec);
47 out.tv_nsec = static_cast<decltype(out.tv_nsec)>(ts.tv_nsec);
48 out.clock_type = GPR_CLOCK_REALTIME;
49 return out;
50 }
51 }
52
ToAbslDuration(gpr_timespec ts)53 absl::Duration ToAbslDuration(gpr_timespec ts) {
54 GPR_ASSERT(ts.clock_type == GPR_TIMESPAN);
55 if (gpr_time_cmp(ts, gpr_inf_future(GPR_TIMESPAN)) == 0) {
56 return absl::InfiniteDuration();
57 } else if (gpr_time_cmp(ts, gpr_inf_past(GPR_TIMESPAN)) == 0) {
58 return -absl::InfiniteDuration();
59 } else {
60 return absl::Seconds(ts.tv_sec) + absl::Nanoseconds(ts.tv_nsec);
61 }
62 }
63
ToAbslTime(gpr_timespec ts)64 absl::Time ToAbslTime(gpr_timespec ts) {
65 GPR_ASSERT(ts.clock_type != GPR_TIMESPAN);
66 gpr_timespec rts = gpr_convert_clock_type(ts, GPR_CLOCK_REALTIME);
67 if (gpr_time_cmp(rts, gpr_inf_future(GPR_CLOCK_REALTIME)) == 0) {
68 return absl::InfiniteFuture();
69 } else if (gpr_time_cmp(rts, gpr_inf_past(GPR_CLOCK_REALTIME)) == 0) {
70 return absl::InfinitePast();
71 } else {
72 return absl::UnixEpoch() + absl::Seconds(rts.tv_sec) +
73 absl::Nanoseconds(rts.tv_nsec);
74 }
75 }
76
77 } // namespace grpc_core
78