#include <unistd.h>
+#include <memory>
+#include <type_traits>
+
#include "aul/common/exception.hh"
#include "aul/common/log_private.hh"
#include "aul/socket/client.hh"
namespace aul {
+namespace {
+
+// POD type
+class Header {
+ public:
+ int cmd;
+ int len;
+ int opt;
+};
+
+} // namespace
+
Client::Client(std::string path, int timeout_msec) : Socket(std::move(path)) {
int retry = 2;
do {
}
int Client::Recv(Packet** packet) {
- int cmd = -1;
- void* p = reinterpret_cast<void*>(&cmd);
- int ret = Socket::Recv(p, sizeof(cmd));
- if (ret < 0)
- return ret;
+ Header header;
+ static_assert(std::is_standard_layout<Header>(),
+ "Header should be POD type");
+ static_assert(std::is_trivial<Header>(), "Header should be POD type");
- int size = -1;
- p = reinterpret_cast<void*>(&size);
- ret = Socket::Recv(p, sizeof(size));
+ int ret = Socket::Recv(&header, sizeof(Header));
if (ret < 0)
return ret;
- if (size < 0 || size > MAX_PAYLOAD_SIZE) {
- _E("Invalid size(%d)", size);
+ if (header.len < 0 || header.len > MAX_PAYLOAD_SIZE) {
+ _E("Invalid size(%d)", header.len);
return -ECOMM;
}
- int opt = -1;
- p = reinterpret_cast<void*>(&opt);
- ret = Socket::Recv(p, sizeof(opt));
- if (ret < 0)
- return ret;
-
- unsigned char* buf = new (std::nothrow) unsigned char[size];
- if (buf == nullptr) {
- _E("Out of memory");
- return -ENOMEM;
- }
-
- ret = Socket::Recv(reinterpret_cast<void*>(buf), size);
+ std::vector<unsigned char> buf(header.len);
+ ret = Socket::Recv(buf.data(), header.len);
if (ret < 0) {
- delete[] buf;
return ret;
}
- std::vector<unsigned char> data(buf, buf + size);
- delete[] buf;
-
- *packet = new (std::nothrow) Packet(cmd, opt, data);
+ *packet = new (std::nothrow) Packet(header.cmd, header.opt, std::move(buf));
if (*packet == nullptr) {
_E("Out of memory");
return -ENOMEM;