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
30 _TimeSpec __convert_to_timespec(const chrono::nanoseconds& __ns)
31 {
32   using namespace chrono;
33   seconds __s = duration_cast<seconds>(__ns);
34   _TimeSpec __ts;
35   typedef decltype(__ts.tv_sec) __ts_sec;
36   const __ts_sec __ts_sec_max = numeric_limits<__ts_sec>::max();
37 
38   if (__s.count() < __ts_sec_max)
39   {
40     __ts.tv_sec = static_cast<__ts_sec>(__s.count());
41     __ts.tv_nsec = static_cast<decltype(__ts.tv_nsec)>((__ns - __s).count());
42   }
43   else
44   {
45     __ts.tv_sec = __ts_sec_max;
46     __ts.tv_nsec = 999999999; // (10^9 - 1)
47   }
48 
49   return __ts;
50 }
51 
52 _LIBCPP_END_NAMESPACE_STD
53 
54 _LIBCPP_POP_MACROS
55 
56 #endif // _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H
57