From f35b7e32809c5d54850ce75c4dad1a8598235cf0 Mon Sep 17 00:00:00 2001 From: Matthew Sotoudeh Date: Wed, 26 Jul 2023 10:53:27 -0700 Subject: simplify code a fair bit --- type_helpers.c | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) (limited to 'type_helpers.c') diff --git a/type_helpers.c b/type_helpers.c index 0f6b022..cfa2241 100644 --- a/type_helpers.c +++ b/type_helpers.c @@ -1,7 +1,7 @@ #include #include "chibicc.h" -unsigned long hash_type(Type *type) { +static unsigned long hash_type(Type *type) { unsigned long hash = 6997; if (!type) return hash; if (type->hashing) return hash; @@ -76,3 +76,41 @@ disequal: type2->hashing = 0; return 0; } + +static Type **HASH_MAP = 0; +static int CAP_HASH_MAP = 0; +static int N_HASH_MAP = 0; +Type *hash_lookup(Type *type) { + if (!CAP_HASH_MAP) return 0; + + size_t idx = hash_type(type) % CAP_HASH_MAP; + while (HASH_MAP[idx]) { + if (definitely_same_type(HASH_MAP[idx], type)) { + return HASH_MAP[idx]; + } + if (++idx == CAP_HASH_MAP) idx = 0; + } + return 0; +} + +void hash_insert(Type *type) { + if ((N_HASH_MAP + 1) >= (CAP_HASH_MAP / 2)) { + // RESIZE AND REHASH + int old_cap = CAP_HASH_MAP; + Type **old_hash_map = HASH_MAP; + + CAP_HASH_MAP = (CAP_HASH_MAP + 1) * 4; + N_HASH_MAP = 0; + HASH_MAP = calloc(CAP_HASH_MAP, sizeof(HASH_MAP[0])); + for (int i = 0; i < old_cap; i++) + if (old_hash_map[i]) + hash_insert(old_hash_map[i]); + if (old_hash_map) free(old_hash_map); + } + + N_HASH_MAP++; + size_t idx = hash_type(type) % CAP_HASH_MAP; + while (HASH_MAP[idx]) + if (++idx == CAP_HASH_MAP) idx = 0; + HASH_MAP[idx] = type; +} -- cgit v1.2.3