test(hmpl): render interpolation tags

This commit is contained in:
2025-03-22 14:56:03 +00:00
parent aeea41b0e1
commit 546a35f1d2
12 changed files with 146 additions and 30 deletions

View File

@@ -0,0 +1,37 @@
{ stdenv, gcc, lib }:
stdenv.mkDerivation {
pname = "hectic";
version = "1.0";
src = ./.;
doCheck = true;
buildPhase = ''
mkdir -p target
${gcc}/bin/cc -Wall -Wextra -g \
-std=c99 \
-pedantic -fsanitize=address \
-c hectic.c -o target/hectic.o
${gcc}/bin/ar rcs target/libhectic.a target/hectic.o
'';
checkPhase = ''
mkdir -p target/test
for test_file in test/*.c; do
exe="target/test/$(basename ''${test_file%.c})"
${gcc}/bin/cc -Wall -Wextra -g -pedantic -fsanitize=address -I. "$test_file" -Ltarget -lhectic -o "$exe"
"$exe"
done
'';
installPhase = ''
mkdir -p $out/lib $out/include
cp target/libhectic.a $out/lib/
cp hectic.h $out/include/
'';
meta = {
description = "libhectic";
license = lib.licenses.mit;
};
}

340
package/c/hectic/hectic.c Normal file
View File

@@ -0,0 +1,340 @@
#include "hectic.h"
void set_output_color_mode(ColorMode mode) {
color_mode = mode;
}
// ------------
// -- Logger --
// ------------
const char* log_level_to_string(LogLevel level) {
switch (level) {
case LOG_LEVEL_DEBUG: return "DEBUG";
case LOG_LEVEL_LOG: return "LOG";
case LOG_LEVEL_INFO: return "INFO";
case LOG_LEVEL_NOTICE: return "NOTICE";
case LOG_LEVEL_WARN: return "WARN";
case LOG_LEVEL_EXCEPTION: return "EXCEPTION";
default: return "UNKNOWN";
}
}
LogLevel log_level_from_string(const char *level_str) {
if (!level_str) return LOG_LEVEL_INFO;
if (strcmp(level_str, "DEBUG") == 0)
return LOG_LEVEL_DEBUG;
else if (strcmp(level_str, "LOG") == 0)
return LOG_LEVEL_LOG;
else if (strcmp(level_str, "INFO") == 0)
return LOG_LEVEL_INFO;
else if (strcmp(level_str, "NOTICE") == 0)
return LOG_LEVEL_NOTICE;
else if (strcmp(level_str, "WARN") == 0)
return LOG_LEVEL_WARN;
else if (strcmp(level_str, "EXCEPTION") == 0)
return LOG_LEVEL_EXCEPTION;
else
return LOG_LEVEL_INFO;
}
LogLevel current_log_level = LOG_LEVEL_INFO;
void logger_level_reset() {
current_log_level = LOG_LEVEL_INFO;
}
void logger_level(LogLevel level) {
current_log_level = level;
}
void init_logger(void) {
current_log_level = log_level_from_string(getenv("LOG_LEVEL"));
}
char* log_message(LogLevel level, char *file, int line, const char *format, ...) {
if (level < current_log_level) {
return NULL;
}
time_t now = time(NULL);
struct tm tm_info;
localtime_r(&now, &tm_info);
static char timeStr[20];
strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", &tm_info);
fprintf(stderr, "%s %s %s:%d ", timeStr, log_level_to_string(level), file, line);
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
return timeStr;
}
// -----------
// -- utils --
// -----------
void substr(const char *src, char *dest, size_t start, size_t len) {
raise_debug("substring %s from %zu to %zu", src, start, len);
size_t srclen = strlen(src);
if (start >= srclen) {
dest[0] = '\0';
return;
}
if (start + len > srclen)
len = srclen - start;
strncpy(dest, src + start, len);
dest[len] = '\0';
}
// ----------
// -- Json --
// ----------
/* Utility: Skip whitespace */
static const char *json_skip_whitespace(const char *s) {
while (*s && isspace((unsigned char)*s))
s++;
return s;
}
/* Parse a JSON string (does not handle full escaping) */
static char *json_parse_string__(const char **s_ptr, Arena *arena) {
const char *s = *s_ptr;
if (*s != '"') return NULL;
s++; // skip opening quote
const char *start = s;
while (*s && *s != '"') {
if (*s == '\\') s++; // skip escaped char
s++;
}
if (*s != '"') return NULL;
size_t len = s - start;
char *str = arena_alloc(arena, len + 1);
if (!str) return NULL;
memcpy(str, start, len);
str[len] = '\0';
*s_ptr = s + 1; // skip closing quote
return str;
}
/* Parse a number using strtod */
static double json_parse_number__(const char **s_ptr) {
char *end;
double num = strtod(*s_ptr, &end);
*s_ptr = end;
return num;
}
/* Forward declaration */
static Json *json_parse_value__(const char **s, Arena *arena);
/* Parse a JSON array: [ value, value, ... ] */
static Json *json_parse_array__(const char **s, Arena *arena) {
if (**s != '[') return NULL;
(*s)++; // skip '['
*s = json_skip_whitespace(*s);
Json *array = arena_alloc(arena, sizeof(Json));
if (!array) return NULL;
memset(array, 0, sizeof(Json));
array->type = JSON_ARRAY;
Json *last = NULL;
if (**s == ']') { // empty array
(*s)++;
return array;
}
while (**s) {
Json *element = json_parse_value__(s, arena);
if (!element) return NULL;
if (!array->child)
array->child = element;
else {
last->next = element;
}
last = element;
*s = json_skip_whitespace(*s);
if (**s == ',') {
(*s)++;
*s = json_skip_whitespace(*s);
} else if (**s == ']') {
(*s)++;
break;
} else {
return NULL; // error
}
}
return array;
}
/* Parse a JSON object: { "key": value, ... } */
static Json *json_parse_object__(const char **s, Arena *arena) {
if (**s != '{') return NULL;
(*s)++; // skip '{'
*s = json_skip_whitespace(*s);
Json *object = arena_alloc(arena, sizeof(Json));
if (!object) return NULL;
memset(object, 0, sizeof(Json));
object->type = JSON_OBJECT;
Json *last = NULL;
if (**s == '}') {
(*s)++;
return object;
}
while (**s) {
char *key = json_parse_string__(s, arena);
if (!key) return NULL;
*s = json_skip_whitespace(*s);
if (**s != ':') return NULL;
(*s)++; // skip ':'
*s = json_skip_whitespace(*s);
Json *value = json_parse_value__(s, arena);
if (!value) return NULL;
value->key = key; // assign key to the value
if (!object->child)
object->child = value;
else {
last->next = value;
}
last = value;
*s = json_skip_whitespace(*s);
if (**s == ',') {
(*s)++;
*s = json_skip_whitespace(*s);
} else if (**s == '}') {
(*s)++;
break;
} else {
return NULL; // error
}
}
return object;
}
/* Full JSON value parser */
static Json *json_parse_value__(const char **s, Arena *arena) {
*s = json_skip_whitespace(*s);
if (**s == '"') {
Json *item = arena_alloc(arena, sizeof(Json));
if (!item) return NULL;
memset(item, 0, sizeof(Json));
item->type = JSON_STRING;
item->string = json_parse_string__(s, arena);
return item;
} else if (strncmp(*s, "null", 4) == 0) {
Json *item = arena_alloc(arena, sizeof(Json));
if (!item) return NULL;
memset(item, 0, sizeof(Json));
item->type = JSON_NULL;
*s += 4;
return item;
} else if (strncmp(*s, "true", 4) == 0) {
Json *item = arena_alloc(arena, sizeof(Json));
if (!item) return NULL;
memset(item, 0, sizeof(Json));
item->type = JSON_BOOL;
item->boolean = 1;
*s += 4;
return item;
} else if (strncmp(*s, "false", 5) == 0) {
Json *item = arena_alloc(arena, sizeof(Json));
if (!item) return NULL;
memset(item, 0, sizeof(Json));
item->type = JSON_BOOL;
item->boolean = 0;
*s += 5;
return item;
} else if ((**s == '-') || isdigit((unsigned char)**s)) {
Json *item = arena_alloc(arena, sizeof(Json));
if (!item) return NULL;
memset(item, 0, sizeof(Json));
item->type = JSON_NUMBER;
item->number = json_parse_number__(s);
return item;
} else if (**s == '[') {
return json_parse_array__(s, arena);
} else if (**s == '{') {
return json_parse_object__(s, arena);
}
return NULL;
}
Json *json_parse(Arena *arena, const char **s) {
return json_parse_value__(s, arena);
}
char *json_to_string(Arena *arena, Json *item) {
return json_to_string_with_opts(arena, item, 0);
}
/* Minimal JSON printer with raw output option.
When raw is non-zero and the item is a JSON_STRING, it is printed without quotes.
*/
char *json_to_string_with_opts(Arena *arena, Json *item, int raw) {
char *out = arena_alloc(arena, 1024);
if (!out)
return NULL;
char *ptr = out;
if (item->type == JSON_OBJECT) {
ptr += sprintf(ptr, "{");
Json *child = item->child;
while (child) {
ptr += sprintf(ptr, "\"%s\":", child->key ? child->key : "");
char *child_str = json_to_string_with_opts(arena, child, raw);
ptr += sprintf(ptr, "%s", child_str);
if (child->next)
ptr += sprintf(ptr, ",");
child = child->next;
}
sprintf(ptr, "}");
} else if (item->type == JSON_ARRAY) {
ptr += sprintf(ptr, "[");
Json *child = item->child;
while (child) {
char *child_str = json_to_string_with_opts(arena, child, raw);
ptr += sprintf(ptr, "%s", child_str);
if (child->next)
ptr += sprintf(ptr, ",");
child = child->next;
}
sprintf(ptr, "]");
} else if (item->type == JSON_STRING) {
if (raw)
sprintf(ptr, "%s", item->string);
else
sprintf(ptr, "\"%s\"", item->string);
} else if (item->type == JSON_NUMBER) {
sprintf(ptr, "%g", item->number);
} else if (item->type == JSON_BOOL) {
sprintf(ptr, item->boolean ? "true" : "false");
} else if (item->type == JSON_NULL) {
sprintf(ptr, "null");
}
return out;
}
/* Retrieve an object item by key (case-sensitive) */
Json *json_get_object_item(Json *object, const char *key) {
raise_debug("json get object item for %s", key);
if (!object || object->type != JSON_OBJECT)
return NULL;
Json *child = object->child;
while (child) {
raise_debug("child->key: %s, key: %s", child->key, key);
if (child->key && strcmp(child->key, key) == 0)
return child;
child = child->next;
}
return NULL;
}
//bool json_is_string(const Json * const item) {
// if (item == NULL) {
// return false;
// }
// return item->type == JSON_STRING;
//}

236
package/c/hectic/hectic.h Normal file
View File

@@ -0,0 +1,236 @@
#ifndef EPRINTF_HECTIC
#define EPRINTF_HECTIC
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
// -------------
// -- Helpers --
// -------------
// Helper macros for argument counting
// NOTE(yukkop): this ugly macroses for avoid all posible warnings
#define PP_CAT(a, b) a##b
// ------------
// -- Colors --
// ------------
// Color mode enumeration
typedef enum {
COLOR_MODE_AUTO,
COLOR_MODE_FORCE,
COLOR_MODE_DISABLE
} ColorMode;
// Static color mode variable
static ColorMode color_mode = COLOR_MODE_AUTO;
// Function to set color mode
void set_output_color_mode(ColorMode mode);
// Macros for detecting terminal and color usage
#define IS_TERMINAL() (isatty(fileno(stderr)))
#define USE_COLOR() ((color_mode == COLOR_MODE_FORCE) || (color_mode == COLOR_MODE_AUTO && IS_TERMINAL()))
#define COLOR_RED (USE_COLOR() ? "\033[1;31m" : "")
#define COLOR_RESET (USE_COLOR() ? "\033[0m" : "")
// ------------
// -- Errors --
// ------------
// Define color macros based on output type
//#define ERROR_PREFIX PP_CAT(COLOR_RED, "Error: ")
//#define ERROR_SUFFIX PP_CAT(COLOR_RESET, "\n")
#define ERROR_PREFIX (USE_COLOR() ? "\033[1;31mError: " : "Error: ")
#define ERROR_SUFFIX (USE_COLOR() ? "\033[0m\n" : "\n")
// eprintf handling 1 or more arguments
#define eprintf(fmt, ...) "%s" fmt "%s", ERROR_PREFIX, ##__VA_ARGS__, ERROR_SUFFIX
#define todo fprintf(stderr, "%sNot implimented yet%s", COLOR_RED, COLOR_RESET);exit(1)
// ------------
// -- Logger --
// ------------
typedef enum {
LOG_LEVEL_DEBUG,
LOG_LEVEL_LOG,
LOG_LEVEL_INFO,
LOG_LEVEL_NOTICE,
LOG_LEVEL_WARN,
LOG_LEVEL_EXCEPTION
} LogLevel;
void logger_level_reset();
void logger_level(LogLevel level);
LogLevel log_level_from_string(const char *level_str);
char* log_message(LogLevel level, char *file, int line, const char *format, ...);
#define raise_debug(fmt, ...) log_message(LOG_LEVEL_DEBUG, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define raise_log(fmt, ...) log_message(LOG_LEVEL_LOG, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define raise_info(fmt, ...) log_message(LOG_LEVEL_INFO, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define raise_notice(fmt, ...) log_message(LOG_LEVEL_NOTICE, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define raise_warn(fmt, ...) log_message(LOG_LEVEL_WARN, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define raise_exception(fmt, ...) log_message(LOG_LEVEL_EXCEPTION, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
// -----------
// -- arena --
// -----------
#define ARENA_DEFAULT_SIZE 1024
typedef struct {
void *begin;
void *current;
size_t capacity;
} Arena;
// NOTE(yukkop): This macro is used to define procedures so that `__LINE__` and `__FILE__`
// in `raise_debug` reflect the location where the macro is called, not where it's defined.
#define arena_alloc_or_null(arena, size) __extension__ ({ \
void *mem__ = NULL; \
if ((arena)->begin == 0) { \
*(arena) = arena_init(ARENA_DEFAULT_SIZE); \
} \
size_t current__ = (size_t)(arena)->current - (size_t)(arena)->begin; \
if ((arena)->capacity <= current__ || (arena)->capacity - current__ < (size)) {\
raise_debug("Arena %p (capacity %zu) used %zu cannot allocate %zu bytes", \
(arena)->begin, (arena)->capacity, current__, (size)); \
} else { \
raise_debug("Arena %p (capacity %zu) used %zu will allocate %zu bytes", \
(arena)->begin, (arena)->capacity, current__, (size)); \
mem__ = (arena)->current; \
(arena)->current = (char*)(arena)->current + (size); \
} \
raise_debug("Allocated at %p", mem__); \
mem__; \
})
#define arena_init(size) __extension__ ({ \
Arena arena__; \
arena__.begin = malloc(size); \
memset(arena__.begin, 0, size); \
arena__.current = arena__.begin; \
arena__.capacity = size; \
raise_debug("Initialized arena at %p with capacity %zu", arena__.begin, size); \
arena__; \
})
#define arena_reset(arena) __extension__ ({ \
(arena)->current = (arena)->begin; \
raise_debug("Arena %p reset", (arena)->begin); \
})
#define arena_free(arena) __extension__ ({ \
raise_debug("Freeing arena at %p", (arena)->begin); \
free((arena)->begin); \
})
#define arena_alloc(arena, size) __extension__ ({ \
void *mem__ = arena_alloc_or_null((arena), (size)); \
if (!mem__) { \
raise_debug("Arena out of memory when trying to allocate %zu bytes", (size)); \
raise_exception("Arena out of memory"); \
exit(1); \
} \
mem__; \
})
#define arena_strdup(arena, s) __extension__ ({ \
const char *s__ = (s); \
char *result__; \
if (s__) { \
size_t len__ = strlen(s__) + 1; \
result__ = (char *)arena_alloc(arena, len__); \
memcpy(result__, s__, len__); \
} else { \
result__ = NULL; \
} \
result__; \
})
#define arena_repstr(arena, src, start, len, rep) __extension__ ({ \
const char *src__ = (src); \
const char *rep__ = (rep); \
size_t start__ = (start); \
size_t len__ = (len); \
int src_len__ = strlen(src__); \
int rep_len__ = strlen(rep__); \
int new_len__ = src_len__ - len__ + 1 + rep_len__; \
char *new_str__ = (char *)arena_alloc(arena, new_len__ + 1); \
memcpy(new_str__, src__, start__); \
memcpy(new_str__ + start__, rep__, rep_len__); \
strcpy(new_str__ + start__ + rep_len__, src__ + start__ + len__ + 1); \
new_str__; \
})
#define arena_realloc_copy(arena, old_ptr, old_size, new_size) __extension__ ({ \
void *old__ = (old_ptr); \
size_t old_size__ = (old_size); \
size_t new_size__ = (new_size); \
void *new__ = NULL; \
if (old__ == NULL) { \
new__ = arena_alloc((arena), new_size__); \
} else if (new_size__ <= old_size__) { \
new__ = old__; \
} else { \
new__ = arena_alloc_or_null((arena), new_size__); \
if (new__) memcpy(new__, old__, old_size__); \
} \
new__; \
})
// ----------
// -- misc --
// ----------
void substr(const char *src, char *dest, size_t start, size_t len);
// ----------
// -- Json --
// ----------
typedef enum {
JSON_NULL,
JSON_BOOL,
JSON_NUMBER,
JSON_STRING,
JSON_ARRAY,
JSON_OBJECT
} JsonType;
/* Full JSON structure */
typedef struct Json {
struct Json *next; /* Next sibling */
struct Json *child; /* Child element (for arrays/objects) */
JsonType type;
char *key; /* Key if item is in an object */
union {
double number;
char *string;
int boolean;
};
} Json;
Json *json_parse(Arena *arena, const char **s);
char *json_to_string(Arena *arena, Json *item);
char *json_to_string_with_opts(Arena *arena, Json *item, int raw);
/* Retrieve an object item by key (case-sensitive) */
Json *json_get_object_item(Json *object, const char *key);
#endif // EPRINTF_H

View File

@@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "hectic.h"
#define TEST_RAISE_GENERIC(LOG_MACRO, LEVEL, LEVEL_STR) do { \
FILE *orig_stderr = stderr; \
FILE *temp = tmpfile(); \
char result_buffer[256]; \
if (!temp) { perror("tmpfile"); exit(EXIT_FAILURE); } \
stderr = temp; \
logger_level(LEVEL); \
const char* time_str = LOG_MACRO("message"); \
logger_level_reset(); \
fflush(stderr); \
fseek(temp, 0, SEEK_SET); \
size_t nread = fread(result_buffer, 1, sizeof(result_buffer)-1, temp); \
result_buffer[nread] = '\0'; \
stderr = orig_stderr; \
fclose(temp); \
char expected_buffer[256]; \
sprintf(expected_buffer, "%s " LEVEL_STR " " __FILE__ ":%d message\n", time_str, __LINE__); \
printf("DEBUG: [%s] [%s]\n", result_buffer, expected_buffer); \
assert(strcmp(result_buffer, expected_buffer) == 0); \
} while(0)
int main(void) {
set_output_color_mode(COLOR_MODE_DISABLE);
TEST_RAISE_GENERIC(raise_debug, LOG_LEVEL_DEBUG, "DEBUG");
TEST_RAISE_GENERIC(raise_log, LOG_LEVEL_LOG, "LOG");
TEST_RAISE_GENERIC(raise_info, LOG_LEVEL_INFO, "INFO");
TEST_RAISE_GENERIC(raise_notice, LOG_LEVEL_NOTICE, "NOTICE");
TEST_RAISE_GENERIC(raise_warn, LOG_LEVEL_WARN, "WARN");
TEST_RAISE_GENERIC(raise_exception, LOG_LEVEL_EXCEPTION, "EXCEPTION");
printf("%s all tests passed.\n", __FILE__);
return 0;
}

View File

@@ -0,0 +1,106 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "hectic.h"
void test_arena_init() {
Arena arena = arena_init(128);
assert(arena.begin != NULL);
assert(arena.current == arena.begin);
assert(arena.capacity == 128);
arena_free(&arena);
}
void test_arena_alloc() {
Arena arena = arena_init(64);
void *ptr1 = arena_alloc(&arena, 16);
assert(ptr1 != NULL);
void *ptr2 = arena_alloc(&arena, 16);
assert(ptr2 != NULL);
raise_debug("%d - %d = %d", (size_t)ptr2, (size_t)ptr1, (char *)ptr2 - (char *)ptr1);
assert((char *)ptr2 - (char *)ptr1 == 16);
arena_free(&arena);
}
void test_arena_alloc_or_null_out_of_memory() {
Arena arena = arena_init(32);
void *ptr = arena_alloc_or_null(&arena, 64);
raise_debug("%d %d %d %d", arena.begin, arena.current, arena.capacity, (size_t)ptr);
assert(ptr == NULL);
arena_free(&arena);
}
void test_arena_reset() {
Arena arena = arena_init(64);
void *ptr1 = arena_alloc(&arena, 16);
arena_reset(&arena);
void *ptr2 = arena_alloc(&arena, 16);
assert(ptr1 == ptr2); // same address after reset
arena_free(&arena);
}
void test_arena_null_init() {
Arena arena = {0};
void *ptr = arena_alloc_or_null(&arena, 32);
assert(ptr != NULL);
arena_free(&arena);
}
void test_arena_strdup() {
Arena arena = arena_init(64);
const char *orig = "Hello, Arena!";
char *copy = arena_strdup(&arena, orig);
assert(copy != NULL);
assert(strcmp(copy, orig) == 0);
arena_free(&arena);
}
void test_arena_repstr() {
Arena arena = arena_init(128);
const char *original = "Hello, World!";
// Replace substring starting at index 5, length 3 (", W") with " -"
// According to the macro logic, the suffix is taken from original[5+3+1] onward.
// That results in: "Hello" + " -" + "rld!" = "Hello -rld!"
char *result = arena_repstr(&arena, original, 5, 3, " -");
assert(strcmp(result, "Hello -rld!") == 0);
arena_free(&arena);
}
void test_arena_overwrite_detection() {
Arena arena = arena_init(128);
char *s1 = arena_alloc(&arena, 6);
strcpy(s1, "hello");
char *s2 = arena_alloc(&arena, 6);
strcpy(s2, "world");
assert(strcmp(s1, "hello") == 0);
assert(strcmp(s2, "world") == 0);
// Force allocation near capacity
void *large = arena_alloc_or_null(&arena, 100);
assert(large != NULL || arena.current == arena.begin + arena.capacity); // If NULL, out of memory
// Check strings again
assert(strcmp(s1, "hello") == 0);
assert(strcmp(s2, "world") == 0);
arena_free(&arena);
}
int main() {
set_output_color_mode(COLOR_MODE_DISABLE);
logger_level(LOG_LEVEL_DEBUG);
test_arena_init();
test_arena_alloc();
test_arena_alloc_or_null_out_of_memory();
test_arena_reset();
test_arena_null_init();
test_arena_strdup();
test_arena_repstr();
test_arena_overwrite_detection();
printf("%s all tests passed.\n", __FILE__);
}

View File

@@ -0,0 +1,138 @@
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "hectic.h"
#define ARENA_SIZE 1024 * 1024
// Test 1: Parse JSON object with a string value.
static void test_parse_json_object(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json = "{\"key\":\"value\"}";
Json *root = json_parse(&arena, &json);
assert(root->type == JSON_OBJECT);
Json *child = root->child;
assert(child && strcmp(child->key, "key") == 0);
assert(child->type == JSON_STRING);
assert(strcmp(child->string, "value") == 0);
arena_free(&arena);
}
// Test 2: Parse JSON number.
static void test_parse_json_number(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json = "42";
Json *root = json_parse(&arena, &json);
assert(root->type == JSON_NUMBER);
assert(root->number == 42);
arena_free(&arena);
}
// Test 3: Parse JSON string.
static void test_parse_json_string(void) {
Arena arena = {0};
const char *json = "\"hello\"";
Json *root = json_parse(&arena, &json);
assert(root->type == JSON_STRING);
assert(strcmp(root->string, "hello") == 0);
arena_free(&arena);
}
// Test 4: Get object items by key.
static void test_get_object_items(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json = "{\"a\":\"1\", \"b\":2}";
Json *root = json_parse(&arena, &json);
Json *item_a = json_get_object_item(root, "a");
assert(item_a && item_a->type == JSON_STRING);
assert(strcmp(item_a->string, "1") == 0);
Json *item_b = json_get_object_item(root, "b");
assert(item_b && item_b->type == JSON_NUMBER);
assert(item_b->number == 2);
arena_free(&arena);
}
// Test 5: Print JSON object.
static void test_print_json_object(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json = "{\"key\":\"value\", \"num\":3.14}";
Json *root = json_parse(&arena, &json);
char *printed = json_to_string(&arena, root);
assert(strstr(printed, "\"key\":") != NULL);
assert(strstr(printed, "\"value\"") != NULL);
assert(strstr(printed, "\"num\":") != NULL);
assert(strstr(printed, "3.14") != NULL);
arena_free(&arena);
}
// Test 6: Print JSON number.
static void test_print_json_number(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json = "123.456";
Json *root = json_parse(&arena, &json);
char *printed = json_to_string(&arena, root);
double val = atof(printed);
assert(val == 123.456);
arena_free(&arena);
}
// Test 7: Print JSON string.
static void test_print_json_string(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json = "\"test string\"";
Json *root = json_parse(&arena, &json);
char *printed = json_to_string(&arena, root);
assert(strcmp(printed, "\"test string\"") == 0);
arena_free(&arena);
}
// Test 8: Nested JSON object.
static void test_nested_json_object(void) {
Arena arena = arena_init(1024 * 1024);
const char *json = "{\"outer\":{\"inner\":100}}";
Json *root = json_parse(&arena, &json);
assert(root != NULL);
assert(root->type == JSON_OBJECT);
Json *outer = json_get_object_item(root, "outer");
assert(outer != NULL);
assert(outer->type == JSON_OBJECT);
Json *inner = json_get_object_item(outer, "inner");
assert(inner != NULL);
assert(inner->type == JSON_NUMBER);
assert(inner->number == 100);
arena_free(&arena);
}
// Test 9: Arena reset and reuse.
static void test_arena_reset_reuse(void) {
Arena arena = arena_init(ARENA_SIZE);
const char *json1 = "{\"key\":\"value\"}";
Json *root1 = json_parse(&arena, &json1);
char *printed1 = json_to_string(&arena, root1);
arena_reset(&arena);
const char *json2 = "\"another test\"";
Json *root2 = json_parse(&arena, &json2);
char *printed2 = json_to_string(&arena, root2);
assert(strcmp(printed2, "\"another test\"") == 0);
arena_free(&arena);
}
int main(void) {
test_parse_json_object();
test_parse_json_number();
test_parse_json_string();
test_get_object_items();
test_print_json_object();
test_print_json_number();
test_print_json_string();
test_nested_json_object();
test_arena_reset_reuse();
printf("%s all tests passed.\n", __FILE__);
return 0;
}