message.cpp 1.41 KB
Newer Older
1
#include <network/message.hpp>
2
#include <assert.h>
3

4
Message::Message():
5
  body(nullptr),
6
  body_size(0),
7
  callback(nullptr)
8 9 10
{
}

11 12 13 14
Message::Message(const Message& message):
  callback(message.callback),
  header(message.header),
  name(message.name)
15
{
16
  this->set_body(message.body, message.body_size);
17 18
}

19
Message::~Message()
20 21 22 23
{
  delete[] this->body;
}

24
void Message::set_body(const char* body, int size)
25 26 27 28 29 30 31 32
{
  if (size == -1)
    size = ::strlen(body);
  this->body = new char[size];
  ::memcpy(this->body, body, size);
  this->set_body_size(size);
}

33 34 35 36 37
void Message::set_body(const google::protobuf::Message& msg)
{
  const int size = msg.ByteSize();
  this->body = new char[size];
  this->set_body_size(size);
38
  const auto&& res = msg.SerializeToArray(this->body, size);
39 40 41 42 43
  log_debug("Setting message body with protobuf: " << msg.ShortDebugString());
  assert(res);
}

void Message::set_name(const std::string& name)
44 45 46 47
{
  this->name = name;
}

48
void Message::set_body_size(int size)
49 50 51 52
{
  this->body_size = size;
}

53
void Message::pack()
54
{
55 56
  assert(this->name.size() > 0);

57 58
  std::ostringstream slength;
  slength << this->body_size;
59 60
  // . separator is ommited if name is 1 char long
  if ((this->name.size() == 1))
61 62 63 64 65 66 67
    this->header = std::string(this->name);
  else
    this->header = std::string(this->name) + ".";
  if (this->body_size > 0) // body size is ommited if it's 0
    this->header += slength.str() + ":";
  else
    this->header += ":";
68
}