blob: e8631d135fee55536713c6daf4ef5807f74c4d2b [file] [log] [blame]
Louis Dionnedf51be82022-01-10 09:43:29 -05001// -*- 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
12#include <__chrono/duration.h>
13#include <__config>
14#include <limits>
15
16#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
Arthur O'Dwyerfa6b9e42022-02-01 20:16:40 -050017# pragma GCC system_header
Louis Dionnedf51be82022-01-10 09:43:29 -050018#endif
19
20_LIBCPP_PUSH_MACROS
21#include <__undef_macros>
22
23_LIBCPP_BEGIN_NAMESPACE_STD
24
25// Convert a nanoseconds duration to the given TimeSpec type, which must have
26// the same properties as std::timespec.
27template <class _TimeSpec>
28_LIBCPP_HIDE_FROM_ABI inline
29_TimeSpec __convert_to_timespec(const chrono::nanoseconds& __ns)
30{
31 using namespace chrono;
32 seconds __s = duration_cast<seconds>(__ns);
33 _TimeSpec __ts;
34 typedef decltype(__ts.tv_sec) __ts_sec;
35 const __ts_sec __ts_sec_max = numeric_limits<__ts_sec>::max();
36
37 if (__s.count() < __ts_sec_max)
38 {
39 __ts.tv_sec = static_cast<__ts_sec>(__s.count());
40 __ts.tv_nsec = static_cast<decltype(__ts.tv_nsec)>((__ns - __s).count());
41 }
42 else
43 {
44 __ts.tv_sec = __ts_sec_max;
45 __ts.tv_nsec = 999999999; // (10^9 - 1)
46 }
47
48 return __ts;
49}
50
51_LIBCPP_END_NAMESPACE_STD
52
53_LIBCPP_POP_MACROS
54
55#endif // _LIBCPP___CHRONO_CONVERT_TO_TIMESPEC_H