modular-worm/plugins/6_database.h

90 lines
2.9 KiB
C

#pragma once
#include <stdint.h>
#include <string.h>
#include "api.h"
#include "error_codes.h"
#define DB_QUERY_ADD 1
#define DB_QUERY_DELETE 2
#define DB_QUERY_GET 3
typedef struct {
uint8_t type;
uint32_t name;
void *content;
uint32_t length;
} p6_query_t;
typedef struct {
uint8_t err_code;
void *content;
uint32_t length;
} p6_response_t;
#define P6_PAGE_SIZE 1000
#define P6_CASE_TO_INDEX(page, name) (page * P6_PAGE_SIZE + name + 1)
#define P6_PAGE_METADATA(page) (page * P6_PAGE_SIZE)
/*
* @param res uint8_t See error_codes.h
* @param page uint32_t The page to write in (typically the plugin id)
* @param name uint32_t The id of the variable within the page
* @param value void* The content of the variable
* @param length uint32_t The length of the variable
*/
#define P6_DATABASE_WRITE(res, page, name, value, length) \
{ \
if ((page != version.id && page < 256)) \
res = ERR_FORBIDDEN; \
else { \
p6_query_t query = {DB_QUERY_ADD, P6_CASE_TO_INDEX(page, name), value, length}; \
api_msg_t msg; \
api_send_message_instant((api_plugin_t){6, 0, 0, 0}, &query, sizeof query, 1); \
res = API_RECEIVE_MESSAGE(&((api_plugin_t){6, 0, 0, 0}), msg); \
if (res == SUCCESS) \
res = ((p6_response_t *)(msg.content))->err_code; \
} \
}
/*
* @param res p6_response_t The response of the plugin, which contains the variable
* @param page uint32_t The page to write in (typically the plugin id)
* @param name uint32_t The id of the variable within the page
*/
#define P6_DATABASE_GET(res, page, name) \
{ \
if ((page != version.id && page < 256)) \
res.err_code = ERR_FORBIDDEN; \
else { \
p6_query_t query = {DB_QUERY_GET, P6_CASE_TO_INDEX(page, name), 0, 0}; \
api_msg_t msg; \
api_send_message_instant((api_plugin_t){6, 0, 0, 0}, &query, sizeof query, 1); \
res.err_code = API_RECEIVE_MESSAGE(&((api_plugin_t){6, 0, 0, 0}), msg); \
if (res.err_code == SUCCESS \
&& msg.content != NULL) { \
memcpy(&res, msg.content, sizeof res); \
} \
} \
}
/*
* @param res uint8_t See error_codes.h
* @param page uint32_t The page to write in (typically the plugin id)
* @param name uint32_t The id of the variable within the page
*/
#define P6_DATABASE_DELETE(res, page, name) \
{ \
if ((page != version.id && page < 256)) \
res = ERR_FORBIDDEN; \
else { \
p6_query_t query = {DB_QUERY_DELETE, P6_CASE_TO_INDEX(page, name), 0, 0}; \
api_msg_t msg; \
api_send_message_instant((api_plugin_t){6, 0, 0, 0}, &query, sizeof query, 1); \
res = API_RECEIVE_MESSAGE(&((api_plugin_t){6, 0, 0, 0}), msg); \
if (res == SUCCESS) \
res = ((p6_response_t *)(msg.content))->err_code; \
} \
}