From 4fc4d665ecfddd9e963ccfe06e5d7a28655b1c77 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Tue, 21 Jul 2026 14:09:27 +0800 Subject: [PATCH] improve mpack --- 3rd/msgpack/include/mpack.h | 2 +- 3rd/msgpack/include/mpack1.h | 12 ++++++++++++ 3rd/msgpack/src/bindings.c | 29 ++++++++++++++++++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 3rd/msgpack/include/mpack1.h diff --git a/3rd/msgpack/include/mpack.h b/3rd/msgpack/include/mpack.h index 1f2386a8..7c16a5eb 100644 --- a/3rd/msgpack/include/mpack.h +++ b/3rd/msgpack/include/mpack.h @@ -251,7 +251,7 @@ * types in @ref docs/protocol.md for more information. */ #ifndef MPACK_EXTENSIONS -#define MPACK_EXTENSIONS 0 +#define MPACK_EXTENSIONS 1 #endif /** diff --git a/3rd/msgpack/include/mpack1.h b/3rd/msgpack/include/mpack1.h new file mode 100644 index 00000000..225cb021 --- /dev/null +++ b/3rd/msgpack/include/mpack1.h @@ -0,0 +1,12 @@ +#pragma once + +#include "mpack.h" +#include "pocketpy.h" + +typedef bool (*is_mpack_ext_t)(py_Type type); +typedef bool (*py_to_mpack_ext_t)(py_Ref object, mpack_writer_t* writer); +typedef bool (*mpack_to_py_ext_t)(mpack_node_t node); + +void mpack_config_exttype_callbacks(is_mpack_ext_t is_ext, + py_to_mpack_ext_t to_mpack, + mpack_to_py_ext_t to_py); \ No newline at end of file diff --git a/3rd/msgpack/src/bindings.c b/3rd/msgpack/src/bindings.c index d1951a81..84a4df55 100644 --- a/3rd/msgpack/src/bindings.c +++ b/3rd/msgpack/src/bindings.c @@ -1,8 +1,22 @@ #include "pocketpy.h" -#include "mpack.h" +#include "mpack1.h" #include +_Static_assert(MPACK_EXTENSIONS == 1, "You should change MPACK_EXTENSIONS in mpack.h to 1"); + +static is_mpack_ext_t is_mpack_ext; +static py_to_mpack_ext_t py_to_mpack_ext; +static mpack_to_py_ext_t mpack_to_py_ext; + +void mpack_config_exttype_callbacks(is_mpack_ext_t is_ext, + py_to_mpack_ext_t to_mpack, + mpack_to_py_ext_t to_py) { + is_mpack_ext = is_ext; + py_to_mpack_ext = to_mpack; + mpack_to_py_ext = to_py; +} + static bool mpack_to_py(mpack_node_t node) { py_StackRef tmp = py_pushtmp(); @@ -69,6 +83,14 @@ static bool mpack_to_py(mpack_node_t node) { } break; } + + case mpack_type_ext: { + if(!mpack_to_py_ext) { + return RuntimeError("msgpack: mpack_to_py_ext is not set, cannot handle ext type"); + } + if(!mpack_to_py_ext(node)) return false; + break; + } default: return ValueError("msgpack: invalid node type"); } return true; @@ -153,6 +175,11 @@ static bool py_to_mpack(py_Ref object, mpack_writer_t* writer) { break; } default: { + if(is_mpack_ext && is_mpack_ext(object->type)) { + assert(py_to_mpack_ext != NULL); + return py_to_mpack_ext(object, writer); + break; + } mpack_write_nil(writer); return TypeError("msgpack: unsupported type '%t'", object->type); }