convert_to_timespec.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. #ifndef _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H
  10. #define _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H
  11. #include <__chrono/duration.h>
  12. #include <__config>
  13. #include <limits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_PUSH_MACROS
  18. #include <__undef_macros>
  19. _LIBCPP_BEGIN_NAMESPACE_STD
  20. // Convert a nanoseconds duration to the given TimeSpec type, which must have
  21. // the same properties as std::timespec.
  22. template <class _TimeSpec>
  23. _LIBCPP_HIDE_FROM_ABI inline
  24. _TimeSpec __convert_to_timespec(const chrono::nanoseconds& __ns)
  25. {
  26. using namespace chrono;
  27. seconds __s = duration_cast<seconds>(__ns);
  28. _TimeSpec __ts;
  29. typedef decltype(__ts.tv_sec) __ts_sec;
  30. const __ts_sec __ts_sec_max = numeric_limits<__ts_sec>::max();
  31. if (__s.count() < __ts_sec_max)
  32. {
  33. __ts.tv_sec = static_cast<__ts_sec>(__s.count());
  34. __ts.tv_nsec = static_cast<decltype(__ts.tv_nsec)>((__ns - __s).count());
  35. }
  36. else
  37. {
  38. __ts.tv_sec = __ts_sec_max;
  39. __ts.tv_nsec = 999999999; // (10^9 - 1)
  40. }
  41. return __ts;
  42. }
  43. _LIBCPP_END_NAMESPACE_STD
  44. _LIBCPP_POP_MACROS
  45. #endif // _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H