convert_to_timespec.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 _TimeSpec __convert_to_timespec(const chrono::nanoseconds& __ns) {
  24. using namespace chrono;
  25. seconds __s = duration_cast<seconds>(__ns);
  26. _TimeSpec __ts;
  27. typedef decltype(__ts.tv_sec) __ts_sec;
  28. const __ts_sec __ts_sec_max = numeric_limits<__ts_sec>::max();
  29. if (__s.count() < __ts_sec_max) {
  30. __ts.tv_sec = static_cast<__ts_sec>(__s.count());
  31. __ts.tv_nsec = static_cast<decltype(__ts.tv_nsec)>((__ns - __s).count());
  32. } else {
  33. __ts.tv_sec = __ts_sec_max;
  34. __ts.tv_nsec = 999999999; // (10^9 - 1)
  35. }
  36. return __ts;
  37. }
  38. _LIBCPP_END_NAMESPACE_STD
  39. _LIBCPP_POP_MACROS
  40. #endif // _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H