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