Hash values aren't printed as "hash" anymore

This commit is contained in:
pjht 2019-06-03 07:02:03 -05:00
parent f7afaf34aa
commit 701b9aad40
3 changed files with 39 additions and 3 deletions

View File

@ -88,7 +88,19 @@ void printObject(Value value) {
printf("]");
break;
case OBJ_HASH:
printf("hash");
printf("{");
Table* hash=AS_HASH(value);
Entry** entries=getEntries(hash);
for (int i=0;entries[i]!=NULL;i++) {
Entry* entry=entries[i];
printValue(entry->key);
printf("=>");
printValue(entry->value);
if (entries[i+1]!=NULL) {
printf(", ");
}
}
printf("}");
break;
}
}

24
table.c
View File

@ -137,3 +137,27 @@ ObjString* tableFindString(Table* table, const char* chars, int length, uint32_t
}
return NULL;
}
static int tableLength(Table* table) {
int length = 0;
for (int i = 0; i < table->capacity; i++) {
Entry entry = table->entries[i];
if (!IS_EMPTY(entry.key)) length++;
}
return length;
}
Entry** getEntries(Table* table) {
int length = tableLength(table);
Entry** entries = malloc(sizeof(Entry*)*(length+1));
entries[length]=NULL;
int j=0;
for (int i=0; i < table->capacity; i++) {
Entry* entry = &table->entries[i];
if (!IS_EMPTY(entry->key)) {
entries[j]=entry;
j++;
}
}
return entries;
}

View File

@ -22,5 +22,5 @@ bool tableSet(Table* table, Value key, Value value);
bool tableDelete(Table* table, Value key);
void tableAddAll(Table* from, Table* to);
ObjString* tableFindString(Table* table, const char* chars, int length, uint32_t hash);
Entry** getEntries(Table* table);
#endif