CppServer  1.0.0.0
C++ Server Library
message.cpp
Go to the documentation of this file.
1 
10 
11 #include "errors/fatal.h"
12 #include "string/format.h"
13 
14 #include <cassert>
15 
16 namespace CppServer {
17 namespace Nanomsg {
18 
19 Message::Message() : _buffer(nullptr), _size(0), _type(0)
20 {
21 }
22 
23 Message::Message(size_t size, int type) : _buffer(nullptr), _size(0), _type(type)
24 {
25  assert((size > 0) && "Message size should be greater than zero!");
26  _buffer = (uint8_t*)nn_allocmsg(size, type);
27  if (_buffer == nullptr)
28  throwex CppCommon::SystemException("Failed to allocate a memory buffer of {} bytes for the nanomsg message! Nanomsg error: {}"_format(size, nn_strerror(nn_errno())));
29  _size = size;
30 }
31 
32 Message::Message(const void* data, size_t size, int type) : Message(size, type)
33 {
34  std::memcpy(_buffer, data, size);
35 }
36 
37 Message::Message(const Message& message) : Message(message.buffer(), message.size(), message.type())
38 {
39 }
40 
42 {
43  try
44  {
45  Clear();
46  }
47  catch (CppCommon::SystemException& ex)
48  {
49  fatality(CppCommon::SystemException(ex.string()));
50  }
51 }
52 
54 {
55  Message temp(message);
56  *this = std::move(temp);
57  return *this;
58 }
59 
61 {
62  if (_buffer != nullptr)
63  {
64  int result = nn_freemsg(_buffer);
65  if (result != 0)
66  throwex CppCommon::SystemException("Failed to free memory of the nanomsg message!");
67  _buffer = nullptr;
68  }
69 }
70 
71 void Message::Reallocate(size_t size)
72 {
73  assert((size > 0) && "Message size should be greater than zero!");
74  if (_buffer != nullptr)
75  {
76  _buffer = (uint8_t*)nn_reallocmsg(_buffer, size);
77  if (_buffer == nullptr)
78  throwex CppCommon::SystemException("Failed to reallocate a memory buffer of {} bytes for the nanomsg message! Nanomsg error: {}"_format(size, nn_strerror(nn_errno())));
79  }
80  else
81  {
82  _buffer = (uint8_t*)nn_allocmsg(size, _type);
83  if (_buffer == nullptr)
84  throwex CppCommon::SystemException("Failed to allocate a memory buffer of {} bytes for the nanomsg message! Nanomsg error: {}"_format(size, nn_strerror(nn_errno())));
85  }
86  _size = size;
87 }
88 
89 } // namespace Nanomsg
90 } // namespace CppServer
void Reallocate(size_t size)
Reallocate the message size.
Definition: message.cpp:71
Nanomsg message.
Definition: message.h:29
int type() const noexcept
Get the message type.
Definition: message.h:73
size_t size() const noexcept
Get the message size.
Definition: message.h:71
Nanomsg message definition.
C++ Server project definitions.
Definition: asio.h:24
Message()
Create an empty message.
Definition: message.cpp:19
void Clear()
Clear the message buffer.
Definition: message.cpp:60
Message & operator=(const Message &message)
Definition: message.cpp:53