This commit is contained in:
2026-05-13 11:40:19 -05:00
parent aefc2ff9ad
commit bb8d5bfe34
4 changed files with 53 additions and 8 deletions

View File

@@ -97,8 +97,9 @@ Table* table_new(Heap const* heap);
void table_destroy(Table* t);
size_t table_len(Table* t);
VALUE table_get(Table const* t, VALUE key);
TYC_RESULT table_get(Table const* t, VALUE key, VALUE* value);
void table_set(Table* t, VALUE key, VALUE value);
void table_del(Table* t, VALUE key);
//
// HEAP

View File

@@ -66,7 +66,7 @@ static TABLE_HASH value_hash(VALUE v)
return 0;
}
VALUE table_get(Table const* t, VALUE key)
TYC_RESULT table_get(Table const* t, VALUE key, VALUE* value)
{
if (value_type(key) == TT_STRING) {
const char* skey;
@@ -74,16 +74,18 @@ VALUE table_get(Table const* t, VALUE key)
abort();
khiter_t k = kh_get(TABLE_STR, t->tbl_str, skey);
if (k == kh_end(t->tbl_str))
__builtin_unreachable();
return kh_value(t->tbl_str, k);
return T_ERR_TABLE_KEY_NOT_FOUND;
*value = kh_value(t->tbl_str, k);
} else {
TABLE_HASH hash = value_hash(key);
khiter_t k = kh_get(TABLE_INT, t->tbl_int, hash);
if (k == kh_end(t->tbl_int))
__builtin_unreachable();
return kh_value(t->tbl_int, k);
return T_ERR_TABLE_KEY_NOT_FOUND;
*value = kh_value(t->tbl_int, k);
}
return T_OK;
}
void table_set(Table* t, VALUE key, VALUE value)
@@ -107,3 +109,23 @@ void table_set(Table* t, VALUE key, VALUE value)
kh_value(t->tbl_int, k) = value;
}
}
void table_del(Table* t, VALUE key)
{
if (value_type(key) == TT_STRING) {
const char* skey;
if (heap_get_string(t->heap, value_idx(key), &skey) != T_OK)
abort();
khiter_t k = kh_get(TABLE_STR, t->tbl_str, skey);
if (k == kh_end(t->tbl_str))
return;
kh_del(TABLE_STR, t->tbl_str, k);
} else {
TABLE_HASH hash = value_hash(key);
khiter_t k = kh_get(TABLE_INT, t->tbl_int, hash);
if (k == kh_end(t->tbl_int))
return;
kh_del(TABLE_INT, t->tbl_int, k);
}
}

View File

@@ -9,6 +9,7 @@ typedef enum {
T_OK = 0,
T_ERR_STACK_UNDERFLOW = -1, T_ERR_STACK_FP_UNDERFLOW = -2, T_ERR_STACK_ACCESS_OUT_OF_RANGE = -3,
T_ERR_HEAP_KEY_NOT_FOUND = -10,
T_ERR_TABLE_KEY_NOT_FOUND = -20,
} TYC_RESULT;
#endif //TYCHE_TYCHE_H

View File

@@ -113,6 +113,27 @@ int main()
array_destroy(a);
}
{
printf("### Table - integer index\n");
Heap* h = heap_new();
Table* t = table_new(h);
table_set(t, create_value_integer(10), create_value_integer(100));
table_set(t, create_value_integer(20), create_value_integer(200));
VALUE v;
assert(table_get(t, create_value_integer(10), &v) == T_OK); assert(value_integer(v) == 100);
assert(table_get(t, create_value_integer(20), &v) == T_OK); assert(value_integer(v) == 200);
table_del(t, create_value_integer(20));
assert(table_get(t, create_value_integer(10), &v) == T_OK);
assert(table_get(t, create_value_integer(20), &v) == T_ERR_TABLE_KEY_NOT_FOUND);
table_destroy(t);
heap_destroy(h);
}
{
printf("### Heap - strings\n");