/*
 * File: assets_parser.h
 * Shared JSON/XML node storage and bounded numeric parsing.
 * Implementation include; compiled only through assets.c.
 */

#ifndef ASSETS_PARSER_H
#define ASSETS_PARSER_H

enum { MAX_NODES = 4096 };

typedef struct Node {
    char *key, *text;
    char type;
    struct Node *child, *next, *attrs;
} Node;

static Node nodes[MAX_NODES];
static int node_count;

static Node *new_node(char type)
{
    Node *n;
    if (node_count == MAX_NODES) fail("too many JSON/XML nodes");
    n = &nodes[node_count++];
    n->type = type;
    return n;
}

static void free_nodes(void)
{
    int i;
    for (i = 0; i < node_count; ++i) {
        free(nodes[i].key);
        free(nodes[i].text);
    }
    memset(nodes, 0, sizeof(nodes));
    node_count = 0;
}

static void whitespace(const char **p)
{
    while (isspace((unsigned char)**p)) ++*p;
}

static void expect(const char **p, char c)
{
    whitespace(p);
    if (**p != c) fail("expected '%c' near %.40s", c, *p);
    ++*p;
}

static int hex_digit(char c)
{
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    return -1;
}

static long integer(const char *s, long low, long high, const char *label)
{
    char *end;
    const char *tail;
    long n;
    errno = 0;
    n = strtol(s, &end, 10);
    tail = end;
    whitespace(&tail);
    if (end == s || *tail || errno || n < low || n > high)
        fail("%s: expected integer %ld..%ld, got '%s'", label, low, high, s);
    return n;
}

#endif
