libtransistor
A userland library for the Nintendo Switch
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros
waiter.hpp
Go to the documentation of this file.
1 
6 #pragma once
7 
8 #include<libtransistor/cpp/types.hpp>
10 
11 #include<functional>
12 #include<variant>
13 #include<memory>
14 
15 namespace trn {
16 
17 class Waiter;
18 
19 class WaitHandle : public std::enable_shared_from_this<WaitHandle> {
20  public:
21  WaitHandle(Waiter *waiter, std::variant<std::unique_ptr<std::function<bool()>>, std::unique_ptr<std::function<uint64_t()>>> callback);
22  ~WaitHandle();
23 
24  void Signal();
25  void ResetSignal();
26  void Cancel();
27 
28  wait_record_t *record;
29  private:
30  friend class Waiter;
31  static bool EventShim(void *data, handle_t handle);
32  static uint64_t DeadlineShim(void *data);
33  static bool SignalShim(void *data);
34 
35  template<typename R>
36  R InvokeCallback() {
37  // make sure we don't get destroyed before this function returns
38  std::shared_ptr<WaitHandle> self = shared_from_this();
39 
40  if((*std::get<std::unique_ptr<std::function<R()>>>(callback))()) {
41  return true;
42  } else {
43  // this is why we need to extend our lifetime
44  is_cancelled = true;
45  return false;
46  }
47  }
48  std::variant<std::unique_ptr<std::function<bool()>>, std::unique_ptr<std::function<uint64_t()>>> callback;
49  Waiter *waiter;
50  bool is_cancelled = false;
51 };
52 
53 class Waiter {
54  public:
55  Waiter();
56 
57  /* callback should return true if this handle should be kept in the wait list */
58  /* when WaitHandle dies, it will unregister itself */
59  std::shared_ptr<WaitHandle> Add(KWaitable &waitable, std::function<bool()> callback);
60  std::shared_ptr<WaitHandle> AddDeadline(uint64_t deadline, std::function<uint64_t()> callback);
61  std::shared_ptr<WaitHandle> AddSignal(std::function<bool()> callback);
62  Result<std::nullopt_t> Wait(uint64_t timeout);
63 
64  ~Waiter();
65 
66  waiter_t *waiter;
67 };
68 
69 }
Manager for waiting on synchronizable handles.
Definition: waiter.hpp:53
Definition: waiter.hpp:19
uint32_t handle_t
Resource handle.
Definition: types.h:38
Definition: types.hpp:71