1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <algorithm>
#include <iostream>
#include <vector>
struct test_msg
{
int32_t msg_type = 0;
int32_t msg_id = 0;
int32_t src = 0;
int32_t dst = 0;
std::string data;
bool Serialize(std::vector<char>& out) {
out.clear();
std::copy((char*)&msg_type, (char*)&msg_type + sizeof(msg_type), std::back_inserter(out));
std::copy((char*)&msg_id, (char*)&msg_id + sizeof(msg_id), std::back_inserter(out));
std::copy((char*)&src, (char*)&src + sizeof(src), std::back_inserter(out));
std::copy((char*)&dst, (char*)&dst + sizeof(dst), std::back_inserter(out));
std::copy(data.begin(), data.end(), std::back_inserter(out));
return true;
}
bool Deserialize(const std::vector<char>& out) {
int last_index = 0;
data.clear();
std::copy(out.begin() + last_index, out.begin() + last_index + sizeof(msg_type), (char*)&msg_type); last_index += sizeof(msg_type);
std::copy(out.begin() + last_index, out.begin() + last_index + sizeof(msg_id), (char*)&msg_id); last_index += sizeof(msg_id);
std::copy(out.begin() + last_index, out.begin() + last_index + sizeof(src), (char*)&src); last_index += sizeof(src);
std::copy(out.begin() + last_index, out.begin() + last_index + sizeof(dst), (char*)&dst); last_index += sizeof(dst);
std::copy(out.begin() + last_index, out.end(), std::back_inserter(data));
return true;
}
};
int main(int argc, char* argv[]) {
test_msg msg;
msg.msg_type = 11;
msg.msg_id = 22;
msg.src = 33;
msg.dst = 44;
msg.data = "this is test!this is test!this is test!";
std::vector<char> data;
printf("original : %d %d %d %d [%s]\n", msg.msg_type, msg.msg_id, msg.src, msg.dst, msg.data.c_str());
msg.Serialize(data);
msg.Deserialize(data);
printf("result : %d %d %d %d [%s]\n", msg.msg_type, msg.msg_id, msg.src, msg.dst, msg.data.c_str());
}
| |