diff --git a/object.c b/object.c index 6029b76..9e726b4 100644 --- a/object.c +++ b/object.c @@ -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; } } diff --git a/table.c b/table.c index 6206bcd..43ffa63 100644 --- a/table.c +++ b/table.c @@ -93,7 +93,7 @@ bool tableSet(Table* table, Value key, Value value) { return isNewKey; } -bool tableDelete(Table* table,Value key) { +bool tableDelete(Table* table, Value key) { if (table->count == 0) return false; // Find the entry. @@ -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; +} diff --git a/table.h b/table.h index a063752..a611807 100644 --- a/table.h +++ b/table.h @@ -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