LoginSignup
1
1

More than 5 years have passed since last update.

C++でchunkedデータからmsgpackデシリアイズ

Posted at

標準入出力、パイプ、ネットワーク通信のようなデータストリームで断片化される可能性があるデータをmsgpackでデシリアイズする方法。ちなみにデータストリーム(例えばstd::cin)から読み込める場合は自分でデータを読み込むまでもなく msgpack::Unpacker unpacker(std::cin); などとしてデシリアイザを作成できる。

毎回忘れるのでメモ。

#include <msgpack.hpp>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  // 標準入力から読み込みのための変数
  static const size_t BUFSIZE = 4096;
  int rc;
  char buf[BUFSIZE];

  // Unpacker
  msgpack::unpacker unpkr;

  // 標準入力から読み込み                                                                                                                                                                                           
  while (0 < (rc = read(0, buf, sizeof(buf)))) {

    // 残りバッファの確保                                                                                                                                                                                           
    unpkr.reserve_buffer(rc);
    // データのコピー                                                                                                                                                                                               
    memcpy(unpkr.buffer(), buf, rc);
    // バッファの読み込み                                                                                                                                                                                           
    unpkr.buffer_consumed(rc);

    msgpack::unpacked result;
    // 結果の取得                                                                                                                                                                                                   
    while (unpkr.next(&result)) {
      const msgpack::object &obj = result.get();
      printf("%d\n", obj.type);

      // メモリ解放                                                                                                                                                                                                 
      result.zone().reset();
    }
  }

  return 0;
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1