1 | // -*- C++ -*- |
2 | //===----------------------------------------------------------------------===// |
3 | // |
4 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
5 | // See https://llvm.org/LICENSE.txt for license information. |
6 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | |
10 | #ifndef _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H |
11 | #define _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H |
12 | |
13 | #include <__chrono/duration.h> |
14 | #include <__config> |
15 | #include <limits> |
16 | |
17 | #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) |
18 | # pragma GCC system_header |
19 | #endif |
20 | |
21 | _LIBCPP_PUSH_MACROS |
22 | #include <__undef_macros> |
23 | |
24 | _LIBCPP_BEGIN_NAMESPACE_STD |
25 | |
26 | // Convert a nanoseconds duration to the given TimeSpec type, which must have |
27 | // the same properties as std::timespec. |
28 | template <class _TimeSpec> |
29 | _LIBCPP_HIDE_FROM_ABI inline _TimeSpec __convert_to_timespec(const chrono::nanoseconds& __ns) { |
30 | using namespace chrono; |
31 | seconds __s = duration_cast<seconds>(__ns); |
32 | _TimeSpec __ts; |
33 | typedef decltype(__ts.tv_sec) __ts_sec; |
34 | const __ts_sec __ts_sec_max = numeric_limits<__ts_sec>::max(); |
35 | |
36 | if (__s.count() < __ts_sec_max) { |
37 | __ts.tv_sec = static_cast<__ts_sec>(__s.count()); |
38 | __ts.tv_nsec = static_cast<decltype(__ts.tv_nsec)>((__ns - __s).count()); |
39 | } else { |
40 | __ts.tv_sec = __ts_sec_max; |
41 | __ts.tv_nsec = 999999999; // (10^9 - 1) |
42 | } |
43 | |
44 | return __ts; |
45 | } |
46 | |
47 | _LIBCPP_END_NAMESPACE_STD |
48 | |
49 | _LIBCPP_POP_MACROS |
50 | |
51 | #endif // _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H |
52 | |