|
| 1 | +#include "object.h" |
| 2 | +#include "vm.h" |
| 3 | +#include "memory.h" |
| 4 | +#include <string.h> |
| 5 | +#include <stdio.h> |
| 6 | + |
| 7 | +static uint32_t hashString(const char* key, int length) { |
| 8 | + uint32_t hash = 2166136261u; |
| 9 | + for (int i = 0; i < length; i++) { |
| 10 | + hash ^= (uint8_t)key[i]; |
| 11 | + hash *= 16777619; |
| 12 | + } |
| 13 | + return hash; |
| 14 | +} |
| 15 | + |
| 16 | +ObjString* takeString(VM* vm, char* chars, int length) { |
| 17 | + uint32_t hash = hashString(chars, length); |
| 18 | + |
| 19 | + ObjString* string = ALLOCATE_OBJ(vm, ObjString, OBJ_STRING); |
| 20 | + string->length = length; |
| 21 | + string->chars = chars; |
| 22 | + string->hash = hash; |
| 23 | + |
| 24 | + return string; |
| 25 | +} |
| 26 | + |
| 27 | +ObjString* copyString(VM* vm, const char* chars, int length) { |
| 28 | + uint32_t hash = hashString(chars, length); |
| 29 | + |
| 30 | + char* heapChars = ALLOCATE(vm, char, length + 1); |
| 31 | + memcpy(heapChars, chars, length); |
| 32 | + heapChars[length] = '\0'; |
| 33 | + |
| 34 | + ObjString* string = ALLOCATE_OBJ(vm, ObjString, OBJ_STRING); |
| 35 | + string->length = length; |
| 36 | + string->chars = heapChars; |
| 37 | + string->hash = hash; |
| 38 | + |
| 39 | + return string; |
| 40 | +} |
| 41 | + |
| 42 | +void printObject(Value value) { |
| 43 | + switch (OBJ_TYPE(value)) { |
| 44 | + case OBJ_STRING: |
| 45 | + printf("%s", AS_CSTRING(value)); |
| 46 | + break; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +void freeObject(VM* vm, Obj* object) { |
| 51 | + switch (object->type) { |
| 52 | + case OBJ_STRING: { |
| 53 | + ObjString* string = (ObjString*)object; |
| 54 | + FREE_ARRAY(vm, char, string->chars, string->length + 1); |
| 55 | + FREE(vm, ObjString, object); |
| 56 | + break; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments