GOJ-Runtime/serialization.c
Joseph Umana da34a7b62e
init
Signed-off-by: Joseph Umana <joseph@josephumana.com>
2025-07-25 16:32:30 -04:00

60 lines
1.8 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "structs.h"
#define WATERMARK {0x69, 0x6E, 0x79, 0x72, 0x74, 0x62, 0x75}
#define VERSION 0x00
// Number of chars required to represent any 64 bit int/uint + NUL
#define INT_BUFFER_SIZE 21
#define SUM_BYTES(x) totalBytes += x
#define CONCAT_BYTES(dst, src, size) memcpy(dst, src, size); \
dst += size;
// len_fb | fb | runtime
// WARNING: This approach assumes uniform endiness and architechture
// TODO: Make it more portable?
// TODO: this is horrible. i need a better way. maybe a serialization lib or c++
// rewrite?
uint64_t calcSize(RunResult* result) {
uint64_t totalBytes = 0;
size_t feedbackLen = strlen(result->feedback);
totalBytes += sizeof(feedbackLen);
totalBytes += feedbackLen;
totalBytes += sizeof(result->runtime);
totalBytes += sizeof(result->maxRss);
totalBytes += sizeof(result->flags);
totalBytes += sizeof(result->exitCode);
return totalBytes;
}
SerializationResult serializeResult(RunResult* result) {
uint64_t size = calcSize(result);
uint8_t* buf = malloc(size);
uint8_t* bufCursor = buf;
size_t feedbackLen = strlen(result->feedback);
CONCAT_BYTES(bufCursor, &feedbackLen, sizeof(feedbackLen));
CONCAT_BYTES(bufCursor, result->feedback, feedbackLen);
CONCAT_BYTES(bufCursor, &result->runtime, sizeof(result->runtime));
CONCAT_BYTES(bufCursor, &result->maxRss, sizeof(result->maxRss));
CONCAT_BYTES(bufCursor, &result->flags, sizeof(result->flags));
CONCAT_BYTES(bufCursor, &result->exitCode, sizeof(result->exitCode));
SerializationResult serialResult = {
.data = buf,
.size = size
};
return serialResult;
}