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 "src/core/util/time_util.h"
18
19 #include <grpc/support/port_platform.h>
20 #include <grpc/support/time.h>
21 #include <stdint.h>
22 #include <time.h>
23
24 #include "absl/log/check.h"
25
26 namespace grpc_core {
27
ToGprTimeSpec(absl::Duration duration)28 gpr_timespec ToGprTimeSpec(absl::Duration duration) {
29 if (duration == absl::InfiniteDuration()) {
30 return gpr_inf_future(GPR_TIMESPAN);
31 } else if (duration == -absl::InfiniteDuration()) {
32 return gpr_inf_past(GPR_TIMESPAN);
33 } else {
34 int64_t s = absl::IDivDuration(duration, absl::Seconds(1), &duration);
35 int64_t n = absl::IDivDuration(duration, absl::Nanoseconds(1), &duration);
36 return gpr_time_add(gpr_time_from_seconds(s, GPR_TIMESPAN),
37 gpr_time_from_nanos(n, GPR_TIMESPAN));
38 }
39 }
40
ToGprTimeSpec(absl::Time time)41 gpr_timespec ToGprTimeSpec(absl::Time time) {
42 if (time == absl::InfiniteFuture()) {
43 return gpr_inf_future(GPR_CLOCK_REALTIME);
44 } else if (time == absl::InfinitePast()) {
45 return gpr_inf_past(GPR_CLOCK_REALTIME);
46 } else {
47 timespec ts = absl::ToTimespec(time);
48 gpr_timespec out;
49 out.tv_sec = static_cast<decltype(out.tv_sec)>(ts.tv_sec);
50 out.tv_nsec = static_cast<decltype(out.tv_nsec)>(ts.tv_nsec);
51 out.clock_type = GPR_CLOCK_REALTIME;
52 return out;
53 }
54 }
55
ToAbslDuration(gpr_timespec ts)56 absl::Duration ToAbslDuration(gpr_timespec ts) {
57 CHECK(ts.clock_type == GPR_TIMESPAN);
58 if (gpr_time_cmp(ts, gpr_inf_future(GPR_TIMESPAN)) == 0) {
59 return absl::InfiniteDuration();
60 } else if (gpr_time_cmp(ts, gpr_inf_past(GPR_TIMESPAN)) == 0) {
61 return -absl::InfiniteDuration();
62 } else {
63 return absl::Seconds(ts.tv_sec) + absl::Nanoseconds(ts.tv_nsec);
64 }
65 }
66
ToAbslTime(gpr_timespec ts)67 absl::Time ToAbslTime(gpr_timespec ts) {
68 CHECK(ts.clock_type != GPR_TIMESPAN);
69 gpr_timespec rts = gpr_convert_clock_type(ts, GPR_CLOCK_REALTIME);
70 if (gpr_time_cmp(rts, gpr_inf_future(GPR_CLOCK_REALTIME)) == 0) {
71 return absl::InfiniteFuture();
72 } else if (gpr_time_cmp(rts, gpr_inf_past(GPR_CLOCK_REALTIME)) == 0) {
73 return absl::InfinitePast();
74 } else {
75 return absl::UnixEpoch() + absl::Seconds(rts.tv_sec) +
76 absl::Nanoseconds(rts.tv_nsec);
77 }
78 }
79
80 } // namespace grpc_core
81