From 3483cc605f6b952d30191fd2f79bdb0e658e0b0f Mon Sep 17 00:00:00 2001 From: kdx Date: Sun, 22 Jan 2023 05:11:18 +0100 Subject: blind scope write --- Makefile | 2 +- Scope.c | 36 ++++++++++++++++++++++++++++++++++++ Scope.h | 17 +++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 Scope.c create mode 100644 Scope.h diff --git a/Makefile b/Makefile index 9c3b944..c4a46ec 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ SRC := $(wildcard *.c) OBJ := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SRC))) NAME := golem CFLAGS := -g -O0 -Wall -Wextra -std=c99 -pedantic -LDFLAGS := +LDFLAGS := -lxxhash all: $(NAME) diff --git a/Scope.c b/Scope.c new file mode 100644 index 0000000..3df00b9 --- /dev/null +++ b/Scope.c @@ -0,0 +1,36 @@ +#include "Scope.h" +#include +#include +#include +#include + +Scope *scope_create(const Scope *parent) +{ + Scope *const scope = malloc(sizeof(Scope)); + if (scope == NULL) { + perror("scope_create"); + return NULL; + } + scope->used = 0; + scope->parent = parent; + return scope; +} + +int scope_insert(Scope *scope, const char *word, int value) +{ + if (scope->used >= SCOPE_WORD_MAX) { + fprintf(stderr, "scope full\n"); + return 1; + } + const XXH32_hash_t hash = XXH32(word, strlen(word), 0); + for (int i = 0; i < scope->used; i++) + if (scope->words_hash[i] == hash) { + fprintf(stderr, "shadowed word\n"); + return 1; + } + scope->words[scope->used] = word; + scope->values[scope->used] = value; + scope->words_hash[scope->used] = hash; + scope->used += 1; + return 0; +} diff --git a/Scope.h b/Scope.h new file mode 100644 index 0000000..e5adacd --- /dev/null +++ b/Scope.h @@ -0,0 +1,17 @@ +#pragma once +#include + +#define SCOPE_WORD_MAX 256 + +/* member strings are borrowed and shouldn't be freed by the node */ +typedef struct Scope Scope; +struct Scope { + int used; + const char *words[SCOPE_WORD_MAX]; + int values[SCOPE_WORD_MAX]; + XXH32_hash_t words_hash[SCOPE_WORD_MAX]; + const Scope *parent; +}; + +Scope *scope_create(const Scope *parent); +int scope_insert(Scope *scope, const char *word, int value); -- cgit v1.2.3