Banuba SDK
Loading...
Searching...
No Matches
event.hpp
1#pragma once
2
3#include <memory>
4
5#include <bnb/utils/class_unique_id.hpp>
6#include <bnb/utils/static_pool_allocator.hpp>
7#include <bnb/utils/allocate_unique.hpp>
8#include <bnb/utils/defs.hpp>
9
10#include <chrono>
11#include <functional>
12#include <unordered_map>
13#include <string>
14
15namespace bnb
16{
17 /**
18 * @addtogroup Utils
19 * @{
20 */
21
22 using event_id_t = size_t;
23 using handler_id_t = size_t;
24
26 {
27 event_id_t event_id;
28 bool is_required = false;
29
30 subscription_request_t(event_id_t a_id)
31 : event_id(a_id)
32 {
33 }
34 subscription_request_t(event_id_t a_id, bool is_req)
35 : event_id(a_id)
36 , is_required(is_req)
37 {
38 }
39 };
40
41
42 class BNB_EXPORT base_event_iface
43 {
44 public:
45 virtual ~base_event_iface() = default;
46 virtual event_id_t get_type_id() const noexcept = 0;
47 };
48
49 template<typename Event, size_t MaxElements = 3 * 2>
50 // align to common cacheline(16) to prevent false sharing
51 class alignas(16) base_event : public base_event_iface,
52 public identified_class<event_id_t, Event>
53 {
54 public:
55 inline const static event_id_t id = identified_class<event_id_t, Event>::get_id();
56
57 event_id_t get_type_id() const noexcept final
58 {
59 return id;
60 }
61
63 };
64
65
66 template<typename Event>
67 class time_stamped_event : public base_event<Event>
68 {
69 public:
70 using time_stamp_t = std::chrono::time_point<std::chrono::high_resolution_clock>;
72 : time_stamp(std::chrono::high_resolution_clock::now())
73 {
74 }
75 const time_stamp_t time_stamp;
76 };
77
78 template<typename T, int Count>
79 class simple_event : public base_event<simple_event<T, Count>>
80 {
81 public:
82 template<typename... Args>
83 explicit simple_event(Args&&... args)
84 : value(args...)
85 {
86 }
87
88 T value;
89 };
90
91 template<int Count>
92 class empty_event : public base_event<empty_event<Count>>
93 {
94 };
95
96 class effect_event : public base_event<effect_event>
97 {
98 public:
99 using params_t = std::unordered_map<std::string, std::string>;
100 explicit effect_event(const std::string& a_name, const params_t& a_params)
101 : name(a_name)
102 , params(a_params)
103 {
104 }
105
106 const std::string name;
107 const params_t params;
108 };
109
110 using base_event_ptr = std::shared_ptr<const base_event_iface>;
111 using base_event_deleter = std::function<void(const bnb::base_event_iface*)>;
112
113 template<typename T>
114 using event_uptr = std::unique_ptr<T, base_event_deleter>;
115
116 using base_event_uptr = event_uptr<const base_event_iface>;
117
118
119 template<typename T, typename... Args>
120 inline std::unique_ptr<T, base_event_deleter> make_unique_event(Args&&... args)
121 {
122 return allocate_unique<T, typename T::allocator, base_event_deleter, Args&&...>(
123 typename T::allocator(),
124 std::forward<Args>(args)...
125 );
126 }
127 /** @} */ // endgroup utils
128} // namespace bnb