SharedStorage/core/Command.cpp
2025-04-21 19:28:00 +00:00

79 lines
2.8 KiB
C++

//
// Created by Kirill Zhukov on 20.04.2025.
//
#include "Command.h"
#include <istream>
#include <ostream>
namespace usub::core {
Command::Command() {
ready.store(0, std::memory_order_relaxed);
response_ready.store(0, std::memory_order_relaxed);
op = OperationType::PUT;
key = utils::Hash128{};
value_size = 0;
response_size = 0;
}
Command::Command(const Command &other) {
ready.store(other.ready.load(std::memory_order_relaxed), std::memory_order_relaxed);
op = other.op;
key = other.key;
value_size = other.value_size;
std::memcpy(value, other.value, other.value_size);
response_ready.store(other.response_ready.load(std::memory_order_relaxed), std::memory_order_relaxed);
response_size = other.response_size;
std::memcpy(response, other.response, other.response_size);
}
Command &Command::operator=(const Command &other) {
if (this != &other) {
ready.store(other.ready.load(std::memory_order_relaxed), std::memory_order_relaxed);
op = other.op;
key = other.key;
value_size = other.value_size;
std::memcpy(value, other.value, other.value_size);
response_ready.store(other.response_ready.load(std::memory_order_relaxed), std::memory_order_relaxed);
response_size = other.response_size;
std::memcpy(response, other.response, other.response_size);
}
return *this;
}
void Command::serialize(std::ostream &out) const {
auto op_val = static_cast<uint8_t>(op);
out.write(reinterpret_cast<const char *>(&op_val), sizeof(op_val));
out.write(reinterpret_cast<const char *>(&key), sizeof(key));
out.write(reinterpret_cast<const char *>(&value_size), sizeof(value_size));
out.write(value, value_size);
out.write(reinterpret_cast<const char *>(&response_size), sizeof(response_size));
out.write(response, response_size);
}
Command Command::deserialize(std::istream &in) {
Command cmd;
uint8_t op_val;
in.read(reinterpret_cast<char *>(&op_val), sizeof(op_val));
cmd.op = static_cast<OperationType>(op_val);
in.read(reinterpret_cast<char *>(&cmd.key), sizeof(cmd.key));
in.read(reinterpret_cast<char *>(&cmd.value_size), sizeof(cmd.value_size));
if (cmd.value_size > 0)
in.read(cmd.value, cmd.value_size);
in.read(reinterpret_cast<char *>(&cmd.response_size), sizeof(cmd.response_size));
if (cmd.response_size > 0)
in.read(cmd.response, cmd.response_size);
cmd.ready.store(1, std::memory_order_relaxed);
cmd.response_ready.store(1, std::memory_order_relaxed);
return cmd;
}
}