SelectHelper.h revision 321369
1//===-- SelectHelper.h ------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef liblldb_SelectHelper_h_
11#define liblldb_SelectHelper_h_
12
13#include "lldb/Utility/Status.h" // for Status
14#include "lldb/lldb-types.h"    // for socket_t
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/Optional.h"
18
19#include <chrono>
20
21class SelectHelper {
22public:
23  // Defaults to infinite wait for select unless you call SetTimeout()
24  SelectHelper();
25
26  // Call SetTimeout() before calling SelectHelper::Select() to set the
27  // timeout based on the current time + the timeout. This allows multiple
28  // calls to SelectHelper::Select() without having to worry about the
29  // absolute timeout as this class manages to set the relative timeout
30  // correctly.
31  void SetTimeout(const std::chrono::microseconds &timeout);
32
33  // Call the FDSet*() functions before calling SelectHelper::Select() to
34  // set the file descriptors that we will watch for when calling
35  // select. This will cause FD_SET() to be called prior to calling select
36  // using the "fd" provided.
37  void FDSetRead(lldb::socket_t fd);
38  void FDSetWrite(lldb::socket_t fd);
39  void FDSetError(lldb::socket_t fd);
40
41  // Call the FDIsSet*() functions after calling SelectHelper::Select()
42  // to check which file descriptors are ready for read/write/error. This
43  // will contain the result of FD_ISSET after calling select for a given
44  // file descriptor.
45  bool FDIsSetRead(lldb::socket_t fd) const;
46  bool FDIsSetWrite(lldb::socket_t fd) const;
47  bool FDIsSetError(lldb::socket_t fd) const;
48
49  // Call the system's select() to wait for descriptors using
50  // timeout provided in a call the SelectHelper::SetTimeout(),
51  // or infinite wait if no timeout was set.
52  lldb_private::Status Select();
53
54protected:
55  struct FDInfo {
56    FDInfo()
57        : read_set(false), write_set(false), error_set(false),
58          read_is_set(false), write_is_set(false), error_is_set(false) {}
59
60    void PrepareForSelect() {
61      read_is_set = false;
62      write_is_set = false;
63      error_is_set = false;
64    }
65
66    bool read_set : 1, write_set : 1, error_set : 1, read_is_set : 1,
67        write_is_set : 1, error_is_set : 1;
68  };
69  llvm::DenseMap<lldb::socket_t, FDInfo> m_fd_map;
70  llvm::Optional<std::chrono::steady_clock::time_point> m_end_time;
71};
72
73#endif // liblldb_SelectHelper_h_
74