Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <type_traits>
- #include <thread>
- #include <cstdint>
- #include <tuple>
- #include <vector>
- using buf_t = std::vector<unsigned char>;
- template <typename T>
- std::size_t binary_serialize(buf_t& buf, std::size_t index, const T& variable)
- {
- std::copy_n(reinterpret_cast<const unsigned char*>(&variable), sizeof(T), &buf[index]);
- return index + sizeof(T);
- }
- template <typename T>
- std::size_t binary_deserialize(const buf_t& buf, std::size_t index, T* variable)
- {
- *variable = *reinterpret_cast<const T*>(&buf[index]);
- return index + sizeof(T);
- }
- class Message {
- public:
- static buf_t serialize(const Message& msg)
- {
- buf_t buf;
- buf.resize(sizeof(a_variable) + sizeof(b_variable));
- std::size_t index = 0;
- index = binary_serialize(buf, index, msg.a_variable);
- index = binary_serialize(buf, index, msg.b_variable);
- return buf;
- }
- static Message deserialize(const buf_t& buf)
- {
- Message msg;
- std::size_t index = 0;
- index = binary_deserialize(buf, index, &msg.a_variable);
- index = binary_deserialize(buf, index, &msg.b_variable);
- return msg;
- }
- int a_variable, b_variable;
- };
- class LoginMessage : public Message {
- public:
- static buf_t serialize(const LoginMessage& msg)
- {
- buf_t buf = Message::serialize(msg);
- std::size_t index = buf.size();
- buf.resize(buf.size() + sizeof(c_variable));
- index = binary_serialize(buf, index, msg.c_variable);
- return buf;
- }
- static LoginMessage deserialize(const buf_t& buf)
- {
- LoginMessage msg;
- static_cast<Message&>(msg) = Message::deserialize(buf);
- std::size_t index = buf.size() - sizeof(c_variable);
- index = binary_deserialize(buf, index, &msg.c_variable);
- return msg;
- }
- float c_variable;
- };
- int main(int argc, char* argv[])
- {
- (void)argc;
- (void)argv;
- LoginMessage msg;
- msg.a_variable = 1;
- msg.b_variable = 2;
- msg.c_variable = 3.1f;
- buf_t buf = LoginMessage::serialize(msg);
- msg = LoginMessage::deserialize(buf);
- std::cout << msg.a_variable << " " << msg.b_variable << " " << msg.c_variable << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement