meta: add serial module for (de)serialising objects
This commit is contained in:
82
serial/serial.c
Normal file
82
serial/serial.c
Normal file
@@ -0,0 +1,82 @@
|
||||
#include "serial.h"
|
||||
|
||||
#include <blue/serial.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
extern const struct b_serial_format_ops z__b_bitcode_format_ops;
|
||||
extern const struct b_serial_format_ops z__b_json_format_ops;
|
||||
|
||||
static const struct b_serial_format_ops *format_ops[] = {
|
||||
[B_SERIAL_FORMAT_NONE] = NULL,
|
||||
[B_SERIAL_FORMAT_BITCODE] = &z__b_bitcode_format_ops,
|
||||
[B_SERIAL_FORMAT_JSON] = &z__b_json_format_ops,
|
||||
};
|
||||
static const size_t nr_format_ops = sizeof format_ops / sizeof format_ops[0];
|
||||
|
||||
enum b_status b_serial_ctx_create(struct b_serial_ctx **out)
|
||||
{
|
||||
struct b_serial_ctx *ctx = malloc(sizeof *ctx);
|
||||
if (!ctx) {
|
||||
return B_ERR_NO_MEMORY;
|
||||
}
|
||||
|
||||
memset(ctx, 0x0, sizeof *ctx);
|
||||
|
||||
enum b_status status = b_stream_pipeline_create(2048, &ctx->ctx_pipeline);
|
||||
if (!B_OK(status)) {
|
||||
free(ctx);
|
||||
return status;
|
||||
}
|
||||
|
||||
*out = ctx;
|
||||
return B_SUCCESS;
|
||||
}
|
||||
|
||||
enum b_status b_serial_ctx_destroy(struct b_serial_ctx *ctx)
|
||||
{
|
||||
b_stream_pipeline_destroy(ctx->ctx_pipeline);
|
||||
free(ctx);
|
||||
return B_SUCCESS;
|
||||
}
|
||||
|
||||
static const struct b_serial_format_ops *get_formatter(enum b_serial_format fmt)
|
||||
{
|
||||
if (fmt < 0 || fmt >= nr_format_ops) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return format_ops[fmt];
|
||||
}
|
||||
|
||||
enum b_status b_serial_ctx_serialise(
|
||||
struct b_serial_ctx *ctx, enum b_serial_format fmt,
|
||||
struct b_object *src, struct b_stream *dest, enum b_serial_flags flags)
|
||||
{
|
||||
const struct b_serial_format_ops *ops = get_formatter(fmt);
|
||||
if (!ops) {
|
||||
return B_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
if (!ops->fmt_serialise) {
|
||||
return B_ERR_NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
return ops->fmt_serialise(ctx, src, dest, flags);
|
||||
}
|
||||
|
||||
enum b_status b_serial_ctx_deserialise(
|
||||
struct b_serial_ctx *ctx, enum b_serial_format fmt,
|
||||
struct b_stream *src, struct b_object **dest, enum b_serial_flags flags)
|
||||
{
|
||||
const struct b_serial_format_ops *ops = get_formatter(fmt);
|
||||
if (!ops) {
|
||||
return B_ERR_INVALID_ARGUMENT;
|
||||
}
|
||||
|
||||
if (!ops->fmt_deserialise) {
|
||||
return B_ERR_NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
return ops->fmt_deserialise(ctx, src, dest, flags);
|
||||
}
|
||||
Reference in New Issue
Block a user