ST_engine  0.3-ALPHA
message.hpp
1 /* This file is part of the "ST" project.
2  * You may use, distribute or modify this code under the terms
3  * of the GNU General Public License version 2.
4  * See LICENCE.txt in the root directory of the project.
5  *
6  * Author: Maxim Atanasov
7  * E-mail: maxim.atanasov@protonmail.com
8  */
9 
10 #ifndef ST_MESSAGE_HPP
11 #define ST_MESSAGE_HPP
12 
13 
14 #include <memory>
15 #include <ST_util/linear_frame_allocator_256.hpp>
16 
18 
21 class message {
22 private:
23  static ST::linear_frame_allocator_256<message> allocator;
24  std::shared_ptr<void> data; //yes, this holds anything created with make_data<>() AND calls the correct destructor
25 
26 public:
27  //An additional 48 bits (3 bytes) of data can be stored here. We're 8 byte aligned, so this is for free.
28  uint32_t base_data0 = 0; //additional 32 bits
29  uint16_t base_data1 = 0; //additional 16 bits
30  uint8_t base_data2 = 0; //additional 8 bits
31 
32  uint8_t msg_name{};
33 
34  [[nodiscard]] void *get_data() const;
35 
36  [[nodiscard]] message *make_copy() const;
37 
38  message() = default;
39 
44  explicit message(uint8_t name, const std::shared_ptr<void> &data = nullptr) {
45  this->msg_name = name;
46  this->data = data;
47  }
48 
49  /*
50  * @param name The type of message. See <b>ST::msg_type</b>.
51  * @param base_data0 32 bits of data. Use this if you want to avoid creating a shared pointer.
52  * @param data The data the message carries - created with <b>make_data<>()</b> or is <b>nullptr</b>
53  */
54  message(uint8_t name, uint32_t base_data0, const std::shared_ptr<void> &data = nullptr) {
55  this->msg_name = name;
56  this->base_data0 = base_data0;
57  this->data = data;
58  }
59 
60  static void *operator new(size_t) {
61  return allocator.allocate();
62  }
63 
64  static void operator delete(void *) {}
65 
66  ~message() {
67  if (data != nullptr) {
68  this->data.reset();
69  }
70  }
71 
72 };
73 
74 static_assert(sizeof(message) == 24, "sizeof message is not 24");
75 //INLINED METHODS
76 
80 inline void *message::get_data() const {
81  return this->data.get();
82 }
83 
87 inline message *message::make_copy() const {
88  return &(*allocator.allocate() = *this);
89 }
90 
91 #endif //ST_MESSAGE_HPP
A message object passed around in the message bus. Holds anything created with make_data<>().
Definition: message.hpp:21
message * make_copy() const
Definition: message.hpp:87
message(uint8_t name, const std::shared_ptr< void > &data=nullptr)
Definition: message.hpp:44
void * get_data() const
Definition: message.hpp:80