Compare commits

...

4 Commits

Author SHA1 Message Date
blueloveTH
f2b6d90a72 Update mpack1.h 2026-07-21 14:30:09 +08:00
blueloveTH
2ed21e8814 Update bindings.c 2026-07-21 14:27:31 +08:00
blueloveTH
08fce73bbb Update mpack1.h 2026-07-21 14:27:18 +08:00
blueloveTH
4fc4d665ec improve mpack 2026-07-21 14:09:27 +08:00
3 changed files with 49 additions and 2 deletions

View File

@ -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
/**

View File

@ -0,0 +1,20 @@
#pragma once
#include "mpack.h"
#include "pocketpy.h"
#ifdef __cplusplus
extern "C" {
#endif
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)(py_StackRef tmp, 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);
#ifdef __cplusplus
}
#endif

View File

@ -1,8 +1,22 @@
#include "pocketpy.h"
#include "mpack.h"
#include "mpack1.h"
#include <assert.h>
_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(tmp, 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);
}