Skip to content

Instantly share code, notes, and snippets.

@NorioKobota
Last active July 12, 2016 12:32
Show Gist options
  • Save NorioKobota/10c046787de0319ded4aaca570292fd4 to your computer and use it in GitHub Desktop.
Save NorioKobota/10c046787de0319ded4aaca570292fd4 to your computer and use it in GitHub Desktop.
Dealing with msgpack easily on C++
// NOTE: linear-cpp/include/any.h, binary.h, optional.h are header only.
// $ git clone --recursive https://github.com/linear-rpc/linear-cpp
// $ clang++ msgpack_bin.cpp -I linear-cpp/deps/msgpack/include -I linear-cpp/include -std=c++11
// $ ./a.out fname # create a msgpack binary file
// $ cat fname | ./a.out # dump it
#include <fstream>
#include <iostream>
#include "linear/any.h"
void w(const std::string& fname) {
char b[] = {0x00, 0x01, 0x02};
std::map<std::string, linear::type::any> m =
{
{"key1", 1},
{"key2", 3.14},
{"key3", "str in map"},
{"key4", std::vector<linear::type::any>({ -1, -3.14, "str in vec" })},
{"key5", linear::type::binary(b, sizeof(b))}
};
std::ofstream ofs(fname);
std::stringstream buffer;
msgpack::pack(buffer, m);
buffer.seekg(0);
ofs << buffer.str();
}
void r() {
std::istreambuf_iterator<char> begin(std::cin), end;
std::string s(begin, end);
msgpack::object_handle oh = msgpack::unpack(s.data(), s.size());
std::cout << "can't show msgpack::type::BIN: "
<< oh.get() << std::endl;
std::cout << "make it readble: "
<< linear::type::any(oh.get()).stringify() << std::endl;
}
int main(int argc, char* argv[]) {
if (argc > 1) {
w(argv[1]);
} else {
r();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment