rwindegger/msgpack23

一个现代的、仅包含头文件的 C++ 库,用于 MessagePack 的序列化和反序列化。msgpack.org [c++23]

License

MIT license

17 stars 2 forks

msgpack23

A modern, header-only C++ library for MessagePack serialization and deserialization.

Overview

msgpack23 是一个轻量级的库,它提供了一种直接的方法,用于将 C++ 数据结构序列化和反序列化为 MessagePack 格式。 它使用现代 C++ (面向 C++20 及更高版本) 编写,并利用模板和类型特征来提供灵活的、零依赖的解决方案,用于打包和解包各种数据类型。

Key Features

Getting Started

  1. Clone the Repository
git clone https://github.com/rwindegger/msgpack23.git
  1. Include the Header 由于这是一个 header-only 的库,只需在您的项目中包含主头文件即可:
#include "msgpack23.hpp"
  1. Pack and Unpack
#include <iostream>
#include <map>
#include "msgpack23.hpp"
int main() {
  // Create a map of some data
  std::map<std::string, int> original {{"apple", 1}, {"banana", 2}};

  // 1) Pack into a vector of std::byte
  msgpack23::Packer packer;
  auto packedData = packer(original);

  // 2) Unpack back into a map
  std::map<std::string, int> unpacked;
  msgpack23::Unpacker unpacker(packedData);
  unpacker(unpacked);

  // Verify the result
  for (auto const& [key, value] : unpacked) {
    std::cout << key << ": " << value << "\n";
  }
  return 0;
}

Custom Types

要序列化您自己的类型,请定义一个 packunpack 函数。 pack 应该接受一个 T &unpack 应该接受一个 T &

struct MyData {
  int64_t my_integer;
  std::string my_string;

  template<typename T>
  std::vector<std::byte> pack(T &packer) const {
   return packer(my_integer, my_string);
  }

  template<typename T>
  void unpack(T &unpacker) {
   unpacker(my_integer, my_string);
  }
};

现在您可以像使用任何内置类型一样使用 MyDatamsgpack23

MyData const my_data {42, "Hello" };
auto const data = msgpack23::pack(my_data);
auto obj = msgpack23::unpack<MyData>(data);

Why msgpack23?

Contributing

欢迎贡献、错误报告和功能请求! 随时打开一个 issue 或者提交一个 pull request。

  1. Fork it!
  2. Create your feature branch: git checkout -b feature/my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin feature/my-new-feature
  5. Submit a pull request

License

该项目基于 MIT License 授权。

祝您打包(和解包)愉快! 如果您有任何问题或反馈,请打开一个 issue 或开始讨论。