• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Linux absolute timeout ---------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_ABS_TIMEOUT_H
10 #define LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_ABS_TIMEOUT_H
11 
12 #include "hdr/time_macros.h"
13 #include "hdr/types/struct_timespec.h"
14 #include "src/__support/CPP/expected.h"
15 #include "src/__support/time/units.h"
16 
17 namespace LIBC_NAMESPACE {
18 namespace internal {
19 // We use AbsTimeout to remind ourselves that the timeout is an absolute time.
20 // This is a simple wrapper around the timespec struct that also keeps track of
21 // whether the time is in realtime or monotonic time.
22 class AbsTimeout {
23   timespec timeout;
24   bool realtime_flag;
AbsTimeout(timespec ts,bool realtime)25   LIBC_INLINE constexpr explicit AbsTimeout(timespec ts, bool realtime)
26       : timeout(ts), realtime_flag(realtime) {}
27 
28 public:
29   enum class Error { Invalid, BeforeEpoch };
get_timespec()30   LIBC_INLINE const timespec &get_timespec() const { return timeout; }
is_realtime()31   LIBC_INLINE bool is_realtime() const { return realtime_flag; }
32   LIBC_INLINE static constexpr cpp::expected<AbsTimeout, Error>
from_timespec(timespec ts,bool realtime)33   from_timespec(timespec ts, bool realtime) {
34     using namespace time_units;
35     if (ts.tv_nsec < 0 || ts.tv_nsec >= 1_s_ns)
36       return cpp::unexpected(Error::Invalid);
37 
38     // POSIX allows tv_sec to be negative. We interpret this as an expired
39     // timeout.
40     if (ts.tv_sec < 0)
41       return cpp::unexpected(Error::BeforeEpoch);
42 
43     return AbsTimeout{ts, realtime};
44   }
45 };
46 } // namespace internal
47 } // namespace LIBC_NAMESPACE
48 
49 #endif // LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_ABS_TIMEOUT_H
50