#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <alloca.h>
#include <inttypes.h>

#include "AVLTree.h"
#include "symbol.h"
#include "error.h"

static AVLTree symbolset = {
	NULL,
	NULL,
	NULL,
	(AVLCompare)strcmp,
};

int symcmp(symbol_t a, symbol_t b) {
	uintptr_t a1 = (uintptr_t)a;
	uintptr_t b1 = (uintptr_t)b;
	if (a1 < b1)
		return -1;
	if (a1 > b1)
		return 1;
	return 0;
}

void symbol_dump(void) {
	AVLNode *c;
	for(c = symbolset.head; c; c = c->next)
		fprintf(stderr, "%s\n", (char *)c->item);
}

symbol_t symbol(const char *src) {
	AVLNode *node, *newnode;
	char *s;
	int r;

	if(!src)
		return errno = EINVAL, (symbol_t)NULL;

	r = AVLCloseSearch(&symbolset, src, &node);
	if(!r && node)
		return node->item;

	if((s = xstrdup(src))) {
		if((newnode = AVLInitNode(xmalloc(sizeof(AVLNode)), s))) {
			switch(r) {
				case -1:
					AVLInsertNodeBefore(&symbolset, node, newnode);
				break;
				case 0:
					AVLInsertTopNode(&symbolset, newnode);
				break;
				case 1:
					AVLInsertNodeAfter(&symbolset, node, newnode);
				break;
			}
			return s;
		}
	}
	return NULL;
}

symbol_t nsymbol(const char *src, unsigned length) {
	if (length > 4096)
		error_exit(7, "excessive symbol length\n");
	char *p = alloca(length + 1);
	memcpy(p, src, length);
	p[length] = 0;
	return symbol(p);
}
